code
stringlengths
2
1.05M
/** * 一些常用的函数方法封装 */ var Util = { /** * 事件绑定 * @param element HTMLElement 元素节点 * @param type String 事件名称 * @param handler Funciton 事件执行的函数 */ addEvent: function(element, type, handler) { if (!element) { return; } if (element instanceof Array) { for (var i = 0, j = element.length; i < j; i++) { this.addEvent(element[i], type, handler); } } if (type instanceof Array) { for (var i = 0, j = type.length; i < j; i++) { this.addEvent(element, type[i], handler); } } if (element.addEventListener) { element.addEventListener(type, handler, false); } else if (element.attachEvent) { element.attachEvent('on' + type, function() { handler.call(element); }); } else { element['on' + type] = handler; } }, /** * 事件移除 * @param element HTMLElement 元素节点 * @param type String 事件名称 * @param handler Funciton 事件执行的函数 */ removeEvent: function(element, type, handler) { if (!element) { return; } if (element instanceof Array) { for (var i = 0, j = element.length; i < j; i++) { this.removeEvent(element[i], type, handler); } } if (type instanceof Array) { for (var i = 0, j = type.length; i < j; i++) { this.removeEvent(element, type[i], handler); } } if (element.removeEventListener) { element.removeEventListener(type, handler, false); } else if (element.detachEvent) { element.detachEvent('on' + type, function() { handler.call(element); }); } else { element['on' + type] = null; } }, /** * 事件冒泡阻止 * @param event EVENTOBJ 事件对象 */ stopPropagation: function(event) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } }, /** * 获取事件对象 * @param event EVENTOBJ 事件对象 * @return EVENTOBJ 事件对象 */ getEvent: function(event) { return event || window.event; }, /** * 获取事件的目标DOM * @param event EVENTOBJ 事件对象 * @return HTMLElement 对象 */ getTarget: function(event) { return event.target || event.srcElement; }, /** * 获取鼠标坐标 * @param event EVENTOBJ 事件对象 * @return Object 当前鼠标坐标 */ getCoords: function(event) { if (event.pageX || event.pageY) { return { x: event.pageX, y: event.pageY }; } else if (event.x || event.y) { return { x: event.x, y: event.y }; } var doc = document.compatMode === 'BackCompat' ? document.body : document.documentElement; return { x: event.clientX + doc.scrollLect - doc.clientLeft, y: event.clientY + doc.scrollTop - doc.clientTop }; }, /** * ajax操作简易版 * @param method String 请求方法类型 * @param url String 请求地址 * @param async Boolean 是否异步 * @param info Object 请求带的参数数据 * @param callback Funciton 请求成功的回调函数 * @return */ ajax: function(method, url, async, info, callback) { var xhr; (function xhrMaker(){ try { xhr = new XMLHTTPRequest(); } catch (e) { try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) { try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) { xhr = null; } } } })(); if (!xhr) { return; } xhr.open(method, url, async); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200) { callback(xhr.responseText); } } }; if (method.toUpperCase() === 'POST') { xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); } xhr.send(Util.serialize(info)); }, /** * 序列化参数 * @param data Object 要序列化的json数据 * @return String 字符串形式的数据 */ serialize: function(data) { var str = []; for (var item in data) { if (data.hasOwnProperty(item)) { str.push(item + '=' + data[item]); } } return str.join('&'); }, // 获取text getText: function(element) { return element.textContent || element.innerText; }, // 设置text setText: function(element, text) { if (element.textContent) { element.textContent = text; } else { element.innerText = text; } }, // 动态加载脚本文件 addScript: function(src) { var script = document.createElement('script'); script.type = 'text/javascipt'; script.src = src; document.body.appendChild(script); }, // 获取url参数对应值 getArgValue: function(arg) { var search = location.href.slice(location.href.indexOf('?') + 1); if (!search) { return null; } var items = search.split('&'); for (var i = 0, j = items.length; i < j; i++) { var item = items[i].split('='); if (item[0] === arg) { return item[1]; } } return null; }, // xss 过滤 xss: function(str, type) { // 空过滤 if (!str) { return str === 0 ? '0' : ''; } switch (type) { case 'none': // 过度方案 return '' + str; break; case 'html': // 过滤html字符串中的xss return str.replace(/[&'"<>\/\\\-\x00-\x09\x0b-\x0c\x1f\x80-\xff]/g, function(r){ return '&#' + r.charCodeAt(0) + ';'; }).replace(/ /g, '&nbsp;').replace(/\r\n/g, '<br />').replace(/\n/g,'<br />').replace(/\r/g,'<br />'); break; case 'htmlEp': // 过滤DOM节点属性中的XSS return str.replace(/[&'"<>\/\\\-\x00-\x1f\x80-\xff]/g, function(r){ return '&#' + r.charCodeAt(0) + ';'; }); break; case 'url': // 过滤url return escape(str).replace(/\+/g, '%2B'); break; case 'miniUrl': return str.replace(/%/g, '%25'); break; case 'script': return str.replace(/[\\"']/g, function(r){ return '\\' + r; }).replace(/%/g, '\\x25').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\x01/g, '\\x01'); break; case 'reg': return str.replace(/[\\\^\$\*\+\?\{\}\.\(\)\[\]]/g, function(a){ return '\\' + a; }); break; default: return escape(str).replace(/[&'"<>\/\\\-\x00-\x09\x0b-\x0c\x1f\x80-\xff]/g, function(r){ return '&#' + r.charCodeAt(0) + ';'; }).replace(/ /g, '&nbsp;').replace(/\r\n/g, '<br />').replace(/\n/g,'<br />').replace(/\r/g,'<br />'); break; } }, // html解码 decodeHtml: function(content) { if (content == null) { return ''; } return Util.strReplace(content, { "&amp;" : '&', "&quot;" : '\"', "\\'" : '\'', "&lt;" : '<', "&gt;" : '>', "&nbsp;" : ' ', "&#39;" : '\'', "&#09;" : '\t', "&#40;" : '(', "&#41;" : ')', "&#42;" : '*', "&#43;" : '+', "&#44;" : ',', "&#45;" : '-', "&#46;" : '.', "&#47;" : '/', "&#63;" : '?', "&#92;" : '\\', "<BR>" : '\n' }); }, // 字符串替换 strReplace: function(str, re, rt) { if (rt != undefined) { replace(re, rt); } else { for (var key in re) { replace(key, re[key]); } } function replace(a, b) { var arr = str.split(a); str = arr.join(b); } return str; }, // 格式化时间 formatDate: function(date, formatStr) { var arrWeek = ['日','一','二','三','四','五','六']; var str = formatStr.replace(/yyyy|YYYY/, date.getFullYear()) .replace(/yy|YY/, Util.addZero(date.getFullYear() % 100, 2) ) .replace(/mm|MM/, Util.addZero(date.getMonth() + 1, 2)) .replace(/m|M/g, date.getMonth() + 1) .replace(/dd|DD/, Util.addZero(date.getDate(), 2) ) .replace(/d|D/g, date.getDate()) .replace(/hh|HH/, Util.addZero(date.getHours(), 2)) .replace(/h|H/g, date.getHours()) .replace(/ii|II/, Util.addZero(date.getMinutes(), 2)) .replace(/i|I/g, date.getMinutes()) .replace(/ss|SS/, Util.addZero(date.getSeconds(), 2)) .replace(/s|S/g, date.getSeconds()) .replace(/w/g, date.getDay()) .replace(/W/g, arrWeek[date.getDay()]); return str; }, // 前补0 addZero: function(v, size) { for(var i = 0,len = size - (v + '').length; i < len; i++) { v = '0' + v; } return v + ''; }, /** * 根据cookie名称获取相应值 * @param name String cookie名称 * @return String cookie值 */ getCookie: function(name) { var reg = new RegExp('(^| )' + name + '(?:=([^;]*))?(;|$)'); var val = document.cookie.match(reg); return val ? (val[2] ? unescape(val[2]) : '') : ''; }, /** * 设置cookie * @param name String cookie名称 * @param value String cookie值 * @param expires Number 过期时间(分钟) * @param domain String 域 * @param path String 路径 * @param secure Boolean 是否设置为安全 */ setCookie: function(name, value, expires, path, domain, secure) { if (!name || !value) { return; } var exp = new Date(), expires = arguments[2] || null, path = arguments[3] || '/', domain = arguments[4] || null, secure = arguments[5] || false; expires ? exp.setMinutes(exp.getMinutes() + parseInt(expires)) : ''; document.cookie = name + '=' + escape(value) + (expires ? ';expires=' + exp.toGMTString() : '') + (path ? ';path=' + path : '') + (domain ? ';domain=' + domain : '') + (secure ? ';secure' : ''); }, /** * 删除cookie * @param name String cookie名称 * @param domain String 域 * @param path String 路径 * @param secure Boolean 是否设置为安全 */ delCookie: function(name, path, domain, secure) { var val = Util.getCookie(name); if (val) { var exp = new Date(), path = path || '/'; exp.setMinutes(exp.getMinutes() - 1000); document.cookie = name + '=;expires=' + exp.toGMTString() + (path ? ';path=' + path : '') + (domain ? ';domain=' + domain : '') + (secure ? ';secure' : ''); } }, /** * 移动DOM对象节点 * @param {[type]} curDom 当前触发事件的dom对象 * @param {[type]} targetDom 触发移动操作后将要移动的dom对象 */ bindObjMove: function(curDom, targetDom, tag) { if (!curDom || !targetDom) { return; } var curPos = diffPos = []; curDom.onmousedown = function(e) { e = e || window.event; curPos = [ targetDom.offsetLeft, targetDom.offsetTop // parseInt(targetDom.style.left, 10) ? parseInt(targetDom.style.left, 10) : 0, // parseInt(targetDom.style.top, 10) ? parseInt(targetDom.style.top, 10) : 0 ]; diffPos = [ Util.getMousePosition(e)[0] - curPos[0], Util.getMousePosition(e)[1] - curPos[1] ]; curDom.onmouseup = function() { curDom.onmousemove = null; }; curDom.onmousemove = function(e) { try { var e = e || window.event; if (tag === 'modal') { targetDom.style.position = 'absolute'; } targetDom.style.marginLeft = '0px'; targetDom.style.marginTop = '0px'; targetDom.style.left = (Util.getMousePosition(e)[0] - diffPos[0]) + 'px'; targetDom.style.top = Util.getMousePosition(e)[1] - diffPos[1] + 'px'; } catch (e) { console.log(e); } }; return false; }; }, /* 获取鼠标坐标 */ getMousePosition: function(e) { e = e || window.event; var pos = []; if (typeof e.pageX != 'undefined') { pos = [e.pageX, e.pageY]; } else if (typeof e.clientX != 'undefined') { pos = [e.clientX + Util.getScrollPosition()[0], e.clientY + Util.getScrollPosition()[1]]; } return pos; }, /* 获取滚动条位置 */ getScrollPosition: function(e) { var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft; var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; return [ scrollLeft ? scrollLeft : 0, scrollTop ? scrollTop : 0 ]; } }; try { module.exports = Util; } catch (e) { }
'use strict'; var Controller = skit.platform.Controller; var net = skit.platform.net; // This is the base controller located in our "library" module. var BaseController = library.BaseController; // This loads Home.html so we can render the main content for the page. var html = __module__.html; // Specifying BaseController here makes BaseController the parent Controller: // It modify our body HTML, title, etc. See that module for more information. return Controller.create(BaseController, { __preload__: function(onLoaded) { // This is where you load any data necessary for the initial page render. // net.send() works from the client and server, exactly the same way. net.send('https://cluster-static.s3.amazonaws.com/skit/example.json', { success: function(response) { this.items = response.body['items']; }, error: function() { this.items = [{title: 'Oops!', description: 'Could not load the example data.'}]; }, complete: function() { onLoaded(); }, context: this }) }, __load__: function() { // This is called on the server and client in order to setup the Controller // object after the preload has completed. }, __title__: function() { return 'Home'; }, __body__: function() { return html({ items: this.items }); }, __ready__: function(container) { // This is where the client lifecycle begins; we hook up event listeners, // format things in the browser if necessary, etc. // var $link = dom.get('a.foo'); // events.bind($link, 'click', this.onClickLink, this); } });
define({ "_widgetLabel": "Mesura" });
/* Copyright (c) 2007 Brian Dillard and Brad Neuberg: Brian Dillard | Project Lead | bdillard@pathf.com | http://blogs.pathf.com/agileajax/ Brad Neuberg | Original Project Creator | http://codinginparadise.org 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. */ /* dhtmlHistory: An object that provides history, history data, and bookmarking for DHTML and Ajax applications. dependencies: * the historyStorage object included in this file. */ window.dhtmlHistory = { /*Public: User-agent booleans*/ isIE: false, isOpera: false, isSafari: false, isKonquerer: false, isGecko: false, isSupported: false, /*Public: Create the DHTML history infrastructure*/ create: function(options) { /* options - object to store initialization parameters options.debugMode - boolean that causes hidden form fields to be shown for development purposes. options.toJSON - function to override default JSON stringifier options.fromJSON - function to override default JSON parser */ var that = this; /*set user-agent flags*/ var UA = navigator.userAgent.toLowerCase(); var platform = navigator.platform.toLowerCase(); var vendor = navigator.vendor || ""; if (vendor === "KDE") { this.isKonqueror = true; this.isSupported = false; } else if (typeof window.opera !== "undefined") { this.isOpera = true; this.isSupported = true; } else if (typeof document.all !== "undefined") { this.isIE = true; this.isSupported = true; } else if (vendor.indexOf("Apple Computer, Inc.") > -1 && parseFloat(navigator.version) < 3.0) { this.isSafari = true; this.isSupported = (platform.indexOf("mac") > -1); } else if (UA.indexOf("gecko") != -1) { this.isGecko = true; this.isSupported = true; } /*Set up the historyStorage object; pass in init parameters*/ window.historyStorage.setup(options); /*Execute browser-specific setup methods*/ if (this.isSafari) { this.createSafari(); } else if (this.isOpera) { this.createOpera(); } /*Get our initial location*/ var initialHash = this.getCurrentLocation(); /*Save it as our current location*/ this.currentLocation = initialHash; /*Now that we have a hash, create IE-specific code*/ if (this.isIE) { this.createIE(initialHash); } /*Add an unload listener for the page; this is needed for FF 1.5+ because this browser caches all dynamic updates to the page, which can break some of our logic related to testing whether this is the first instance a page has loaded or whether it is being pulled from the cache*/ var unloadHandler = function() { that.firstLoad = null; }; this.addEventListener(window,'unload',unloadHandler); /*Determine if this is our first page load; for IE, we do this in this.iframeLoaded(), which is fired on pageload. We do it there because we have no historyStorage at this point, which only exists after the page is finished loading in IE*/ if (this.isIE) { /*The iframe will get loaded on page load, and we want to ignore this fact*/ this.ignoreLocationChange = true; } else { if (!historyStorage.hasKey(this.PAGELOADEDSTRING)) { /*This is our first page load, so ignore the location change and add our special history entry*/ this.ignoreLocationChange = true; this.firstLoad = true; historyStorage.put(this.PAGELOADEDSTRING, true); } else { /*This isn't our first page load, so indicate that we want to pay attention to this location change*/ this.ignoreLocationChange = false; /*For browsers other than IE, fire a history change event; on IE, the event will be thrown automatically when its hidden iframe reloads on page load. Unfortunately, we don't have any listeners yet; indicate that we want to fire an event when a listener is added.*/ this.fireOnNewListener = true; } } /*Other browsers can use a location handler that checks at regular intervals as their primary mechanism; we use it for IE as well to handle an important edge case; see checkLocation() for details*/ var locationHandler = function() { that.checkLocation(); }; setInterval(locationHandler, 100); }, /*Public: Initialize our DHTML history. You must call this after the page is finished loading.*/ initialize: function() { /*IE needs to be explicitly initialized. IE doesn't autofill form data until the page is finished loading, so we have to wait*/ if (this.isIE) { /*If this is the first time this page has loaded*/ if (!historyStorage.hasKey(this.PAGELOADEDSTRING)) { /*For IE, we do this in initialize(); for other browsers, we do it in create()*/ this.fireOnNewListener = false; this.firstLoad = true; historyStorage.put(this.PAGELOADEDSTRING, true); } /*Else if this is a fake onload event*/ else { this.fireOnNewListener = true; this.firstLoad = false; } } }, /*Public: Adds a history change listener. Note that only one listener is supported at this time.*/ addListener: function(listener) { this.listener = listener; /*If the page was just loaded and we should not ignore it, fire an event to our new listener now*/ if (this.fireOnNewListener) { this.fireHistoryEvent(this.currentLocation); this.fireOnNewListener = false; } }, /*Public: Generic utility function for attaching events*/ addEventListener: function(o,e,l) { if (o.addEventListener) { o.addEventListener(e,l,false); } else if (o.attachEvent) { o.attachEvent('on'+e,function() { l(window.event); }); } }, /*Public: Add a history point.*/ add: function(newLocation, historyData) { if (this.isSafari) { /*Remove any leading hash symbols on newLocation*/ newLocation = this.removeHash(newLocation); /*Store the history data into history storage*/ historyStorage.put(newLocation, historyData); /*Save this as our current location*/ this.currentLocation = newLocation; /*Change the browser location*/ window.location.hash = newLocation; /*Save this to the Safari form field*/ this.putSafariState(newLocation); } else { /*Most browsers require that we wait a certain amount of time before changing the location, such as 200 MS; rather than forcing external callers to use window.setTimeout to account for this, we internally handle it by putting requests in a queue.*/ var that = this; var addImpl = function() { /*Indicate that the current wait time is now less*/ if (that.currentWaitTime > 0) { that.currentWaitTime = that.currentWaitTime - that.waitTime; } /*Remove any leading hash symbols on newLocation*/ newLocation = that.removeHash(newLocation); /*IE has a strange bug; if the newLocation is the same as _any_ preexisting id in the document, then the history action gets recorded twice; throw a programmer exception if there is an element with this ID*/ if (document.getElementById(newLocation) && that.debugMode) { var e = "Exception: History locations can not have the same value as _any_ IDs that might be in the document," + " due to a bug in IE; please ask the developer to choose a history location that does not match any HTML" + " IDs in this document. The following ID is already taken and cannot be a location: " + newLocation; throw new Error(e); } /*Store the history data into history storage*/ historyStorage.put(newLocation, historyData); /*Indicate to the browser to ignore this upcomming location change since we're making it programmatically*/ that.ignoreLocationChange = true; /*Indicate to IE that this is an atomic location change block*/ that.ieAtomicLocationChange = true; /*Save this as our current location*/ that.currentLocation = newLocation; /*Change the browser location*/ window.location.hash = newLocation; /*Change the hidden iframe's location if on IE*/ if (that.isIE) { that.iframe.src = "blank.html?" + newLocation; } /*End of atomic location change block for IE*/ that.ieAtomicLocationChange = false; }; /*Now queue up this add request*/ window.setTimeout(addImpl, this.currentWaitTime); /*Indicate that the next request will have to wait for awhile*/ this.currentWaitTime = this.currentWaitTime + this.waitTime; } }, /*Public*/ isFirstLoad: function() { return this.firstLoad; }, /*Public*/ getVersion: function() { return "0.6"; }, /*Get browser's current hash location; for Safari, read value from a hidden form field*/ /*Public*/ getCurrentLocation: function() { var r = (this.isSafari ? this.getSafariState() : this.getCurrentHash() ); return r; }, /*Public: Manually parse the current url for a hash; tip of the hat to YUI*/ getCurrentHash: function() { var r = window.location.href; var i = r.indexOf("#"); return (i >= 0 ? r.substr(i+1) : "" ); }, /*- - - - - - - - - - - -*/ /*Private: Constant for our own internal history event called when the page is loaded*/ PAGELOADEDSTRING: "DhtmlHistory_pageLoaded", /*Private: Our history change listener.*/ listener: null, /*Private: MS to wait between add requests - will be reset for certain browsers*/ waitTime: 200, /*Private: MS before an add request can execute*/ currentWaitTime: 0, /*Private: Our current hash location, without the "#" symbol.*/ currentLocation: null, /*Private: Hidden iframe used to IE to detect history changes*/ iframe: null, /*Private: Flags and DOM references used only by Safari*/ safariHistoryStartPoint: null, safariStack: null, safariLength: null, /*Private: Flag used to keep checkLocation() from doing anything when it discovers location changes we've made ourselves programmatically with the add() method. Basically, add() sets this to true. When checkLocation() discovers it's true, it refrains from firing our listener, then resets the flag to false for next cycle. That way, our listener only gets fired on history change events triggered by the user via back/forward buttons and manual hash changes. This flag also helps us set up IE's special iframe-based method of handling history changes.*/ ignoreLocationChange: null, /*Private: A flag that indicates that we should fire a history change event when we are ready, i.e. after we are initialized and we have a history change listener. This is needed due to an edge case in browsers other than IE; if you leave a page entirely then return, we must fire this as a history change event. Unfortunately, we have lost all references to listeners from earlier, because JavaScript clears out.*/ fireOnNewListener: null, /*Private: A variable that indicates whether this is the first time this page has been loaded. If you go to a web page, leave it for another one, and then return, the page's onload listener fires again. We need a way to differentiate between the first page load and subsequent ones. This variable works hand in hand with the pageLoaded variable we store into historyStorage.*/ firstLoad: null, /*Private: A variable to handle an important edge case in IE. In IE, if a user manually types an address into their browser's location bar, we must intercept this by calling checkLocation() at regular intervals. However, if we are programmatically changing the location bar ourselves using the add() method, we need to ignore these changes in checkLocation(). Unfortunately, these changes take several lines of code to complete, so for the duration of those lines of code, we set this variable to true. That signals to checkLocation() to ignore the change-in-progress. Once we're done with our chunk of location-change code in add(), we set this back to false. We'll do the same thing when capturing user-entered address changes in checkLocation itself.*/ ieAtomicLocationChange: null, /*Private: Create IE-specific DOM nodes and overrides*/ createIE: function(initialHash) { /*write out a hidden iframe for IE and set the amount of time to wait between add() requests*/ this.waitTime = 400;/*IE needs longer between history updates*/ var styles = (historyStorage.debugMode ? 'width: 800px;height:80px;border:1px solid black;' : historyStorage.hideStyles ); var iframeID = "rshHistoryFrame"; var iframeHTML = '<iframe frameborder="0" id="' + iframeID + '" style="' + styles + '" src="blank.html?' + initialHash + '"></iframe>'; document.write(iframeHTML); this.iframe = document.getElementById(iframeID); }, /*Private: Create Opera-specific DOM nodes and overrides*/ createOpera: function() { this.waitTime = 400;/*Opera needs longer between history updates*/ var imgHTML = '<img src="javascript:location.href=\'javascript:dhtmlHistory.checkLocation();\';" style="' + historyStorage.hideStyles + '" />'; document.write(imgHTML); }, /*Private: Create Safari-specific DOM nodes and overrides*/ createSafari: function() { var formID = "rshSafariForm"; var stackID = "rshSafariStack"; var lengthID = "rshSafariLength"; var formStyles = historyStorage.debugMode ? historyStorage.showStyles : historyStorage.hideStyles; var inputStyles = (historyStorage.debugMode ? 'width:800px;height:20px;border:1px solid black;margin:0;padding:0;' : historyStorage.hideStyles ); var safariHTML = '<form id="' + formID + '" style="' + formStyles + '">' + '<input type="text" style="' + inputStyles + '" id="' + stackID + '" value="[]"/>' + '<input type="text" style="' + inputStyles + '" id="' + lengthID + '" value=""/>' + '</form>'; document.write(safariHTML); this.safariStack = document.getElementById(stackID); this.safariLength = document.getElementById(lengthID); if (!historyStorage.hasKey(this.PAGELOADEDSTRING)) { this.safariHistoryStartPoint = history.length; this.safariLength.value = this.safariHistoryStartPoint; } else { this.safariHistoryStartPoint = this.safariLength.value; } }, /*Private: Safari method to read the history stack from a hidden form field*/ getSafariStack: function() { var r = this.safariStack.value; return historyStorage.fromJSON(r); }, /*Private: Safari method to read from the history stack*/ getSafariState: function() { var stack = this.getSafariStack(); var state = stack[history.length - this.safariHistoryStartPoint - 1]; return state; }, /*Private: Safari method to write the history stack to a hidden form field*/ putSafariState: function(newLocation) { var stack = this.getSafariStack(); stack[history.length - this.safariHistoryStartPoint] = newLocation; this.safariStack.value = historyStorage.toJSON(stack); }, /*Private: Notify the listener of new history changes.*/ fireHistoryEvent: function(newHash) { /*extract the value from our history storage for this hash*/ var historyData = historyStorage.get(newHash); /*call our listener*/ this.listener.call(null, newHash, historyData); }, /*Private: See if the browser has changed location. This is the primary history mechanism for Firefox. For IE, we use this to handle an important edge case: if a user manually types in a new hash value into their IE location bar and press enter, we want to to intercept this and notify any history listener.*/ checkLocation: function() { /*Ignore any location changes that we made ourselves for browsers other than IE*/ if (!this.isIE && this.ignoreLocationChange) { this.ignoreLocationChange = false; return; } /*If we are dealing with IE and we are in the middle of making a location change from an iframe, ignore it*/ if (!this.isIE && this.ieAtomicLocationChange) { return; } /*Get hash location*/ var hash = this.getCurrentLocation(); /*Do nothing if there's been no change*/ if (hash == this.currentLocation) { return; } /*In IE, users manually entering locations into the browser; we do this by comparing the browser's location against the iframe's location; if they differ, we are dealing with a manual event and need to place it inside our history, otherwise we can return*/ this.ieAtomicLocationChange = true; if (this.isIE && this.getIframeHash() != hash) { this.iframe.src = "blank.html?" + hash; } else if (this.isIE) { /*the iframe is unchanged*/ return; } /*Save this new location*/ this.currentLocation = hash; this.ieAtomicLocationChange = false; /*Notify listeners of the change*/ this.fireHistoryEvent(hash); }, /*Private: Get the current location of IE's hidden iframe.*/ getIframeHash: function() { var doc = this.iframe.contentWindow.document; var hash = String(doc.location.search); if (hash.length == 1 && hash.charAt(0) == "?") { hash = ""; } else if (hash.length >= 2 && hash.charAt(0) == "?") { hash = hash.substring(1); } return hash; }, /*Private: Remove any leading hash that might be on a location.*/ removeHash: function(hashValue) { var r; if (hashValue === null || hashValue === undefined) { r = null; } else if (hashValue === "") { r = ""; } else if (hashValue.length == 1 && hashValue.charAt(0) == "#") { r = ""; } else if (hashValue.length > 1 && hashValue.charAt(0) == "#") { r = hashValue.substring(1); } else { r = hashValue; } return r; }, /*Private: For IE, tell when the hidden iframe has finished loading.*/ iframeLoaded: function(newLocation) { /*ignore any location changes that we made ourselves*/ if (this.ignoreLocationChange) { this.ignoreLocationChange = false; return; } /*Get the new location*/ var hash = String(newLocation.search); if (hash.length == 1 && hash.charAt(0) == "?") { hash = ""; } else if (hash.length >= 2 && hash.charAt(0) == "?") { hash = hash.substring(1); } /*Keep the browser location bar in sync with the iframe hash*/ window.location.hash = hash; /*Notify listeners of the change*/ this.fireHistoryEvent(hash); } }; /* historyStorage: An object that uses a hidden form to store history state across page loads. The mechanism for doing so relies on the fact that browsers save the text in form data for the life of the browser session, which means the text is still there when the user navigates back to the page. This object can be used independently of the dhtmlHistory object for caching of Ajax session information. dependencies: * json2007.js (included in a separate file) or alternate JSON methods passed in through an options bundle. */ window.historyStorage = { /*Public: Set up our historyStorage object for use by dhtmlHistory or other objects*/ setup: function(options) { /* options - object to store initialization parameters - passed in from dhtmlHistory or directly into historyStorage options.debugMode - boolean that causes hidden form fields to be shown for development purposes. options.toJSON - function to override default JSON stringifier options.fromJSON - function to override default JSON parser */ /*process init parameters*/ if (typeof options !== "undefined") { if (options.debugMode) { this.debugMode = options.debugMode; } if (options.toJSON) { this.toJSON = options.toJSON; } if (options.fromJSON) { this.fromJSON = options.fromJSON; } } /*write a hidden form and textarea into the page; we'll stow our history stack here*/ var formID = "rshStorageForm"; var textareaID = "rshStorageField"; var formStyles = this.debugMode ? historyStorage.showStyles : historyStorage.hideStyles; var textareaStyles = (historyStorage.debugMode ? 'width: 800px;height:80px;border:1px solid black;' : historyStorage.hideStyles ); var textareaHTML = '<form id="' + formID + '" style="' + formStyles + '">' + '<textarea id="' + textareaID + '" style="' + textareaStyles + '"></textarea>' + '</form>'; document.write(textareaHTML); this.storageField = document.getElementById(textareaID); if (typeof window.opera !== "undefined") { this.storageField.focus();/*Opera needs to focus this element before persisting values in it*/ } }, /*Public*/ put: function(key, value) { this.assertValidKey(key); /*if we already have a value for this, remove the value before adding the new one*/ if (this.hasKey(key)) { this.remove(key); } /*store this new key*/ this.storageHash[key] = value; /*save and serialize the hashtable into the form*/ this.saveHashTable(); }, /*Public*/ get: function(key) { this.assertValidKey(key); /*make sure the hash table has been loaded from the form*/ this.loadHashTable(); var value = this.storageHash[key]; if (value === undefined) { value = null; } return value; }, /*Public*/ remove: function(key) { this.assertValidKey(key); /*make sure the hash table has been loaded from the form*/ this.loadHashTable(); /*delete the value*/ delete this.storageHash[key]; /*serialize and save the hash table into the form*/ this.saveHashTable(); }, /*Public: Clears out all saved data.*/ reset: function() { this.storageField.value = ""; this.storageHash = {}; }, /*Public*/ hasKey: function(key) { this.assertValidKey(key); /*make sure the hash table has been loaded from the form*/ this.loadHashTable(); return (typeof this.storageHash[key] !== "undefined"); }, /*Public*/ isValidKey: function(key) { return (typeof key === "string"); }, /*Public - CSS strings utilized by both objects to hide or show behind-the-scenes DOM elements*/ showStyles: 'border:0;margin:0;padding:0;', hideStyles: 'left:-1000px;top:-1000px;width:1px;height:1px;border:0;position:absolute;', /*Public - debug mode flag*/ debugMode: false, /*- - - - - - - - - - - -*/ /*Private: Our hash of key name/values.*/ storageHash: {}, /*Private: If true, we have loaded our hash table out of the storage form.*/ hashLoaded: false, /*Private: DOM reference to our history field*/ storageField: null, /*Private: Assert that a key is valid; throw an exception if it not.*/ assertValidKey: function(key) { var isValid = this.isValidKey(key); if (!isValid && this.debugMode) { throw new Error("Please provide a valid key for window.historyStorage. Invalid key = " + key + "."); } }, /*Private: Load the hash table up from the form.*/ loadHashTable: function() { if (!this.hashLoaded) { var serializedHashTable = this.storageField.value; if (serializedHashTable !== "" && serializedHashTable !== null) { this.storageHash = this.fromJSON(serializedHashTable); this.hashLoaded = true; } } }, /*Private: Save the hash table into the form.*/ saveHashTable: function() { this.loadHashTable(); var serializedHashTable = this.toJSON(this.storageHash); this.storageField.value = serializedHashTable; }, /*Private: Bridges for our JSON implementations - both rely on 2007 JSON.org library - can be overridden by options bundle*/ toJSON: function(o) { return o.toJSONString(); }, fromJSON: function(s) { return s.parseJSON(); } };
/* * The Django-tribune jQuery plugin * * TODO: This lack of : * * Use the header "X-Post-Id" to retrieve owned message posted and enable owner * mark for anonymous; * * "clock_store" cleaning when dropping messages from the list * * User settings panel; * * Think about themes usage; */ DEBUG = false; // To enable/disable message logs with "console.log()" // Array Remove - By John Resig (MIT Licensed) Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); }; /* * The djangotribune plugin * * Usage for first init : * * $(".mycontainer").djangotribune({options...}); */ (function($){ /* * Plugin extensions calling logic */ $.fn.djangotribune = function(method) { if ( extensions[method] ) { return extensions[method].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return extensions.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.djangotribune' ); } }; /* * Timer methods and registries */ var Timer = { timers : {}, /* * Get the timer from registry */ getTimer : function(key) { var timerObj; try { timerObj = this.timers[key]; } catch (e) { timerObj = null; } return timerObj; }, /* * Stop timer */ stopTimer : function(key) { var timerObj = this.getTimer(key); if (timerObj !== null) { if(DEBUG) console.log("Timer '"+key+"' cleared"); clearInterval(timerObj); this.timers[key] = null; } }, /* * Set a new timer */ setTimer : function(key, funcString, milliseconds, force_zero) { if( typeof(milliseconds) != "number" ) milliseconds = parseInt(milliseconds); this.stopTimer(key); // Clear previous clearInterval from memory if(DEBUG) console.log("Timer '"+key+"' setted for "+milliseconds+" milliseconds"); this.timers[key] = setTimeout(funcString, milliseconds); } }; /* * Plugin extension methods */ var extensions = { /* * Expose some debug infos */ debug : function() { return this.each(function(){ var $this = $(this), data = $this.data("djangotribune"), key = data.key; console.log("'clock store' debug output"); console.log( "@@ _index_ids @@" ); console.log( clock_store._index_ids[key] ); console.log( "@@ _index_timestamps @@" ); console.log( clock_store._index_timestamps[key] ); console.log( "@@ _index_dates @@" ); console.log( clock_store._index_dates[key] ); console.log( "@@ _index_clocks @@" ); console.log( clock_store._index_clocks[key] ); console.log( "@@ _count_timestamp @@" ); console.log( clock_store._count_timestamp[key] ); console.log( "@@ _count_short_clock @@" ); console.log( clock_store._count_short_clock[key] ); console.log( "@@ _index_user_ids @@" ); console.log( clock_store._index_user_ids[key] ); console.log( "@@ _index_user_timestamps @@" ); console.log( clock_store._index_user_timestamps[key] ); console.log( "@@ _index_user_clocks @@" ); console.log( clock_store._index_user_clocks[key] ); console.log( "@@ _map_clock @@" ); console.log( clock_store._map_clock[key] ); console.log( "@@ _map_clockids @@" ); console.log( clock_store._map_clockids[key] ); }); }, /* * Initialize plugin, must be called first */ init : function(options) { // Default for DjangoCodeMirror & CodeMirror var settings = $.extend( { "host" : '', "remote_path": '', "post_path": '', "channel": null, "clockfinder_path": '', "theme": 'default', "message_limit": 30, "refresh_active": true, "refresh_time_shifting": 10000, "authenticated_username": null, "urlopen_blank": true, "shortcut_map": { "bold": ["b", "b", function(s){ return "<b>"+s+"</b>" }], "italic": ["i", "i", function(s){ return "<i>"+s+"</i>" }], "stroke": ["s", "s", function(s){ return "<s>"+s+"</s>" }], "underline": ["u", "u", function(s){ return "<u>"+s+"</u>" }], "teletype": ["tt", "t", function(s){ return "<tt>"+s+"</tt>" }], "code": ["code", "c", function(s){ return "<code>"+s+"</code>" }], "moment": ["m", "m", function(s){ return "<m>"+s+"</m>" }] } }, options); // Build DjangoTribune for each selected element return this.each(function() { var $this = $(this), djangotribune_key = "djangotribune-id-" + (settings.channel||'default'), // djangotribune instance ID, must be unique, reference to the current channel if any djangotribune_scroll = $("<div class=\"djangotribune_scroll\"></div>").insertBefore("form", $this).append($("ul.messages", $this)), refresh_input = templates.refresh_checkbox(settings).insertBefore("form .input-column .ctrlHolder", $this), shortcut_bar = $("<div class=\"djangotribune_shortcut_bar row collapse\"></div>").insertBefore("form *:first", $this), // REFRESH INDICATOR display refresh_indicator = { start: function(instance){ $("input.content_field", instance).removeClass("backend-refresh-error").addClass("backend-refresh-spinner"); }, stop: function(instance){ $("input.content_field", instance).removeClass("backend-refresh-spinner"); }, error: function(instance){ $("input.content_field", instance).removeClass("backend-refresh-spinner").addClass("backend-refresh-error"); }, }, // SUBMIT INDICATOR display submit_indicator = { start: function(instance){ $("input.content_field", instance).removeClass("error").addClass("disabled"); }, stop: function(instance){ $("input.content_field", instance).removeClass("disabled"); }, error: function(instance){ $("input.content_field", instance).removeClass("disabled").addClass("error"); $("input.content_field", instance).removeClass("disabled").addClass("error"); }, }, absolute_container = $('<div class="absolute-message-container"><div class="content"></div></div>').css({"display": "none"}).appendTo("body"), extra_context = {}; // Attach element's data $this.data("djangotribune", { "djangotribune": $this, "key": djangotribune_key, "scroller": djangotribune_scroll, "refresh_input": refresh_input.find('input'), "refresh_indicator": refresh_indicator, "submit_indicator": submit_indicator, "absolute_container": absolute_container, "settings": settings }); $this.data("djangotribune_lastid", 0); // Open a new store for the current channel clock_store.new_store(djangotribune_key); // Default Ajax request settings $.ajaxSetup({ global: false, type: "GET", dataType: "json", beforeSend: CSRFpass, ifModified: true, cache: false }); // Bind djangotribune's specific events extra_context.djangotribune = $this; $(window).bind("update_backend_display.djangotribune", events.update); refresh_input.find('input').change(extra_context, events.change_refresh_active); $("form input[type='submit']", $this).click(extra_context, events.submit); $("input.content_field", $this).keydown(extra_context, function(e){ if(e.keyCode == '13'){ e.stopPropagation(); return events.submit(e); } return true; }); $("form", $this).bind("submit", function() { return false; }); // Bind keyboard shortcuts for syntax from the map $.each(settings.shortcut_map, function(index, row) { $("input.content_field", $this).bind('keydown', jwerty.event('alt+'+row[1], events.shortcut_key, [index, $this])); // Add a button in bar to simulate shortcut key on button click $('<a class="'+index+'" title="alt+'+row[1]+'">'+row[0]+'</a>').appendTo(shortcut_bar).click(function(){ jwerty.fire('alt+'+row[1], "input.content_field", $this); return false; }); }); // First parsing from html $this.djangotribune('initial'); }); }, /* * Parse HTML message list as initial backend, index/store their data and update * the last_id */ initial : function() { return this.each(function(){ var $this = $(this), data = $this.data("djangotribune"), last_id = $this.data("djangotribune_lastid"), currentid = 0, owned; $(".djangotribune_scroll li.message", $this).each(function(index) { currentid = parseInt( $(this).attr("data-tribune-pk") ); // Break to avoid doublet processing if( last_id >= currentid ) return false; // Chech message author identity var identity_username = null; if( $("span.identity", this).hasClass('authenticated') ) { identity_username = $("span.identity", this).html(); } // Compile message datas as a message object var message_data = { "id": currentid, "created": $(this).attr("data-tribune-created"), "clock": $("span.clock", this).text(), "clock_indice": parseInt( $(this).attr("data-tribune-clock_indice") ), "clockclass": $(this).attr("data-tribune-clockclass"), "user_agent": $("span.identity", this).attr('title'), "author__username": identity_username, "owned": ($(this).attr("data-tribune-owned") && $(this).attr("data-tribune-owned")=="true") ? true : false, "web_render": $("span.content", this).html() }; // Store the clock clock_store.add(data.key, message_data.created, message_data.clock_indice, message_data.owned); // Detect /me action if(message_data.author__username && message_data.web_render.search(/^\/me /) >= 0){ $(this).addClass('me-action'); $("span.content", this).html(message_data.web_render.replace(/^\/me /, '')); } // Put data in clock/timestamp/etc.. register and initialize // events (clock, links, totoz, etc..) on rows events.bind_message($this, data, this, message_data, true); }); // First timer init if(data.settings.refresh_active){ Timer.setTimer(data.key, function(){ $this.djangotribune('refresh'); }, data.settings.refresh_time_shifting); } // Push the last message id as reference for next backend requests $this.data("djangotribune_lastid", currentid); }); }, /* * Get the fucking backend */ refresh : function(options) { return this.each(function(){ var $this = $(this), data = $this.data("djangotribune"), last_id = $this.data("djangotribune_lastid"), query = $.QueryString, refresh_indicator = data.refresh_indicator; // Custom options if any options = options||{}; // Check custom last_id if(options.last_id) { last_id = options.last_id; } query.last_id = last_id; // Custom settings on the fly if any current_settings = data.settings; if(options.extra_settings){ current_settings = $.extend({}, current_settings, options.extra_settings); } // Perform request to fetch backend var url = CoreTools.get_request_url(current_settings.host, current_settings.remote_path, query); if(DEBUG) console.log("Djangotribune refresh on : "+url); $.ajax({ url: url, data: {}, beforeSend: function(req){ refresh_indicator.start($this); }, success: function (backend, textStatus) { if(DEBUG) console.log("Djangotribune Request textStatus: "+textStatus); refresh_indicator.stop($this); if(textStatus == "notmodified") return false; // Send signal to update messages list with the fetched backend // if there are at least one row if(backend.length>0) { $this.trigger("update_backend_display", [data, backend, last_id]); } }, error: function(XMLHttpRequest, textStatus, errorThrown){ if(DEBUG) console.log("Djangotribune Error request textStatus: "+textStatus); if(DEBUG) console.log("Djangotribune Error request errorThrown: "+textStatus); refresh_indicator.error($this); }, complete: function (XMLHttpRequest, textStatus) { // Relaunch timer if(data.settings.refresh_active){ Timer.setTimer(data.key, function(){ $this.djangotribune('refresh'); }, data.settings.refresh_time_shifting); } } }); }); } }; /* * Plugin event methods */ var events = { /* * Update HTML to append new messages from the given backend data * This should not be used if there are no message in backend */ update : function(event, data, backend, last_id, options) { var element, element_ts, $this = $(event.target), current_message_length = $(".djangotribune_scroll li", $this).length; if(DEBUG) console.log("Djangotribune events.update"); // Drop the notice for empty lists $(".djangotribune_scroll li.notice.empty", $this).remove(); // Custom options if any options = options||{}; current_settings = data.settings; if(options.extra_settings){ current_settings = $.extend({}, current_settings, options.extra_settings); } // Get the current knowed last post ID last_id = $this.data("djangotribune_lastid"); $.each(backend, function(index, row) { // Drop the oldiest item if message list has allready reached the // display limit // TODO: This should drop also item clocks references from the // "clock_store" (to avoid too much memory usage) if (current_message_length >= data.settings.message_limit) { $(".djangotribune_scroll li", $this).slice(0,1).remove(); } // Register the message in the clock store element_ts = clock_store.add(data.key, row.created, null, row.owned); // Update clock attributes from computed values by the clock store row.clock_indice = element_ts.indice; row.clockclass = clock_store.clock_to_cssname(element_ts.clock); // Compute some additionals row data row = CoreTools.compute_extra_row_datas(row); // Compile template, add its result to html and attach it his data element = $( templates.message_row(row) ).appendTo( $(".djangotribune_scroll ul", $this) ).data("djangotribune_row", row); // Bind all related message events events.bind_message($this, data, element, row); // Update to the new last_id last_id = row.id; }); // Push the last message id as reference for next backend requests $this.data("djangotribune_lastid", last_id); }, /* * Change the settings "refresh_active" from the checkbox * TODO: This should be memorized in a cookie or something else more persistent * (like user personnal settings) instead of local variables in a page instance */ change_refresh_active : function(event) { var $this = $(event.data.djangotribune), data = $this.data("djangotribune"); if(DEBUG) console.log("Djangotribune events.change_refresh_active"); if( data.refresh_input.is(':checked') ){ // Enable refresh Timer.setTimer(data.key, function(){ $this.djangotribune('refresh'); }, data.settings.refresh_time_shifting); data.settings.refresh_active = true; } else { // Disable refresh Timer.stopTimer(data.key); data.settings.refresh_active = false; } // Update settings $this.data("djangotribune", data); return true; }, /* * Submit form to post content */ submit : function(event) { var $this = $(event.data.djangotribune), data = $this.data("djangotribune"), last_id = $this.data("djangotribune_lastid"), submit_indicator = data.submit_indicator, query = $.QueryString; if(DEBUG) console.log("Djangotribune events.submit"); var content_value = $("input.content_field", $this).val(); if(!content_value || content_value.length<1) return false; query.last_id = last_id; // Perform request to fetch backend var url = CoreTools.get_request_url(data.settings.host, data.settings.post_path, query); if(DEBUG) console.log("Djangotribune posting on : "+url); $.ajax({ type: "POST", url: url, data: {"content": content_value}, beforeSend: function(req){ // Stop timer and put display marks on content field input Timer.stopTimer(data.key); $("form input[type='submit']", $this).attr("disabled", "disabled"); submit_indicator.start(); }, success: function (backend, textStatus) { if(DEBUG) console.log("Djangotribune Request textStatus: "+textStatus); submit_indicator.stop(); $("input.content_field", $this).val(""); if(textStatus == "notmodified") return false; // Send signal to update messages list with the fetched backend // if there are at least one row if(backend.length>0) { $this.trigger("update_backend_display", [data, backend, last_id]); } }, error: function(XMLHttpRequest, textStatus, errorThrown){ if(DEBUG) console.log("Djangotribune Error request textStatus: "+textStatus); if(DEBUG) console.log("Djangotribune Error request errorThrown: "+textStatus); submit_indicator.error(); }, complete: function (XMLHttpRequest, textStatus) { $("form input[type='submit']", $this).removeAttr("disabled"); // Relaunch timer if(data.settings.refresh_active){ Timer.setTimer(data.key, function(){ $this.djangotribune('refresh'); }, data.settings.refresh_time_shifting); } } }); return false; }, /* * Bind message events and add some sugar on message HTML */ bind_message : function(djangotribune_element, djangotribune_data, message_element, message_data, initial) { var preload, clock, input_sel, pointer_name, clock_name, css_attrs, initial = (initial) ? true : false, // TODO: move in the djangotribune data // NOTE: initial HTML use entity reference and JSON backend use decimal // reference, so for now we need to support both of them regex_cast_initial = new RegExp(djangotribune_data.settings.authenticated_username+"&#60;"), regex_cast_backend = new RegExp(djangotribune_data.settings.authenticated_username+"&lt;"); // Add event to force URL opening in a new window $("span.content a", message_element).click( function() { window.open($(this).attr("href")); return false; }); // Smiley images $("span.content a.smiley", message_element).each(function(index) { preload = new Image(); preload.src = $(this).attr("href"); }).mouseenter( {"djangotribune": djangotribune_element}, events.display_smiley ).mouseleave( function() { $("p.smiley_container").remove(); }); // Add flat clock as a class name on pointers $("span.content span.pointer", message_element).each(function(index) { $(this).addClass("pointer_"+clock_store.plainclock_to_cssname($(this).text())); }); // Broadcasting if( message_data.web_render.toLowerCase().search(/moules&lt;/) != -1 || message_data.web_render.toLowerCase().search(/moules&#60;/) != -1 ){ // Global mussles broadcasting $(message_element).addClass("musslecast"); $('span.marker', message_element).html("<i class=\"icon-bullhorn\"></i>") } else if ( djangotribune_data.settings.authenticated_username && ( message_data.web_render.toLowerCase().search( regex_cast_initial ) != -1 || message_data.web_render.toLowerCase().search( regex_cast_backend ) != -1 ) ){ // User broadcasting $(message_element).addClass("usercast"); $('span.marker', message_element).html("<i class=\"icon-bullhorn\"></i>") } // Message reference clock $("span.clock", message_element).mouseenter(function(){ // Get related pointers in all messages and highlight them $(this).parent().addClass("highlighted"); pointer_name = "pointer_"+clock_store.plainclock_to_cssname(jQuery.trim($(this).text())); $("li.message span.pointer."+pointer_name, djangotribune_element).each(function(index) { $(this).addClass("highlighted"); $(this).parent().parent().addClass("highlighted"); }); }).mouseleave(function(){ // Get related pointers and un-highlight them $(this).parent().removeClass("highlighted"); pointer_name = "pointer_"+clock_store.plainclock_to_cssname(jQuery.trim($(this).text())); $("li.message span.pointer."+pointer_name, djangotribune_element).each(function(index) { $(this).removeClass("highlighted"); $(this).parent().parent().removeClass("highlighted"); }); }).click(function(){ // Add clicked clock at input cursor position then focus after // the clock position clock = jQuery.trim($(this).text()); input_sel = $("#id_content").textrange('get'); $("#id_content").textrange('insert', clock+" ").textrange('setcursor', input_sel.position+clock.length+1); }); // Clock pointers contained $("span.content span.pointer", message_element).mouseout(function(){ $(this).removeClass("highlighted"); // Get related pointers and un-highlight them pointer_name = "pointer_"+clock_store.plainclock_to_cssname(jQuery.trim($(this).text())); $("li.message span.pointer."+pointer_name, djangotribune_element).each(function(index) { $(this).removeClass("highlighted"); }); // Get related messages and un-highlight them clock_name = "msgclock_"+clock_store.plainclock_to_cssname(jQuery.trim($(this).text())); $("li."+clock_name, djangotribune_element).each(function(index) { $(this).removeClass("highlighted"); }); // Allways empty the absolute display container // NOTE: Mouseout event seems to be throwed to soon in some case like with the // clock out of history feature. The absolute_container seems to be created AFTER // the mouseout event is throwed. (to confirm) djangotribune_data.absolute_container.html("").hide(); }).mouseover(function(){ var $this_pointer = $(this), clock_pointer = jQuery.trim($this_pointer.text()), _clock_pointer_match_count = 0; $this_pointer.addClass("highlighted"); // Get related pointers in all messages and highlight them pointer_name = "pointer_"+clock_store.plainclock_to_cssname(clock_pointer); $("li.message span.pointer."+pointer_name, djangotribune_element).each(function(index) { $(this).addClass("highlighted"); }); // Get related messages and highlight them clock_name = "msgclock_"+clock_store.plainclock_to_cssname(clock_pointer); if(DEBUG) console.info("Clock pointer hover for: %s", clock_name); $("li."+clock_name, djangotribune_element).each(function(index) { _clock_pointer_match_count += 1; $(this).addClass("highlighted"); if(DEBUG) { console.group("Pointer event for message: %s", clock_pointer) console.log("Window scrollTop: "+ $(window).scrollTop()); console.log("Pointer offset: "+ $this_pointer.offset().top); console.log("Reference offset from pointer: "+ $(this).offset().top); } // Display messages that are out of screen if($(window).scrollTop() > $(this).offset().top) { events.display_message_popin(djangotribune_data, $this_pointer, $(this).html()); } if(DEBUG) console.groupEnd(); }); // So there is no matched clock in the current history.. what if we try // to find them out of the history ? //if(DEBUG) console.info("Clock pointer matched: %s", _clock_pointer_match_count); if(_clock_pointer_match_count == 0){ if(DEBUG) console.warn("No matched clock %s in current history", clock_pointer); var today = new Date(), item_id = today.getFullYear().toString() + today.getMonth().toString() + today.getDay().toString() + clock_store.plainclock_to_cssname(clock_pointer), url = CoreTools.get_request_url(djangotribune_data.settings.host, djangotribune_data.settings.clockfinder_path).replace(/00:00\//,clock_pointer+"/"), html = ""; if(DEBUG) console.info("Trying to find clock '%s' (id=%s) on url : %s", clock_pointer, item_id, url); $.ajax({ cache: true, url: url, data: {}, success: function (backend, textStatus) { if(DEBUG) console.log("Djangotribune Request textStatus: "+textStatus); if(textStatus == "notmodified"){ // Fill "backend" with cache value for the item_id backend = backends_store[item_id]; } else { // Fill item_id cache with the backend backends_store[item_id] = backend; } if(backend.length==0) return false; $.each(backend, function(index, row) { row = CoreTools.compute_extra_row_datas(row); html += templates.message_row(row, true); }); events.display_message_popin(djangotribune_data, $this_pointer, "<ul>"+html+"</ul>"); }, error: function(XMLHttpRequest, textStatus, errorThrown){ if(DEBUG) console.log("Djangotribune Error request textStatus: "+textStatus); if(DEBUG) console.log("Djangotribune Error request errorThrown: "+textStatus); } }); } }); // Mark answers for current user // TODO: this use "simple" clocks as references without checking, so this // will also mark same clock from another day if they are somes in // history $("span.content span.pointer", message_element).each( function(i){ if( clock_store.is_user_clock(djangotribune_data.key, $(this).text()) ) { $(this).addClass("pointer-answer").parent().parent().addClass("answer").find('span.marker').html("<i class=\"icon-bubble\"></i>"); } }); }, /* * Replace selected text with some method attached to shortcut key */ shortcut_key : function(event, code) { event.preventDefault(); var $this = this[1], data = $this.data("djangotribune"), method_name = this[0], sel = $("input.content_field", $this).textrange('get'), tagged_text = data.settings.shortcut_map[method_name][2](sel.text), pos_diff = tagged_text.length - sel.length; $("input.content_field", $this).textrange('replace', tagged_text); $('input.content_field').textrange('setcursor', sel.end+pos_diff); }, /* * Display the smiley in a "bubble tip" positionned from the element */ display_smiley : function(event) { var $this = $(event.target), djangotribune_element = event.data.djangotribune, url = $this.attr("href"), alt = ($this.attr("alt")||''), top_offset = ($this.offset().top + $this.outerHeight()), left_offset = ($this.offset().left + $this.outerWidth()), bottom_screen_pos = $(document).scrollTop() + $(window).height(), image_height, bottom_image_pos, container; // Remove all previous smiley if any $("p.smiley_container", djangotribune_element).remove(); // Build container positionned at the bottom of the element source container = $("<p class=\"smiley_container\"><img src=\""+ url +"\" alt=\""+ (alt||'') +"\"/>"+"</p>").css({ "height": "", "position":"absolute", "padding":"0", "top": top_offset+"px", "bottom": "", "left": left_offset+"px" }).prependTo("body"); // By default the image is positionned at the bottom of the element, but // if its bottom corner is "out of screen", we move it at the top of element. image_height = container.height(); bottom_image_pos = top_offset + image_height; if(bottom_image_pos > bottom_screen_pos) { top_offset = top_offset-image_height-$this.outerHeight(); container.css("height", image_height+"px").css("top", top_offset).css("bottom", ""); } }, /* * Display message(s) in an absolute pop-in */ display_message_popin : function(djangotribune_data, pointer, html) { // Append html now so we can know about his future height djangotribune_data.absolute_container.html( html ); css_attrs = { "left":djangotribune_data.scroller.offset().left }; // Calculate the coordinates of the bottom container displayed // at top by default var container_bottom_position = $(window).scrollTop() + djangotribune_data.absolute_container.outerHeight(true); // Display at top of the screen by default if( pointer.offset().top > container_bottom_position) { css_attrs.top = 0; css_attrs.bottom = ""; djangotribune_data.absolute_container.removeClass("at-bottom").addClass("at-top"); if(DEBUG) console.info("Absolute display at top"); // Display at bottom of the screen } else { css_attrs.top = ""; css_attrs.bottom = 0; djangotribune_data.absolute_container.removeClass("at-top").addClass("at-bottom"); if(DEBUG) console.info("Absolute display at bottom"); } // Apply css position and show it djangotribune_data.absolute_container.css(css_attrs).show(); } }; /* * Backends store * * Store fetched backend from special method like clock finding * * This is not for storing all the fetched backend by the refresh event. * * Backends are store on their id that is a full timestamp */ var backends_store = { _map_backends : {} }; /* * Clock date store * * Should know about any clock/timestamp with some facilities to get various format, * append new item, remove them(?) and an minimal interface to search on items * * Items ID are internal timestamps, this is a concat of the date, the time and the indice like that : * * YYYYMMDD+hhmmss+i * */ var clock_store = { _indices : '¹²³⁴⁵⁶⁷⁸⁹', // Exposant indices characters map _index_keys : [], // registry keys, each key store his own stuff, values between key stores are never related _index_ids : {}, // IDs are internal timestamp _index_timestamps : {}, // timestamp that represents clocks in a full date format _index_dates : {}, // dates, NOTE: should be removed _index_clocks : {}, // clocks _index_user_ids : {}, // ids owned by the current user _index_user_timestamps : {}, // timestamps owned by the current user _index_user_clocks : {}, // clocks owned by the current user _map_clock : {}, // a map indexed on clocks, with all their timestamps as values, each clock can have multiple timestamp _map_clockids : {}, // a map indexed on clocks, with all their ids as values, each clock can have multiple ids _count_timestamp : {}, // Timestamps count _count_short_clock : {}, // Short clock count /* * New registry initialization */ 'new_store' : function(key) { this._index_keys.push(key); this._index_ids[key] = []; this._index_timestamps[key] = []; this._index_dates[key] = []; this._index_clocks[key] = []; this._index_user_ids[key] = []; this._index_user_timestamps[key] = []; this._index_user_clocks[key] = []; this._map_clock[key] = {}; this._map_clockids[key] = {}; this._count_timestamp[key] = {}; this._count_short_clock[key] = {}; }, /* * Add a timestamp entry to a key store * * NOTE: Shouldn't be an "id" as argument instead of a "timestamp" ?? */ 'add' : function(key, timestamp, indice, user_owned) { var indice = (indice) ? indice : this.get_timestamp_indice(key, timestamp), id = timestamp+this.lpadding(indice), clock = this.timestamp_to_full_clock(timestamp, indice), short_clock = this.timestamp_to_short_clock(timestamp), date = this.timestamp_to_date(timestamp); //console.log("ADDING= key:"+key+"; timestamp:"+timestamp+"; indice:"+indice+"; user_owned:"+user_owned+";"); // Indexing EVERYTHING ! if(this._index_dates[key].indexOf(date) == -1) this._index_dates[key].push(date); if(this._index_ids[key].indexOf(id) == -1) this._index_ids[key].push(id); if(this._index_timestamps[key].indexOf(timestamp) == -1) this._index_timestamps[key].push(timestamp); if(this._index_clocks[key].indexOf(clock) == -1) this._index_clocks[key].push(clock); if(this._index_clocks[key].indexOf(short_clock) == -1) this._index_clocks[key].push(short_clock); // Count TIMESTAMP=>COUNT if(!this._count_timestamp[key][timestamp]) this._count_timestamp[key][timestamp] = 0; // if array doesnt allready exist, create it this._count_timestamp[key][timestamp] += 1; // Count SHORT_CLOCK=>COUNT if(!this._count_short_clock[key][short_clock]) this._count_short_clock[key][short_clock] = 0; // if array doesnt allready exist, create it this._count_short_clock[key][short_clock] += 1; // Map CLOCK=>[TIMESTAMP,..] and SHORT_CLOCK=>[TIMESTAMP,..] if(!this._map_clock[key][clock]) this._map_clock[key][clock] = []; // if array doesnt allready exist, create it if(this._map_clock[key][clock].indexOf(timestamp) == -1) this._map_clock[key][clock].push(timestamp); if(!this._map_clock[key][short_clock]) this._map_clock[key][short_clock] = []; // if array doesnt allready exist, create it if(this._map_clock[key][short_clock].indexOf(timestamp) == -1) this._map_clock[key][short_clock].push(timestamp); // Map CLOCK=>[ID,..] and SHORT_CLOCK=>[ID,..] if(!this._map_clockids[key][clock]) this._map_clockids[key][clock] = []; // if array doesnt allready exist, create it if(this._map_clockids[key][clock].indexOf(id) == -1) this._map_clockids[key][clock].push(id); if(!this._map_clockids[key][short_clock]) this._map_clockids[key][short_clock] = []; // if array doesnt allready exist, create it if(this._map_clockids[key][short_clock].indexOf(id) == -1) this._map_clockids[key][short_clock].push(id); // Flag as a owned clock if true if(user_owned){ if(this._index_user_ids[key].indexOf(id) == -1 ) this._index_user_ids[key].push(id); if(this._index_user_timestamps[key].indexOf(timestamp) == -1 ) this._index_user_timestamps[key].push(timestamp); if(this._index_user_clocks[key].indexOf(clock) == -1 ) this._index_user_clocks[key].push(clock); } return {'id':id, 'timestamp':timestamp, 'date':date, 'clock':clock, 'indice':indice, 'short_clock':short_clock}; }, /* * Remove a timestamp entry from a key store * * NOTE: Shouldn't be an "id" as argument instead of a "timestamp" and "indice" ?? */ 'remove' : function(key, timestamp, indice) { // TODO: full clean of given timestamp in indexes and map // Needed to clear history to avoid too much memory usage when user stay a long time // This is not finished, but not used also for now, we need before to // see what index/count/map is really useful var id = timestamp+this.lpadding(indice), clock = this.timestamp_to_full_clock(timestamp, indice), short_clock = this.timestamp_to_short_clock(timestamp), date = this.timestamp_to_date(timestamp); delete this._index_ids[key][id]; delete this._index_clocks[key][clock]; //full clock this._map_clock[key][clock].remove( this._map_clock[key].indexOf(clock) ); this._map_clockids[key][clock].remove( this._map_clockids[key].indexOf(clock) ); delete this._index_user_ids[key][id]; delete this._index_user_clocks[key][clock]; //full clock this._count_timestamp[key][timestamp] -= 1; this._count_short_clock[key][timestamp] -= 1; return {'id':id, 'timestamp':timestamp, 'date':date, 'clock':clock, 'indice':indice, 'short_clock':short_clock}; }, // Calculate in "real time" the indice for the given timestamp using indexes get_timestamp_indice : function(key, ts) { if(!this._count_timestamp[key][ts]) { return 1; } // Identical timestamp count incremented by one return this._count_timestamp[key][ts]+1; }, // Check if a clock is owned by the current user // Attempt a "simple" clock in argument, not a "full" clock is_user_clock : function(key, clock) { clock = this.clock_to_full_clock(clock); return (this._index_user_clocks[key].indexOf(clock) > -1 ); }, /* ********** PUBLIC STATICS ********** */ /* * timestamp: 20130124005502 * id: 2013012400550201 (the two last digits are the indice) * clock: 00:55:02 or 00:55 or 00:55:02² * clockclass: 005502 * full clock: 00:55:02:01 (':01' is the indice padded on 2 digits) * short clock: 00:55 (seconds are stripped) */ id_to_full_clock : function(id) { return this.timestamp_to_clock(id)+":"+id.substr(14,2); }, timestamp_to_full_clock : function(ts, i) { return this.timestamp_to_clock(ts)+":"+this.lpadding(i); }, timestamp_to_clock : function(ts) { return ts.substr(8,2)+":"+ts.substr(10,2)+":"+ts.substr(12,2); }, timestamp_to_short_clock : function(ts) { return ts.substr(8,2)+":"+ts.substr(10,2); }, // Renvoi un nom de classe composé d'une horloge sans les : à partir d'un timestamp timestamp_to_clockclass : function(ts) { return ts.substr(8,6); }, // Renvoi la partie du timestamp concernant la date, sans l'horloge et le reste timestamp_to_date : function(ts) { return this.split_timestamp(ts)[0]; }, // Sépare en deux parties : date et time split_timestamp : function(ts) { return [ts.substr(0,8), ts.substr(8)]; }, // Convert a clock HH:MM[:SS[i]] to a full clock clock_to_full_clock : function(clock) { if(clock.length > 8) { return clock.substr(0,8)+":"+this.indice_to_number(clock.substr(8,2)); } else if(clock.length < 8) { // short clock is assumed to be at second 00 return clock+":00:01"; } return clock+":01"; }, // Format to a padded number on two digits lpadding : function(indice) { if(indice > 0 && indice < 10) { return '0'+indice; } return "01"; }, // Return an exposant indice from the given number (padded on two digit) number_to_indice : function(i) { if( i > 1 ) return this._indices[i-1]; return ''; }, // Return a padded number on two digit from the given exposant indice indice_to_number : function(indice) { var i = this._indices.indexOf(indice); // Cherche un indice sous forme d'exposant if( i > -1 ) return this.lpadding(i+1); return '01'; }, // Parse a plain clock "HH:MM[:SS[i]]" and return a "flat" version (without the ":") // suitable for class/id css name // If not present in clock, default indice is "01" plainclock_to_cssname : function(clock) { var indice = "01"; if(clock.length > 8){ indice = this.indice_to_number(clock.substr(8,2)); clock = clock.substr(0,8); } return clock.split(":").join("")+indice; }, // Convert a full clock "HH:MM[:SS:[ii]]" to a "flat" version (without the ":") // suitable for class/id css name clock_to_cssname : function(clock) { return clock.split(":").join(""); } }; /* * Various utilities */ var CoreTools = { /* * Build and return a full url from the given args */ get_request_url : function(host, path_view, options) { var url = host + path_view; if(options && $.param(options)!=''){ url += "?" + $.param(options); } return url; }, /* * Compute some extra datas from the row data from a backend */ compute_extra_row_datas: function(row){ row.css_classes = ["msgclock_"+row.clockclass]; if(row.owned) row.css_classes.push("owned"); row.identity = {'title': row.user_agent, 'kind': 'anonymous', 'content': row.user_agent.slice(0,30)}; if(row.author__username){ row.identity.kind = 'authenticated'; row.identity.content = row.author__username; } return row; } }; /* * Plugin HTML templates * This is not "real" templates like with "Mustach.js" and others but just * some functions to build the needed HTML */ var templates = { /* * Message row template * @content is an object with all needed attributes for the template */ refresh_checkbox: function(settings) { var input_checked = (settings.refresh_active) ? " checked=\"checked\"" : ""; return $('<p class="refresh_active"><input type="checkbox" name="active" value="1"'+ input_checked +'/></p>'); }, /* * Message row template * @content is an object with all needed attributes for the template */ message_row: function(content, noclasses) { var clock_indice = "&nbsp;", noclass = (noclasses) ? true : false, css_classes = content.css_classes||[], row_classes; // Display clock indice only if greater than 1 if(content.clock_indice > 1) clock_indice = clock_store.number_to_indice(content.clock_indice); // Detect /me action only for authenticated message if(content.identity.kind == 'authenticated' && content.web_render.search(/^\/me /) >= 0){ css_classes.push('me-action'); content.web_render = content.web_render.replace(/^\/me /, ''); } row_classes = (noclasses) ? "" : " class=\"message "+ css_classes.join(" ") +"\"" return "<li"+ row_classes +"><span class=\"marker\"></span>" + "<span class=\"clock\">"+ content.clock+"<sup>"+clock_indice +"</sup></span> " + "<strong><span class=\"identity "+ content.identity.kind +"\" title=\""+ content.identity.title +"\">"+ content.identity.content +"</span></strong> " + "<span class=\"content\">"+ content.web_render +"</span>" + "</li>"; } }; })( jQuery );
import { h, Component } from 'preact/preact'; import ShallowCompare from 'shallow-compare/index'; import $JammerTV from 'external/jammertv/jammertv'; import SVGIcon from 'com/svg-icon/icon'; import NavSpinner from 'com/nav-spinner/spinner'; import IMG from 'com/img2/img2'; import ButtonBase from 'com/button-base/base'; import ButtonLink from 'com/button-link/link'; const RequiredStreams = 5; export default class SidebarTV extends Component { constructor( props ) { super(props); this.state = { active: 0, streams: [] }; this.services = [ 'null', 'twitch', 'youtube', ]; this.serviceIcons = [ (<div />), // Null // (<SVGIcon>twitch</SVGIcon>), // Twitch // (<SVGIcon>youtube</SVGIcon>), // YouTube // (<div></div>), (<div></div>), (<div></div>), (<div></div>), ]; this.FailImage = '//'+STATIC_DOMAIN+'/other/asset/TVFail.png'; this.refreshStreams = this.refreshStreams.bind(this); } loadStreams() { var NewStreams = []; // Fetch Ludum Dare streams first return $JammerTV.GetLive([ 'ludum-dare', /*'ludum-dare-art', 'ludum-dare-music', 'ludum-dare-craft', 'ludum-dare-play', 'ludum-dare-talk'*/ ]) // Fetch Game Jam streams next (if we don't have enough) .then(data => { // Parse Data if ( data && Array.isArray(data.streams) ) { NewStreams = NewStreams.concat(data.streams); } // Fetch more (if needed) if ( NewStreams.length < RequiredStreams ) { return $JammerTV.GetLive([ 'game-jam', /*'game-jam-art', 'game-jam-music', 'demoscene',*/ ]); } return null; }) // Fetch Game Dev streams last (if we didn't have enough) .then(data => { // Parse data if ( data && Array.isArray(data.streams) ) { NewStreams = NewStreams.concat(data.streams); } // Fetch more (if needed) if ( NewStreams.length < RequiredStreams ) { return $JammerTV.GetLive([ 'game-dev', ]); } return null; }) // Wrap up .then(data => { // Parse Data if ( data && Array.isArray(data.streams) ) { NewStreams = NewStreams.concat(data.streams); } // Populate state with streams this.setState({ 'streams': NewStreams }); return null; }) .catch(err => { // Error state this.setState({ 'error': err }); return err; }); } // Called every few minutes, to make sure stream list is fresh refreshStreams() { // TODO: Raise this, once JammerTV caching is correctly supported var StreamRefreshRate = 3*60*1000; var HiddenRefreshRate = 1*20*1000; // When hidden, refresh more often (which fails, so work is minimal) // But only if the window is visible if ( !document.hidden ) { //console.log("Streams Refreshed: "+Date.now()); this.loadStreams().then(() => { //console.log("Queued"); this.timer = setTimeout(() => { this.refreshStreams(); }, StreamRefreshRate); }); } else { //console.log("Hidden Queue"); this.timer = setTimeout(() => { this.refreshStreams(); }, HiddenRefreshRate); } } // shouldComponentUpdate( nextProps, nextState ) { // var com = ShallowCompare(this, nextProps, nextState); // console.log("SideBarTV",com,this.state, nextState); // return com; // } componentDidMount() { // console.log("SideBarTV: componentDidMount"); this.refreshStreams(); } componentWillUnmount() { // console.log("SideBarTV: componentWillUnmount"); } setActive( id, e ) { this.setState({ active: id }); } showOthers( others, active ) { return others.map((other, index) => { return ( <div class={cN(other === active ? "selected" : "")} onclick={this.setActive.bind(this, index)} title={other && other.user_name ? other.user_name : ""}> <div><IMG src={ other ? other.thumbnail_180p : ""} failsrc={this.FailImage} /></div> </div> ); }); } render( props, state ) { if ( state.error ) { return ( <div class="sidebar-base sidebar-tv"> <div class="-detail"> {""+state.error} </div> </div> ); } else if ( state.streams.length == 0 ) { return ( <div class="sidebar-base sidebar-tv"> <NavSpinner /> </div> ); } else { let active = state.streams[state.active]; let others = [ state.streams[0], state.streams[1], state.streams[2], ]; // This is the above stuff (LIVE vs VOD). disabled for now // <div class="-view"> // <ButtonBase class="-live selected"><SVGIcon baseline small>video-camera</SVGIcon> <span>LIVE</span></ButtonBase> // <ButtonBase class="-vod "><SVGIcon baseline small>video</SVGIcon> <span>VIDEO</span></ButtonBase> // </div> return ( <div class="sidebar-base sidebar-tv"> <div class="-active" onclick={e => { console.log('tv'); /*window.open("https://www.twitch.tv/directory/game/Creative/ldjam", '_blank');*/ window.location.hash = "#tv/"+this.services[active.service_id]+'/'+active.user_slug; }}> <div class="-img"><IMG src={active.thumbnail_180p} failsrc={this.FailImage} /></div> <div class="-live"><SVGIcon baseline small>circle</SVGIcon> <span class="-text">LIVE</span></div> <div class={'-name stream-'+this.services[active.service_id]}>{this.serviceIcons[active.service_id]} <span class="-text">{active.user_name}</span></div> <div class="-viewers"><SVGIcon baseline>tv</SVGIcon> <span class="-text">{active.viewers}</span></div> <div class="-external" onclick={e => { e.stopPropagation(); if ( this.services[active.service_id] == "twitch" ) { window.open("https://www.twitch.tv/"+active.user_slug, "_blank"); } else if ( this.services[active.service_id] == "youtube" ) { //TODO: add youtube action, when youtube displays in TV } }}><SVGIcon>twitch</SVGIcon></div> <div class="-play"><SVGIcon>play</SVGIcon></div> </div> <div class="-detail" title={active.title}> <SVGIcon top>quotes-left</SVGIcon> <SVGIcon bottom>quotes-right</SVGIcon> <div>{active.title}</div> </div> <div class="-browse"> {this.showOthers(others,active)} <ButtonLink class="-more" href="https://www.twitch.tv/directory/all/tags/c8d6d6ee-3b02-4ae7-81e9-4c0f434941cc" title="MORE"> <div><SVGIcon>circle</SVGIcon> <SVGIcon>circle</SVGIcon> <SVGIcon>circle</SVGIcon></div> </ButtonLink> </div> </div> ); } } }
/** * Created by aleckim on 2016. 2. 13.. */ 'use strict'; var kmaTimeLib = {}; /** * 201712242255 -> date * @param str YYYYmmDDHHMMSS * @returns {*} */ kmaTimeLib.convertStringToDate = function(str) { if (!str) { return new Date(0); } var y = str.substr(0,4), m = str.substr(4,2) - 1, d = str.substr(6,2), h = str.substr(8,2), min = str.substr(10,2), sec = str.substr(12,2); if (h == '') { h = '0'; } if (min == '') { min = '0'; } if (sec == '') { sec = '0'; } var D = new Date(y,m,d,h,min, sec); return (D.getFullYear() == y && D.getMonth() == m && D.getDate() == d) ? D : undefined; }; /** * Date -> 20171007 * @param date * @returns {string} */ kmaTimeLib.convertDateToYYYYMMDD = function(date) { //I don't know why one more create Date object by aleckim var d = new Date(date); var month = '' + (d.getMonth() + 1); var day = '' + d.getDate(); var year = d.getFullYear(); if (month.length < 2) { month = '0' + month; } if (day.length < 2) { day = '0' + day; } return year+month+day; }; /** * Date -> 1200 * @param date * @returns {string} */ kmaTimeLib.convertDateToHHZZ = function(date) { //I don't know why one more create Date object by aleckim var d = new Date(date); var hh = '' + (d.getHours()); if (hh.length < 2) {hh = '0'+hh; } return hh+'00'; }; /** * Date -> 1210 * @param date * @returns {string} */ kmaTimeLib.convertDateToHHMM = function(date) { //I don't know why one more create Date object by aleckim var d = new Date(date); var hh = '' + (d.getHours()); if (hh.length < 2) {hh = '0'+hh; } var mm = '' + (d.getMinutes()); if (mm.length < 2) {mm = '0'+mm; } return hh+mm; }; kmaTimeLib.toTimeZone = function (zone, time) { if (time == undefined) { time = new Date(); } var tz = time.getTime() + (time.getTimezoneOffset() * 60000) + (9* 3600000); time.setTime(tz); return time; }; /** * Date -> 2017-10-17 * @param date * @returns {string} */ kmaTimeLib.convertDateToYYYY_MM_DD = function (date) { if (date == undefined) { date = kmaTimeLib.toTimeZone(9); } return date.getFullYear()+ '-'+manager.leadingZeros(date.getMonth()+1, 2)+ '-'+manager.leadingZeros(date.getDate(), 2); }; /** * 20170107 -> 2017-10-07 * @param dateStr * @returns {string} */ kmaTimeLib.convertYYYYMMDDtoYYYY_MM_DD = function (dateStr) { return dateStr.substr(0,4)+'-'+dateStr.substr(4,2)+'-'+dateStr.substr(6,2); }; /** * 2017-01-07 -> 20171007 * 2017.01.07 -> 20171007 * @param dateStr * @returns {string} */ kmaTimeLib.convertYYYY_MM_DDtoYYYYMMDD = function (dateStr) { return dateStr.substr(0,4)+dateStr.substr(5,2)+dateStr.substr(8,2); }; /** * 201701071210 -> 2017.10.07.12:10 * @param dateStr * @returns {string} */ kmaTimeLib.convertYYYYMMDDHHMMtoYYYYoMMoDDoHHoMM = function(dateStr) { var str = dateStr.substr(0,4)+'.'+dateStr.substr(4,2)+'.'+dateStr.substr(6,2); if (dateStr.length > 8) { str += '.' + dateStr.substr(8,2) + ':' + dateStr.substr(10,2); } return str; }; /** * 201701071210 -> 2017.10.07 12:10 * @param dateStr * @returns {string} */ kmaTimeLib.convertYYYYMMDDHHMMtoYYYYoMMoDD_HHoMM = function(dateStr) { var str = dateStr.substr(0,4)+'.'+dateStr.substr(4,2)+'.'+dateStr.substr(6,2); if (dateStr.length > 8) { str += ' ' + dateStr.substr(8,2) + ':' + dateStr.substr(10,2); } return str; }; /** * 201701071210 -> 2017.10.07 12:00 * @param dateStr * @returns {string} */ kmaTimeLib.convertYYYYMMDDHHMMtoYYYYoMMoDD_HHoZZ = function(dateStr) { var str = dateStr.substr(0,4)+'.'+dateStr.substr(4,2)+'.'+dateStr.substr(6,2); if (dateStr.length > 8) { str += ' ' + dateStr.substr(8,2) + ':00'; } return str; }; /** * 201701071210 -> 2017.10.07.12:00 * @param dateStr * @returns {string} */ kmaTimeLib.convertYYYYMMDDHHMMtoYYYYoMMoDDoHHoZZ = function(dateStr) { var str = dateStr.substr(0,4)+'.'+dateStr.substr(4,2)+'.'+dateStr.substr(6,2); if (dateStr.length > 8) { str += '.' + dateStr.substr(8,2) + ':00'; } return str; }; /** * 2017.01.07.15:00 -> 201701071500 * @param dateStr * @returns {string} */ kmaTimeLib.convertYYYYoMMoDDoHHoMMtoYYYYMMDDHHMM = function(dateStr) { var str = dateStr.substr(0,4)+dateStr.substr(5,2)+dateStr.substr(8,2); if (dateStr.length > 10) { str += dateStr.substr(11,2) + dateStr.substr(14,2); } return str; }; /** * 2017.01.07.15:10 -> 1510 * @param dateStr * @returns {string} */ kmaTimeLib.convertYYYYoMMoDDoHHoMMtoHHMM = function(dateStr) { var str = ""; if (dateStr.length > 10) { str += dateStr.substr(11,2) + dateStr.substr(14,2); } return str; }; /** * 2017.01.07.15:10 -> 2017.01.07 15:10 * @param dateStr * @returns {string} */ kmaTimeLib.convertYYYYoMMoDDoHHoMMtoYYYYoMMoDD_HHoMM = function(dateStr) { var str = dateStr.substr(0,4)+'.'+dateStr.substr(5,2)+'.'+dateStr.substr(8,2); if (dateStr.length > 10) { str += ' ' + dateStr.substr(11,2)+ ':' + dateStr.substr(14,2); } return str; }; /** * for kma scraper * Date -> 2018.12.31.23:00 * @param date * @returns {string} */ kmaTimeLib.convertDateToYYYYoMMoDDoHHoZZ = function (date) { if (date == undefined) { date = kmaTimeLib.toTimeZone(9); } return date.getFullYear()+ '.'+manager.leadingZeros(date.getMonth()+1, 2)+ '.'+manager.leadingZeros(date.getDate(), 2) + '.'+manager.leadingZeros(date.getHours(), 2) + ':00'; }; /** * Date -> 2018.12.31.23:59 * @param date * @returns {string} */ kmaTimeLib.convertDateToYYYYoMMoDDoHHoMM = function (date) { if (date == undefined) { date = kmaTimeLib.toTimeZone(9); } return date.getFullYear()+ '.'+manager.leadingZeros(date.getMonth()+1, 2)+ '.'+manager.leadingZeros(date.getDate(), 2) + '.'+manager.leadingZeros(date.getHours(), 2) + ':'+manager.leadingZeros(date.getMinutes(), 2); }; /** * Date -> 2018.12.31 23:00 * @param date * @returns {string} */ kmaTimeLib.convertDateToYYYYoMMoDD_HHoZZ = function (date) { if (date == undefined) { date = kmaTimeLib.toTimeZone(9); } return date.getFullYear()+ '.'+manager.leadingZeros(date.getMonth()+1, 2)+ '.'+manager.leadingZeros(date.getDate(), 2) + ' '+manager.leadingZeros(date.getHours(), 2) + ':00'; }; /** * Date -> 2018.12.31 23:59 * @param date * @returns {string} */ kmaTimeLib.convertDateToYYYYoMMoDD_HHoMM = function (date) { if (date == undefined) { date = kmaTimeLib.toTimeZone(9); } return date.getFullYear()+ '.'+manager.leadingZeros(date.getMonth()+1, 2)+ '.'+manager.leadingZeros(date.getDate(), 2) + ' '+manager.leadingZeros(date.getHours(), 2) + ':'+manager.leadingZeros(date.getMinutes(), 2); }; /** * Date -> 2018-12-31 23:59 * @param date * @returns {string} */ kmaTimeLib.convertDateToYYYY_MM_DD_HHoMM = function (date) { if (date == undefined) { date = kmaTimeLib.toTimeZone(9); } return date.getFullYear()+ '-'+manager.leadingZeros(date.getMonth()+1, 2)+ '-'+manager.leadingZeros(date.getDate(), 2) + ' '+manager.leadingZeros(date.getHours(), 2) + ':'+manager.leadingZeros(date.getMinutes(), 2); }; kmaTimeLib.convert0Hto24H = function (obj) { if (obj.time === "0000") { var D = kmaTimeLib.convertStringToDate(obj.date); D.setDate(D.getDate()-1); //date = back one day //date = (parseInt(short.date)-1).toString(); obj.time = "2400"; obj.date = kmaTimeLib.convertDateToYYYYMMDD(D); } }; kmaTimeLib.convert24Hto0H = function (obj) { if (obj.time === "2400") { var D = kmaTimeLib.convertStringToDate(obj.date); D.setDate(D.getDate()+1); //date = back one day //date = (parseInt(short.date)-1).toString(); obj.time = "0000"; obj.date = kmaTimeLib.convertDateToYYYYMMDD(D); } }; kmaTimeLib.compareDateTime = function (objA, objB) { var self = this; var tempA = JSON.parse(JSON.stringify(objA)); var tempB = JSON.parse(JSON.stringify(objB)); self.convert0Hto24H(tempA); self.convert0Hto24H(tempB); if (tempA.date === tempB.date && tempA.time === tempB.time) { return true; } return false; }; /** * 2017년 06월 18일 15시 00분 -> date * @param str */ kmaTimeLib.convertKoreaStr2Date = function (str) { var strArray = str.split(' '); var y = strArray[0].substr(0, 4); var m = strArray[1].substr(0, 2) - 1; var d = strArray[2].substr(0, 2); var h = strArray[3].substr(0, 2); var min = strArray[4].substr(0, 2); var D = new Date(y,m,d,h,min); return (D.getFullYear() == y && D.getMonth() == m && D.getDate() == d) ? D : undefined; }; kmaTimeLib.leadingZeros = function(n, digits) { var zero = ''; n = n.toString(); if(n.length < digits) { for(var i = 0; i < digits - n.length; i++){ zero += '0'; } } return zero + n; }; kmaTimeLib.getPast3DaysTime = function(curTime){ var now = new Date(curTime.getTime()); var tz = now.getTime() + (-72 * 3600000); //var tz = now.getTime() + (3 * 3600000); now.setTime(tz); return now; }; /** * 시차 고려하여 9일이전것부터 지우게 변겸. * @param curTime * @returns {Date} */ kmaTimeLib.getPast8DaysTime = function(curTime){ var now = new Date(curTime.getTime()); var tz = now.getTime() + (-216 * 3600000); //var tz = now.getTime() + (3 * 3600000); now.setTime(tz); return now; }; /** * 201812312300 -> Date(Timezone +9) * @param curTime * @returns {Date} */ kmaTimeLib.getKoreaDateObj = function(curTime){ return new Date(curTime.slice(0,4)+ '-' + curTime.slice(4,6) + '-' + curTime.slice(6,8) + 'T' + curTime.slice(8,10) + ':' + curTime.slice(10,12) + ':00+09:00'); }; /** * Date + 9 -> 201812312300 * @param curTime * @returns {*} */ kmaTimeLib.getKoreaTimeString = function(curTime){ var now = new Date(curTime.getTime()); var tz = now.getTime() + (9 * 3600000); now.setTime(tz); var result = kmaTimeLib.leadingZeros(now.getUTCFullYear(), 4) + kmaTimeLib.leadingZeros(now.getUTCMonth() + 1, 2) + kmaTimeLib.leadingZeros(now.getUTCDate(), 2) + kmaTimeLib.leadingZeros(now.getUTCHours(), 2) + kmaTimeLib.leadingZeros(now.getUTCMinutes(), 2); return result; }; kmaTimeLib.getDiffDays = function(target, current) { if (!target || !current) { log.error("target or current is invalid"); return 0; } if (typeof target === 'string') { target = new Date(target); } if (typeof current === 'string') { current = new Date(current); } var targetDay = new Date(target.getFullYear(), target.getMonth(), target.getDate()); var date = new Date(current.getFullYear(), current.getMonth(), current.getDate()); return Math.ceil((targetDay - date) / (1000 * 3600 * 24)); }; /** * 2018-01-21 11시 발표 -> 2018-01-21 11:00 * @param str */ kmaTimeLib.convertYYYY_MM_DD_HHStr2YYYY_MM_DD_HHoZZ = function (str) { return str.substr(0, 13) + ":00"; }; kmaTimeLib.toLocalTime = function (offset, date) { if (date) { date = new Date(date); } else { date = new Date(); } date.setMinutes(date.getMinutes()+date.getTimezoneOffset()); //to utc time date.setMinutes(date.getMinutes()+offset); return date; }; kmaTimeLib.convertDatetoString = function(src){ var date = new Date(); date.setTime(src); var result = kmaTimeLib.leadingZeros(date.getFullYear(), 4) + kmaTimeLib.leadingZeros(date.getMonth() + 1, 2) + kmaTimeLib.leadingZeros(date.getDate(), 2) + kmaTimeLib.leadingZeros(date.getHours(), 2) + kmaTimeLib.leadingZeros(date.getMinutes(), 2); return result; }; module.exports = kmaTimeLib;
"use strict"; var EventEmitter = require('events').EventEmitter , inherits = require('util').inherits , f = require('util').format , ServerCapabilities = require('./topology_base').ServerCapabilities , MongoCR = require('mongodb-core').MongoCR , MongoError = require('mongodb-core').MongoError , CMongos = require('mongodb-core').Mongos , Cursor = require('./cursor') , AggregationCursor = require('./aggregation_cursor') , CommandCursor = require('./command_cursor') , Define = require('./metadata') , Server = require('./server') , Store = require('./topology_base').Store , shallowClone = require('./utils').shallowClone , MAX_JS_INT = require('./utils').MAX_JS_INT , translateOptions = require('./utils').translateOptions , filterOptions = require('./utils').filterOptions , mergeOptions = require('./utils').mergeOptions , os = require('os'); // Get package.json variable var driverVersion = require(__dirname + '/../package.json').version; var nodejsversion = f('Node.js %s, %s', process.version, os.endianness()); var type = os.type(); var name = process.platform; var architecture = process.arch; var release = os.release(); /** * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is * used to construct connections. * * **Mongos Should not be used, use MongoClient.connect** * @example * var Db = require('mongodb').Db, * Mongos = require('mongodb').Mongos, * Server = require('mongodb').Server, * test = require('assert'); * // Connect using Mongos * var server = new Server('localhost', 27017); * var db = new Db('test', new Mongos([server])); * db.open(function(err, db) { * // Get an additional db * db.close(); * }); */ // Allowed parameters var legalOptionNames = ['ha', 'haInterval', 'acceptableLatencyMS' , 'poolSize', 'ssl', 'checkServerIdentity', 'sslValidate' , 'sslCA', 'sslCert', 'sslKey', 'sslPass', 'socketOptions', 'bufferMaxEntries' , 'store', 'auto_reconnect', 'autoReconnect', 'emitError' , 'keepAlive', 'noDelay', 'connectTimeoutMS', 'socketTimeoutMS' , 'loggerLevel', 'logger', 'reconnectTries', 'appname', 'domainsEnabled' , 'servername', 'promoteLongs', 'promoteValues']; /** * Creates a new Mongos instance * @class * @deprecated * @param {Server[]} servers A seedlist of servers participating in the replicaset. * @param {object} [options=null] Optional settings. * @param {booelan} [options.ha=true] Turn on high availability monitoring. * @param {number} [options.haInterval=5000] Time between each replicaset status check. * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for MongoS proxy selection * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. * @param {object} [options.socketOptions=null] Socket options * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. * @fires Mongos#connect * @fires Mongos#ha * @fires Mongos#joined * @fires Mongos#left * @fires Mongos#fullsetup * @fires Mongos#open * @fires Mongos#close * @fires Mongos#error * @fires Mongos#timeout * @fires Mongos#parseError * @return {Mongos} a Mongos instance. */ var Mongos = function(servers, options) { if(!(this instanceof Mongos)) return new Mongos(servers, options); options = options || {}; var self = this; // Filter the options options = filterOptions(options, legalOptionNames); // Ensure all the instances are Server for(var i = 0; i < servers.length; i++) { if(!(servers[i] instanceof Server)) { throw MongoError.create({message: "all seed list instances must be of the Server type", driver:true}); } } // Stored options var storeOptions = { force: false , bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : MAX_JS_INT } // Shared global store var store = options.store || new Store(self, storeOptions); // Set up event emitter EventEmitter.call(this); // Build seed list var seedlist = servers.map(function(x) { return {host: x.host, port: x.port} }); // Get the reconnect option var reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; reconnect = typeof options.autoReconnect == 'boolean' ? options.autoReconnect : reconnect; // Clone options var clonedOptions = mergeOptions({}, { disconnectHandler: store, cursorFactory: Cursor, reconnect: reconnect, emitError: typeof options.emitError == 'boolean' ? options.emitError : true, size: typeof options.poolSize == 'number' ? options.poolSize : 5 }); // Translate any SSL options and other connectivity options clonedOptions = translateOptions(clonedOptions, options); // Socket options var socketOptions = options.socketOptions && Object.keys(options.socketOptions).length > 0 ? options.socketOptions : options; // Translate all the options to the mongodb-core ones clonedOptions = translateOptions(clonedOptions, socketOptions); if(typeof clonedOptions.keepAlive == 'number') { clonedOptions.keepAliveInitialDelay = clonedOptions.keepAlive; clonedOptions.keepAlive = clonedOptions.keepAlive > 0; } // Build default client information this.clientInfo = { driver: { name: "nodejs", version: driverVersion }, os: { type: type, name: name, architecture: architecture, version: release }, platform: nodejsversion } // Build default client information clonedOptions.clientInfo = this.clientInfo; // Do we have an application specific string if(options.appname) { clonedOptions.clientInfo.application = { name: options.appname }; } // Create the Mongos var mongos = new CMongos(seedlist, clonedOptions) // Server capabilities var sCapabilities = null; // Internal state this.s = { // Create the Mongos mongos: mongos // Server capabilities , sCapabilities: sCapabilities // Debug turned on , debug: clonedOptions.debug // Store option defaults , storeOptions: storeOptions // Cloned options , clonedOptions: clonedOptions // Actual store of callbacks , store: store // Options , options: options } } var define = Mongos.define = new Define('Mongos', Mongos, false); /** * @ignore */ inherits(Mongos, EventEmitter); // Last ismaster Object.defineProperty(Mongos.prototype, 'isMasterDoc', { enumerable:true, get: function() { return this.s.mongos.lastIsMaster(); } }); // BSON property Object.defineProperty(Mongos.prototype, 'bson', { enumerable: true, get: function() { return this.s.mongos.s.bson; } }); Object.defineProperty(Mongos.prototype, 'haInterval', { enumerable:true, get: function() { return this.s.mongos.s.haInterval; } }); // Connect Mongos.prototype.connect = function(db, _options, callback) { var self = this; if('function' === typeof _options) callback = _options, _options = {}; if(_options == null) _options = {}; if(!('function' === typeof callback)) callback = null; self.s.options = _options; // Update bufferMaxEntries self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; // Error handler var connectErrorHandler = function(event) { return function(err) { // Remove all event handlers var events = ['timeout', 'error', 'close']; events.forEach(function(e) { self.removeListener(e, connectErrorHandler); }); self.s.mongos.removeListener('connect', connectErrorHandler); // Try to callback try { callback(err); } catch(err) { process.nextTick(function() { throw err; }) } } } // Actual handler var errorHandler = function(event) { return function(err) { if(event != 'error') { self.emit(event, err); } } } // Error handler var reconnectHandler = function(err) { self.emit('reconnect'); self.s.store.execute(); } // relay the event var relay = function(event) { return function(t, server) { self.emit(event, t, server); } } // Connect handler var connectHandler = function() { // Clear out all the current handlers left over ["timeout", "error", "close", 'serverOpening', 'serverDescriptionChanged', 'serverHeartbeatStarted', 'serverHeartbeatSucceeded', 'serverHearbeatFailed', 'serverClosed', 'topologyOpening', 'topologyClosed', 'topologyDescriptionChanged'].forEach(function(e) { self.s.mongos.removeAllListeners(e); }); // Set up listeners self.s.mongos.once('timeout', errorHandler('timeout')); self.s.mongos.once('error', errorHandler('error')); self.s.mongos.once('close', errorHandler('close')); // Set up SDAM listeners self.s.mongos.on('serverDescriptionChanged', relay('serverDescriptionChanged')); self.s.mongos.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); self.s.mongos.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); self.s.mongos.on('serverHearbeatFailed', relay('serverHearbeatFailed')); self.s.mongos.on('serverOpening', relay('serverOpening')); self.s.mongos.on('serverClosed', relay('serverClosed')); self.s.mongos.on('topologyOpening', relay('topologyOpening')); self.s.mongos.on('topologyClosed', relay('topologyClosed')); self.s.mongos.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); // Set up serverConfig listeners self.s.mongos.on('fullsetup', relay('fullsetup')); // Emit open event self.emit('open', null, self); // Return correctly try { callback(null, self); } catch(err) { process.nextTick(function() { throw err; }) } } // Set up listeners self.s.mongos.once('timeout', connectErrorHandler('timeout')); self.s.mongos.once('error', connectErrorHandler('error')); self.s.mongos.once('close', connectErrorHandler('close')); self.s.mongos.once('connect', connectHandler); // Join and leave events self.s.mongos.on('joined', relay('joined')); self.s.mongos.on('left', relay('left')); // Reconnect server self.s.mongos.on('reconnect', reconnectHandler); // Start connection self.s.mongos.connect(_options); } // Server capabilities Mongos.prototype.capabilities = function() { if(this.s.sCapabilities) return this.s.sCapabilities; if(this.s.mongos.lastIsMaster() == null) return null; this.s.sCapabilities = new ServerCapabilities(this.s.mongos.lastIsMaster()); return this.s.sCapabilities; } define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); // Command Mongos.prototype.command = function(ns, cmd, options, callback) { this.s.mongos.command(ns, cmd, options, callback); } define.classMethod('command', {callback: true, promise:false}); // Insert Mongos.prototype.insert = function(ns, ops, options, callback) { this.s.mongos.insert(ns, ops, options, function(e, m) { callback(e, m) }); } define.classMethod('insert', {callback: true, promise:false}); // Update Mongos.prototype.update = function(ns, ops, options, callback) { this.s.mongos.update(ns, ops, options, callback); } define.classMethod('update', {callback: true, promise:false}); // Remove Mongos.prototype.remove = function(ns, ops, options, callback) { this.s.mongos.remove(ns, ops, options, callback); } define.classMethod('remove', {callback: true, promise:false}); // Destroyed Mongos.prototype.isDestroyed = function() { return this.s.mongos.isDestroyed(); } // IsConnected Mongos.prototype.isConnected = function() { return this.s.mongos.isConnected(); } define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); // Insert Mongos.prototype.cursor = function(ns, cmd, options) { options.disconnectHandler = this.s.store; return this.s.mongos.cursor(ns, cmd, options); } define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); Mongos.prototype.lastIsMaster = function() { return this.s.mongos.lastIsMaster(); } Mongos.prototype.close = function(forceClosed) { this.s.mongos.destroy(); // We need to wash out all stored processes if(forceClosed == true) { this.s.storeOptions.force = forceClosed; this.s.store.flush(); } } define.classMethod('close', {callback: false, promise:false}); Mongos.prototype.auth = function() { var args = Array.prototype.slice.call(arguments, 0); this.s.mongos.auth.apply(this.s.mongos, args); } define.classMethod('auth', {callback: true, promise:false}); Mongos.prototype.logout = function() { var args = Array.prototype.slice.call(arguments, 0); this.s.mongos.logout.apply(this.s.mongos, args); } define.classMethod('logout', {callback: true, promise:false}); /** * All raw connections * @method * @return {array} */ Mongos.prototype.connections = function() { return this.s.mongos.connections(); } define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); /** * A mongos connect event, used to verify that the connection is up and running * * @event Mongos#connect * @type {Mongos} */ /** * The mongos high availability event * * @event Mongos#ha * @type {function} * @param {string} type The stage in the high availability event (start|end) * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only * @param {number} data.id The id for this high availability request * @param {object} data.state An object containing the information about the current replicaset */ /** * A server member left the mongos set * * @event Mongos#left * @type {function} * @param {string} type The type of member that left (primary|secondary|arbiter) * @param {Server} server The server object that left */ /** * A server member joined the mongos set * * @event Mongos#joined * @type {function} * @param {string} type The type of member that joined (primary|secondary|arbiter) * @param {Server} server The server object that joined */ /** * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. * * @event Mongos#fullsetup * @type {Mongos} */ /** * Mongos open event, emitted when mongos can start processing commands. * * @event Mongos#open * @type {Mongos} */ /** * Mongos close event * * @event Mongos#close * @type {object} */ /** * Mongos error event, emitted if there is an error listener. * * @event Mongos#error * @type {MongoError} */ /** * Mongos timeout event * * @event Mongos#timeout * @type {object} */ /** * Mongos parseError event * * @event Mongos#parseError * @type {object} */ module.exports = Mongos;
// useful es6 shim if( !Array.prototype.find ) { Array.prototype.find = function (iteratee, thisArg) { if( typeof iteratee !== 'function' ) throw new TypeError('predicate must be a function'); for( var i = 0, n = this.length ; i < n ; i++ ) { if( iteratee.call(thisArg, this[i]) ) { return this[i]; } } }; } // nitro declaration var nitro = function (handler) { if( handler instanceof Function ) handler(nitro); return nitro; }, _ = require('nitro-tools'), fs = require('fs'), color = require('./color'), deasync = require('deasync'), noop = function (value) { return value; }, YAML = require('js-yaml'); var file = require('./file'), dir = require('./dir'), processors = require('./processors'), tasks = require('./tasks'), joinPaths = require('./join-paths'), server = require('./server'), livereload = require('./livereload'), autoRequire = require('./auto-require'), dirExpand = require('./dir-expand'); function returnNitro (fn) { return function () { fn.apply(this, arguments); return nitro; }; } _.extend(nitro, { color: color, noop: noop, cwdRoot: process.cwd(), cwd: require('./cwd'), joinPaths: joinPaths, exec: require('child_process').execSync || deasync( require('child_process').exec ), deasync: deasync, dir: dir, expand: function (pattern, options) { return dir('.').expand(pattern, options); }, isDir: function (dirpath) { try { return fs.statSync(dirpath).isDirectory(); } catch(err) { return false; } }, file: file, isFile: function (dirpath) { try { return fs.statSync(dirpath).isFile(); } catch(err) { return false; } }, tools: _, copy: function () { dir.copy.apply(this, arguments); return nitro; }, symlink: function (_path, target, type) { var dirpath = joinPaths.root( _path.replace(/\/[^\/]+$/, '') ); if( !dir.exists(dirpath) ) { dir.create(dirpath); } fs.symlinkSync( target, joinPaths.root(_path), type); return nitro; }, load: function (pattern, options) { return dir.load('.', pattern, options); }, // addPreset: returnNitro( processors.addPreset ), // loadProcessors: returnNitro( processors.loadPresets ), dirExpand: dirExpand, require: autoRequire, import: function (dirpath, filter) { if( !dir.exists(dirpath) ) { console.error('directory ' + color.yellow(dirpath) + ' does not exists'); process.exit(1); } dir(dirpath).load( filter || ( filter === false ? '*.js' : '{,**/}*.js' ) ) .each(function (f) { var fullpath = joinPaths.root( f.cwd, f.path ); if( fullpath === __filename ) return; require( fullpath )(nitro); }); return nitro; }, registerProcessor: returnNitro(processors.register), task: tasks, template: require('trisquel'), libs2html: dir.libs2html, watch: require('./watch'), livereload: function (dirpath, options) { options = options ? _.copy(options) : {}; if( options.highlight ) { options.highlight = autoRequire('cardinal').highlight; } livereload(options.server || server(__dirname + '/livereload', { port: options.port || 12345, log: false }), dirpath, options); }, parseJSON: function (json) { return JSON.parse(json); }, parseYAML: function (yaml, options) { options = options || {}; return YAML.safeLoad(yaml, { filename: options.filename, schema: options.schema, json: options.json, onWarning: function () { console.log.apply(console, ['YAML error'].concat(arguments)); if( options.onWarning instanceof Function ) options.onWarning.apply(this, arguments); } }); }, stringify: function (data, format, options) { format = format || 'json'; options = options || {}; if( format === 'json' ) { return JSON.stringify(data, null, options.indentBy || '\t' ); } else if( format === 'yaml' ) { return YAML.safeDump(data); } throw new Error('Stringify to ' + format + ' format not supported.'); }, run: function (taskList) { if( taskList && process.argv.length < 3 ) { console.error('needs at least 1 argument'); process.exit(1); } return tasks.run( taskList || [].slice.call(process.argv, 2)); }, server: server }); nitro.package = require('./package')(nitro); module.exports = nitro;
/* * 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'; /** * Application gateway probe health response match * */ class ApplicationGatewayProbeHealthResponseMatch { /** * Create a ApplicationGatewayProbeHealthResponseMatch. * @member {string} [body] Body that must be contained in the health * response. Default value is empty. * @member {array} [statusCodes] Allowed ranges of healthy status codes. * Default range of healthy status codes is 200-399. */ constructor() { } /** * Defines the metadata of ApplicationGatewayProbeHealthResponseMatch * * @returns {object} metadata of ApplicationGatewayProbeHealthResponseMatch * */ mapper() { return { required: false, serializedName: 'ApplicationGatewayProbeHealthResponseMatch', type: { name: 'Composite', className: 'ApplicationGatewayProbeHealthResponseMatch', modelProperties: { body: { required: false, serializedName: 'body', type: { name: 'String' } }, statusCodes: { required: false, serializedName: 'statusCodes', type: { name: 'Sequence', element: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } } } } }; } } module.exports = ApplicationGatewayProbeHealthResponseMatch;
type T = [x: A, y?: B, ...z: C];
import 'nanoid'; import './Debug-dda4b5bc.js'; import 'redux'; import './turn-order-62966a9c.js'; import 'immer'; import 'lodash.isplainobject'; import './reducer-763b001e.js'; import 'rfc6902'; import './initialize-ca65fd4a.js'; import './transport-0079de87.js'; export { C as Client } from './client-5202a476.js'; import 'flatted'; import './ai-92d44551.js'; export { L as LobbyClient, a as LobbyClientError } from './client-99609c4d.js';
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "Z.MU.", "Z.MW." ], "DAY": [ "Ku w\u2019indwi", "Ku wa mbere", "Ku wa kabiri", "Ku wa gatatu", "Ku wa kane", "Ku wa gatanu", "Ku wa gatandatu" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "Nzero", "Ruhuhuma", "Ntwarante", "Ndamukiza", "Rusama", "Ruheshi", "Mukakaro", "Nyandagaro", "Nyakanga", "Gitugutu", "Munyonyo", "Kigarama" ], "SHORTDAY": [ "cu.", "mbe.", "kab.", "gtu.", "kan.", "gnu.", "gnd." ], "SHORTMONTH": [ "Mut.", "Gas.", "Wer.", "Mat.", "Gic.", "Kam.", "Nya.", "Kan.", "Nze.", "Ukw.", "Ugu.", "Uku." ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y HH:mm:ss", "mediumDate": "d MMM y", "mediumTime": "HH:mm:ss", "short": "d/M/y HH:mm", "shortDate": "d/M/y", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "FBu", "DECIMAL_SEP": ",", "GROUP_SEP": ".", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a4", "posPre": "", "posSuf": "\u00a4" } ] }, "id": "rn", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
// o--------------------------------------------------------------------------------o // | This file is part of the RGraph package - you can learn more at: | // | | // | https://www.rgraph.net | // | | // | RGraph is licensed under the Open Source MIT license. That means that it's | // | totally free to use and there are no restrictions on what you can do with it! | // o--------------------------------------------------------------------------------o // // Initialise the various objects // RGraph = window.RGraph || {isrgraph:true,isRGraph: true,rgraph:true}; // // This function has been taken out of the RGraph.common.core.js file to // enable the CSV reader to work standalone. // if (!RGraph.AJAX) RGraph.AJAX = function () { var args = RGraph.getArgs(arguments, 'url,callback'); // Mozilla, Safari, ... if (window.XMLHttpRequest) { var httpRequest = new XMLHttpRequest(); // MSIE } else if (window.ActiveXObject) { var httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } httpRequest.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { this.__user_callback__ = callback; this.__user_callback__(this.responseText); } } httpRequest.open('GET', args.url, true); httpRequest.send(); }; // // Use the AJAX function above to fetch a string // if (!RGraph.AJAX.getString) RGraph.AJAX.getString = function () { var args = RGraph.getArgs(arguments, 'url,callback'); RGraph.AJAX(args.url, function () { var str = String(this.responseText); args.callback(str); }); }; // This function simply creates UID. Formerly the function in // RGraph.common.core.js was being used - but now the CSV code // is now standalone, hence this function if (!RGraph.createUID) RGraph.createUID = function () { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); }; RGraph.CSV = function () { var args = RGraph.getArgs(arguments, 'url,callback,separator,eol'); // // Some default values // this.url = args.url; this.ready = args.callback; this.data = null; this.numrows = null; this.numcols = null; this.separator = args.separator || ','; this.endofline = args.eol || /\r?\n/; this.uid = RGraph.createUID(); // // A Custom split function // // @param string str The CSV string to split // @param mixed char The character to split on - or it can also be an object like this: // { // preserve: false, // Whether to preserve whitespace // char: ',' // The character to split on // } // this.splitCSV = function (str, split) { // Defaults var arr = []; var field = ''; var inDoubleQuotes = false; var inSingleQuotes = false; var preserve = (typeof split === 'object' && split.preserve) ? true : false; // The character to split the CSV string on if (typeof split === 'object') { if (typeof split.char === 'string') { split = split.char; } else { split = ','; } } // If not an object just leave the char as it's supplied for (var i=0,len=str.length; i<len; i+=1) { char = str.charAt(i); if ( (char === '"') && !inDoubleQuotes) { inDoubleQuotes = true; continue; } else if ( (char === '"') && inDoubleQuotes) { inDoubleQuotes = false; continue; } if ( (char === "'") && !inSingleQuotes) { inSingleQuotes = true; continue; } else if ( (char === "'") && inSingleQuotes) { inSingleQuotes = false; continue; } else if (char === split && !inDoubleQuotes && !inSingleQuotes) { // TODO look ahead in order to allow for multi-character separators arr.push(field); field = ''; continue; } else { field = field + char; } } // Add the last field arr.push(field); // Now trim each value if necessary if (!preserve) { for (i=0,len=arr.length; i<len; i+=1) { arr[i] = arr[i].trim(); } } return arr; }; // // This function splits the CSV data into an array so that it can be useful. // this.fetch = function () { var sep = this.separator, eol = this.endofline, obj = this; if (this.url.substring(0,3) === 'id:' || this.url.substring(0,4) === 'str:') { // Get rid of any surrounding whitespace if (this.url.substring(0,3) === 'id:') { var data = document.getElementById(this.url.substring(3)).innerHTML.trim(); } else if (this.url.substring(0,4) === 'str:') { var data = this.url.substring(4).trim(); } // Store the CSV data on the CSV object (ie - this object) obj.data = data.split(eol); // Store the number of rows obj.numrows = obj.data.length; for (var i=0,len=obj.data.length; i<len; i+=1) { // // Split the individual line // //var row = obj.data[i].split(sep); var row = obj.splitCSV(obj.data[i], {preserve: false, char: sep}); if (!obj.numcols) { obj.numcols = row.length; } // // If the cell is purely made up of numbers - convert it // for (var j=0; j<row.length; j+=1) { if ((/^\-?[0-9.]+$/).test(row[j])) { row[j] = parseFloat(row[j]); } // Assign the split-up-row back to the data array obj.data[i] = row; } } // Call the ready function straight away obj.ready(obj); } else { RGraph.AJAX.getString({url: this.url, callback: function (data) { data = data.replace(/(\r?\n)+$/, ''); // // Split the lines in the CSV // obj.data = data.split(eol); // // Store the number of rows // obj.numrows = obj.data.length; // // Loop thru each lines in the CSV file // for (var i=0,len=obj.data.length; i<len; i+=1) { // // Use the new split function to split each row NOT preserving whitespace // //var row = obj.data[i].split(sep); var row = obj.splitCSV(obj.data[i], {preserve: false, char: sep}); if (!obj.numcols) { obj.numcols = row.length; } // // If the cell is purely made up of numbers - convert it // for (var j=0; j<row.length; j+=1) { if ((/^\-?[0-9.]+$/).test(row[j])) { row[j] = parseFloat(row[j]); } // Assign the split-up-row back to the data array obj.data[i] = row; } } // Call the ready function straight away obj.ready(obj); }}); } }; // // Returns a row of the CSV file // // @param number index The index of the row to fetch // @param start OPTIONAL If desired you can specify a column to // start at (which starts at 0 by default) // this.row = this.getRow = function (index) { var row = [], start = parseInt(arguments[1]) || 0; row = this.data[index].slice(start); return row; }; // // Returns a column of the CSV file // // @param number index The index of the column to fetch // @param start OPTIONAL If desired you can specify a row to start at (which starts at 0 by default) // this.col = this.column = this.getCol = this.getColumn = function (index) { var col = [], start = arguments[1] || 0; for (var i=start; i<this.data.length; i+=1) { if (this.data[i] && this.data[i][index]) { col.push(this.data[i][index]); } else { col.push(null); } } return col; }; // Fetch the CSV file this.fetch(); };
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import _extends from "@babel/runtime/helpers/esm/extends"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import formControlState from '../FormControl/formControlState'; import useFormControl from '../FormControl/useFormControl'; import capitalize from '../utils/capitalize'; import withStyles from '../styles/withStyles'; export const styles = theme => ({ /* Styles applied to the root element. */ root: _extends({ color: theme.palette.text.secondary }, theme.typography.body1, { lineHeight: 1, padding: 0, '&$focused': { color: theme.palette.primary.main }, '&$disabled': { color: theme.palette.text.disabled }, '&$error': { color: theme.palette.error.main } }), /* Styles applied to the root element if the color is secondary. */ colorSecondary: { '&$focused': { color: theme.palette.secondary.main } }, /* Pseudo-class applied to the root element if `focused={true}`. */ focused: {}, /* Pseudo-class applied to the root element if `disabled={true}`. */ disabled: {}, /* Pseudo-class applied to the root element if `error={true}`. */ error: {}, /* Pseudo-class applied to the root element if `filled={true}`. */ filled: {}, /* Pseudo-class applied to the root element if `required={true}`. */ required: {}, /* Styles applied to the asterisk element. */ asterisk: { '&$error': { color: theme.palette.error.main } } }); const FormLabel = /*#__PURE__*/React.forwardRef(function FormLabel(props, ref) { const { children, classes, className, component: Component = 'label' } = props, other = _objectWithoutPropertiesLoose(props, ["children", "classes", "className", "color", "component", "disabled", "error", "filled", "focused", "required"]); const muiFormControl = useFormControl(); const fcs = formControlState({ props, muiFormControl, states: ['color', 'required', 'focused', 'disabled', 'error', 'filled'] }); return /*#__PURE__*/React.createElement(Component, _extends({ className: clsx(classes.root, classes[`color${capitalize(fcs.color || 'primary')}`], className, fcs.disabled && classes.disabled, fcs.error && classes.error, fcs.filled && classes.filled, fcs.focused && classes.focused, fcs.required && classes.required), ref: ref }, other), children, fcs.required && /*#__PURE__*/React.createElement("span", { "aria-hidden": true, className: clsx(classes.asterisk, fcs.error && classes.error) }, "\u2009", '*')); }); process.env.NODE_ENV !== "production" ? FormLabel.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * The content of the component. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * The color of the component. It supports those theme colors that make sense for this component. */ color: PropTypes.oneOf(['primary', 'secondary']), /** * The component used for the root node. * Either a string to use a HTML element or a component. */ component: PropTypes.elementType, /** * If `true`, the label should be displayed in a disabled state. */ disabled: PropTypes.bool, /** * If `true`, the label should be displayed in an error state. */ error: PropTypes.bool, /** * If `true`, the label should use filled classes key. */ filled: PropTypes.bool, /** * If `true`, the input of this label is focused (used by `FormGroup` components). */ focused: PropTypes.bool, /** * If `true`, the label will indicate that the input is required. */ required: PropTypes.bool } : void 0; export default withStyles(styles, { name: 'MuiFormLabel' })(FormLabel);
import _extends from"@babel/runtime/helpers/esm/extends";import _objectWithoutProperties from"@babel/runtime/helpers/esm/objectWithoutProperties";import*as React from"react";import PropTypes from"prop-types";import clsx from"clsx";import withStyles from"../styles/withStyles";import ListContext from"../List/ListContext";export var styles={root:{minWidth:56,flexShrink:0},alignItemsFlexStart:{marginTop:8}};var ListItemAvatar=React.forwardRef(function(e,t){var s=e.classes,r=e.className,o=_objectWithoutProperties(e,["classes","className"]),i=React.useContext(ListContext);return React.createElement("div",_extends({className:clsx(s.root,r,"flex-start"===i.alignItems&&s.alignItemsFlexStart),ref:t},o))});"production"!==process.env.NODE_ENV&&(ListItemAvatar.propTypes={children:PropTypes.element.isRequired,classes:PropTypes.object.isRequired,className:PropTypes.string});export default withStyles(styles,{name:"MuiListItemAvatar"})(ListItemAvatar);
/*jshint eqnull:true */ /*! * jQuery Cookie Plugin v1.1 * https://github.com/carhartl/jquery-cookie * * Copyright 2011, Klaus Hartl * Dual licensed under the MIT or GPL Version 2 licenses. * http://www.opensource.org/licenses/mit-license.php * http://www.opensource.org/licenses/GPL-2.0 */ (function($, document) { var pluses = /\+/g; function raw(s) { return s; } function decoded(s) { return decodeURIComponent(s.replace(pluses, ' ')); } $.cookie = function(key, value, options) { // key and at least value given, set cookie... if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value == null)) { options = $.extend({}, $.cookie.defaults, options); if (value == null) { options.expires = -1; } if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setDate(t.getDate() + days); } value = String(value); return (document.cookie = [ encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } // key and possibly options given, get cookie... options = value || $.cookie.defaults || {}; var decode = options.raw ? raw : decoded; var cookies = document.cookie.split('; '); for (var i = 0, parts; (parts = cookies[i] && cookies[i].split('=')); i++) { if (decode(parts.shift()) === key) { return decode(parts.join('=')); } } return null; }; $.cookie.defaults = {}; $.removeCookie = function (key, options) { if ($.cookie(key) !== undefined) { // Must not alter options, thus extending a fresh object... $.cookie(key, '', $.extend({}, options, { expires: -1 })); return true; } return false; }; })(jQuery, document);
import Ember from "ember-metal/core"; import { meta as metaFor, typeOf } from "ember-metal/utils"; import { defineProperty as o_defineProperty, hasPropertyAccessors } from "ember-metal/platform"; import { MANDATORY_SETTER_FUNCTION, DEFAULT_GETTER_FUNCTION } from "ember-metal/properties"; export function watchKey(obj, keyName, meta) { // can't watch length on Array - it is special... if (keyName === 'length' && typeOf(obj) === 'array') { return; } var m = meta || metaFor(obj); var watching = m.watching; // activate watching first time if (!watching[keyName]) { watching[keyName] = 1; var desc = m.descs[keyName]; if (desc && desc.willWatch) { desc.willWatch(obj, keyName); } if ('function' === typeof obj.willWatchProperty) { obj.willWatchProperty(keyName); } if (Ember.FEATURES.isEnabled('mandatory-setter')) { if (hasPropertyAccessors) { handleMandatorySetter(m, obj, keyName); } } } else { watching[keyName] = (watching[keyName] || 0) + 1; } } if (Ember.FEATURES.isEnabled('mandatory-setter')) { var handleMandatorySetter = function handleMandatorySetter(m, obj, keyName) { var descriptor = Object.getOwnPropertyDescriptor && Object.getOwnPropertyDescriptor(obj, keyName); var configurable = descriptor ? descriptor.configurable : true; var isWritable = descriptor ? descriptor.writable : true; var hasValue = descriptor ? 'value' in descriptor : true; // this x in Y deopts, so keeping it in this function is better; if (configurable && isWritable && hasValue && keyName in obj) { m.values[keyName] = obj[keyName]; o_defineProperty(obj, keyName, { configurable: true, enumerable: Object.prototype.propertyIsEnumerable.call(obj, keyName), set: MANDATORY_SETTER_FUNCTION(keyName), get: DEFAULT_GETTER_FUNCTION(keyName) }); } }; } export function unwatchKey(obj, keyName, meta) { var m = meta || metaFor(obj); var watching = m.watching; if (watching[keyName] === 1) { watching[keyName] = 0; var desc = m.descs[keyName]; if (desc && desc.didUnwatch) { desc.didUnwatch(obj, keyName); } if ('function' === typeof obj.didUnwatchProperty) { obj.didUnwatchProperty(keyName); } if (Ember.FEATURES.isEnabled('mandatory-setter')) { if (hasPropertyAccessors && keyName in obj) { o_defineProperty(obj, keyName, { configurable: true, enumerable: Object.prototype.propertyIsEnumerable.call(obj, keyName), set: function(val) { // redefine to set as enumerable o_defineProperty(obj, keyName, { configurable: true, writable: true, enumerable: true, value: val }); delete m.values[keyName]; }, get: DEFAULT_GETTER_FUNCTION(keyName) }); } } } else if (watching[keyName] > 1) { watching[keyName]--; } }
/* * 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'; var models = require('./index'); var util = require('util'); /** * @class * Initializes a new instance of the AdlsRuntimeException class. * @constructor * A WebHDFS exception thrown when an unexpected error occurs during an * operation. Thrown when a 500 error response code is returned (Internal * server error). * */ function AdlsRuntimeException() { AdlsRuntimeException['super_'].call(this); } util.inherits(AdlsRuntimeException, models['AdlsRemoteException']); /** * Defines the metadata of AdlsRuntimeException * * @returns {object} metadata of AdlsRuntimeException * */ AdlsRuntimeException.prototype.mapper = function () { return { required: false, serializedName: 'RuntimeException', type: { name: 'Composite', className: 'AdlsRuntimeException', modelProperties: { javaClassName: { required: false, readOnly: true, serializedName: 'javaClassName', type: { name: 'String' } }, message: { required: false, readOnly: true, serializedName: 'message', type: { name: 'String' } }, exception: { required: true, serializedName: 'exception', type: { name: 'String' } } } } }; }; module.exports = AdlsRuntimeException;
System.register([],function(e,t){"use strict";t&&t.id;return{setters:[],execute:function(){}}}); //# sourceMappingURL=index.js.map
'use strict'; exports.init = () => { const dsn = process.env.SENTRY_DSN; if (dsn) { const raven = require('raven'); return new raven.Client(dsn); } };
export default function Home() { return <div>Hello World!</div> }
export const SERVER_URI = process.env.SERVER_URI || 'http://127.0.0.1:3000'; export const GET_TOKEN_REQUEST = 'GET_TOKEN_REQUEST'; export const GET_TOKEN_SUCCESS = 'GET_TOKEN_SUCCESS'; export const GET_TOKEN_FAILED = 'GET_TOKEN_FAILED'; export const START_MICROPHONE = 'START_MICROPHONE'; export const STOP_MICROPHONE = 'STOP_MICROPHONE'; export const TEXT_RESULT = 'TEXT_RESULT';
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- // JavaScript source code WScript.LoadScriptFile("..\\UnitTestFramework\\UnitTestFramework.js"); var handler = { getOwnPropertyDescriptor: function (target, name) { return emulatedProps[name]; }, defineProperty: function (target, name, desc) { emulatedProps[name] = desc; // $LOG('success: ' + success); return success[name]; }, preventExtensions: function (target) { Object.defineProperties(target, emulatedProps); Object.preventExtensions(target); return true; }, deleteProperty: function (target, name) { delete emulatedProps[name]; return success[name]; }, get: function (target, name, receiver) { var desc = emulatedProps[name]; if (desc === undefined) { return emulatedProto[name]; } if ('value' in desc) return desc.value; if ('get' in desc) return desc.get.call(target); }, set: function (target, name, value, receiver) { return success[name]; }, has: function (target, name) { return !!emulatedProps[name]; }, hasOwn: function (target, name) { return !!emulatedProps[name]; }, ownKeys: function (target) { return Object.getOwnPropertyNames(emulatedProps); }, enumerate: function (target) { return Object.getOwnPropertyNames(emulatedProps).filter(function (name) { return emulatedProps[name].enumerable; }); } }; var tests = [ { name: "non-configurable property can't be reported as non-existent", body: function () { var target = {}; emulatedProps = {}; emulatedProps.x = { value: 'test', configurable: false }; Object.defineProperty(target, 'x', emulatedProps.x); var proxy = new Proxy(target, handler); // Checkout handler code at the bottom var desc; delete emulatedProps.x; assert.throws(function () { desc = Object.getOwnPropertyDescriptor(proxy, 'x'); }, TypeError, "Cannot return non-existent for a non-configurable property"); }, }, { name: "existing property on non-extensible object cannot be reported as non-existent", body: function(){ var target = {}; emulatedProps = {}; target.x = 20; Object.preventExtensions(target); var desc; var proxy = new Proxy(target, handler); // Checkout handler code at the bottom assert.throws(function () { desc = Object.getOwnPropertyDescriptor(proxy, 'x'); }, TypeError); } }, { name: "non existing property on non-extensible object cannot be reported as existent", body: function () { var target = {}; emulatedProps = {}; emulatedProps.x = { value: 1, configurable: false }; Object.preventExtensions(target); var proxy = new Proxy(target, handler); assert.throws(function () { Object.getOwnPropertyDescriptor(proxy, 'x') }, TypeError); } }, { name:'configurable property cannot be reported as non-configurable', body: function () { var target = {}; emulatedProps = {}; emulatedProps.x = { value: 1, configurable: false }; Object.defineProperty(target, 'x', { value: 1, configurable: true }); var proxy = new Proxy(target, handler); assert.throws(function () { desc = Object.getOwnPropertyDescriptor(proxy, 'x') }, TypeError, "configurable property cannot be reported as non-configurable"); } }, { name: "a non-existent property cannot be reported as non-configurable", body: function() { emulatedProps = {}; var target = {}; Object.defineProperty(emulatedProps, 'y', { value: 'test', configurable: 'false' }); var proxy = new Proxy(target, handler); assert.throws(function () { var desc = Object.getOwnPropertyDescriptor(proxy, 'y') }, TypeError, "a non-existent property cannot be reported as non-configurable"); } }, { name: "can't add property on non-extensible object.", body: function () { var target = {}; Object.preventExtensions(target); emulatedProps = {}; emulatedProps.x = 5; var proxy = new Proxy(target, emulatedProps); success = function () { }; assert.throws(function () { Object.defineProperty(proxy, 'x', { value: 20 }) }, TypeError); }, }, { name: "target property must be non-configurable after set as such in proxy #1", body: function () { var target = {}; emulatedProps = {}; var proxy = new Proxy(target, handler); success = function () { }; success.x = 21; assert.throws(function () { Object.defineProperty(proxy, 'x', { value: 20, configurable: false }) }, TypeError); }, }, { name: "target property must be non-configurable after set as such in proxy #2", body: function () { var target = {}; emulatedProps = {}; emulatedProps.x = 5; var proxy = new Proxy(target, handler); Object.defineProperty(target, 'x', { value: 41, configurable: true }); success = function () { }; success.x = 21; assert.throws(function () { Object.defineProperty(proxy, 'x', { value: 20, configurable: false }) }, TypeError); }, }, ]; testRunner.runTests(tests, { verbose: WScript.Arguments[0] != "summary" });
"use strict"; import store from "../store"; export default (network, channel) => { if (!network.isCollapsed || channel.highlight || channel.type === "lobby") { return false; } if (store.state.activeChannel && channel === store.state.activeChannel.channel) { return false; } return true; };
/* * jitsu.js: Top-level include for the jitsu module. * * (C) 2010, Nodejitsu Inc. * */ var path = require('path'), util = require('util'), colors = require('colors'), flatiron = require('flatiron') godaddy = require('./jitsu/commands/godaddy'); var jitsu = module.exports = flatiron.app; // // Setup `jitsu` to use `pkginfo` to expose version // require('pkginfo')(module, 'name', 'version'); // // Configure jitsu to use `flatiron.plugins.cli` // jitsu.use(flatiron.plugins.cli, { version: true, usage: require('./jitsu/usage'), source: path.join(__dirname, 'jitsu', 'commands'), argv: { version: { alias: 'v', description: 'print jitsu version and exit', string: true }, localconf: { description: 'search for .jitsuconf file in ./ and then parent directories', string: true }, jitsuconf: { alias: 'j', description: 'specify file to load configuration from', string: true }, noanalyze: { description: 'skip require-analyzer: do not attempt to dynamically detect dependencies', boolean: true }, colors: { description: '--no-colors will disable output coloring', default: true, boolean: true }, confirm: { alias: 'c', description: 'prevents jitsu from asking before overwriting/removing things', default: false, boolean: true }, release: { alias: 'r', description: 'specify release version number or semantic increment (build, patch, minor, major)', string: true }, raw: { description: 'jitsu will only output line-delimited raw JSON (useful for piping)', boolean: true } } }); jitsu.options.log = { console: { raw: jitsu.argv.raw } }; // // Setup config, users, command aliases and prompt settings // jitsu.prompt.properties = flatiron.common.mixin( jitsu.prompt.properties, require('./jitsu/properties') ); jitsu.prompt.override = jitsu.argv; require('./jitsu/config'); require('./jitsu/alias'); require('./jitsu/commands'); // // Setup other jitsu settings. // jitsu.started = false; jitsu.common = require('./jitsu/common'); jitsu.package = require('./jitsu/package'); jitsu.logFile = new (require('./jitsu/common/logfile').LogFile)(path.join(process.env.HOME, '.jitsulog')); // // Hoist `jitsu.api` from `nodejitsu-api` module. // jitsu.api = {}; jitsu.api.Client = require('nodejitsu-api').Client; jitsu.api.Apps = require('nodejitsu-api').Apps; jitsu.api.Databases = require('nodejitsu-api').Databases; jitsu.api.Logs = require('nodejitsu-api').Logs; jitsu.api.Snapshots = require('nodejitsu-api').Snapshots; jitsu.api.Users = require('nodejitsu-api').Users; jitsu.api.Tokens = require('nodejitsu-api').Tokens; // // ### function welcome () // Print welcome message. // jitsu.welcome = function () { // // If a user is logged in, show username // var username = jitsu.config.get('username') || ''; godaddy.notice(jitsu); jitsu.log.info('Welcome to ' + 'Nodejitsu'.grey + ' ' + username.magenta); jitsu.log.info('jitsu v' + jitsu.version + ', node ' + process.version); jitsu.log.info('It worked if it ends with ' + 'Nodejitsu'.grey + ' ok'.green.bold); }; // // ### function start (command, callback) // #### @command {string} Command to execute once started // #### @callback {function} Continuation to pass control to when complete. // Starts the jitsu CLI and runs the specified command. // jitsu.start = function (callback) { // // Check for --no-colors/--colors option, without hitting the config file // yet // var useColors = (typeof jitsu.argv.colors == 'undefined' || jitsu.argv.colors); useColors || (colors.mode = "none"); // // whoami command should not output anything but username // if (jitsu.argv._[0] === "whoami") { console.log(jitsu.config.get('username') || ''); return; } jitsu.init(function (err) { if (err) { jitsu.welcome(); jitsu.showError(jitsu.argv._.join(' '), err); return callback(err); } jitsu.common.checkVersion(function (err) { if (err) { return callback(); } var minor, username; // // --no-colors option turns off output coloring, and so does setting // colors: false in ~/.jitsuconf (see // https://github.com/nodejitsu/jitsu/issues/101 ) // if ( !jitsu.config.get('colors') || !useColors ) { colors.mode = "none"; jitsu.log.get('default').stripColors = true; jitsu.log.get('default').transports.console.colorize = false; } jitsu.welcome(); minor = process.version.split('.')[1]; if (parseInt(minor, 10) % 2) { jitsu.log.warn('You are using unstable version of node.js. You may experience problems.'); } username = jitsu.config.get('username'); if (!username && jitsu.config.get('requiresAuth').indexOf(jitsu.argv._[0]) !== -1) { return jitsu.commands.users.login(function (err) { if (err) { jitsu.showError(jitsu.argv._.join(' '), err); return callback(err); } var username = jitsu.config.get('username'); jitsu.log.info('Successfully configured user ' + username.magenta); return jitsu.exec(jitsu.argv._, callback); }); } return jitsu.exec(jitsu.argv._, callback); }); }); }; // // ### function exec (command, callback) // #### @command {string} Command to execute // #### @callback {function} Continuation to pass control to when complete. // Runs the specified command in the jitsu CLI. // jitsu.exec = function (command, callback) { function execCommand (err) { if (err) { return callback(err); } // // Remark: This is a temporary fix for aliasing init=>install, // was having a few issues with the alias command on the install resource // if (command[0] === 'init') { command[0] = 'install'; } // Alias db to databases if (command[0] === 'db' || command[0] === 'dbs' || command[0] === 'database') { command[0] = 'databases'; } // Allow `jitsu logs` as a shortcut for `jitsu logs app` if (command[0] === 'logs' && command.length === 1) { command[1] = 'app'; } // Allow `jitsu host` as a shortcut for `jitsu config set remoteHost` if (command[0] === 'host' && command.length === 2) { command[3] = command[1]; command[0] = 'config'; command[1] = 'set'; command[2] = 'remoteHost'; } // // Prevent sign-ups on our alias as well as on the regular route. // if (command[0] === 'signup' || command[0] === 'users' && command[1] === 'create') { godaddy.disabled(jitsu, command.join(' ')); return callback(new Error('Signup is disabled')); } jitsu.log.info('Executing command ' + command.join(' ').magenta); jitsu.router.dispatch('on', command.join(' '), jitsu.log, function (err, shallow) { if (err) { jitsu.showError(command.join(' '), err, shallow); return callback(err); } // // TODO (indexzero): Something here // callback(); }); } return !jitsu.started ? jitsu.setup(execCommand) : execCommand(); }; // // ### function setup (callback) // #### @callback {function} Continuation to pass control to when complete. // Sets up the instances of the Resource clients for jitsu. // there is no io here, yet this function is ASYNC. // jitsu.setup = function (callback) { if (jitsu.started === true) { return callback(); } var rejectUnauthorized = jitsu.config.get('rejectUnauthorized'); if (typeof rejectUnauthorized === 'undefined') { jitsu.config.set('rejectUnauthorized', false); } var userAgent = jitsu.config.get('headers:user-agent'); if (!userAgent) { jitsu.config.set('headers:user-agent', 'jitsu/' + jitsu.version); } ['Users', 'Apps', 'Snapshots', 'Databases', 'Logs', 'Tokens'].forEach(function (key) { var k = key.toLowerCase(); jitsu[k] = new jitsu.api[key](jitsu.config); jitsu[k].on('debug::request', debug); jitsu[k].on('debug::response', debug); function debug (data) { if (jitsu.argv.debug || jitsu.config.get('debug')) { if (data.headers && data.headers['Authorization']) { data = JSON.parse(JSON.stringify(data)); data.headers['Authorization'] = Array(data.headers['Authorization'].length).join('*'); } util.inspect(data, false, null, true).split('\n').forEach(jitsu.log.debug); } }; }); jitsu.started = true; callback(); }; // // ### function showError (command, err, shallow, skip) // #### @command {string} Command which has errored. // #### @err {Error} Error received for the command. // #### @shallow {boolean} Value indicating if a deep stack should be displayed // #### @skip {boolean} Value indicating if this error should be forcibly suppressed. // Displays the `err` to the user for the `command` supplied. // jitsu.showError = function (command, err, shallow, skip) { var username, display, errors, stack; // // ### function unknownError(message, stack) // Displays an unknown error by dumping the call `stack` // and a given `message`. // function unknownError(message, stack) { jitsu.log.error(message); stack.split('\n').forEach(function (line) { jitsu.log.error(line); }) } // // ### function solenoidError(display) // Displays a "solenoid" error. // function solenoidError(display) { jitsu.log.error('Error starting application. This could be a user error.'); display.solenoid.split('\n').forEach(function (line) { jitsu.log.error(line); }); } // // ### function appError(display) // Displays an "application" error. // function appError(display) { if (display.output) { jitsu.log.error('Error output from application. This is usually a user error.'); display.output.split('\n').forEach(function (line) { jitsu.log.error(line); }) } return !display.solenoid ? unknownError(display.message, display.stack) : solenoidError(display); } if (err.statusCode === 403) { //jitsu.log.error('403 ' + err.result.error); } else if (err.statusCode === 503) { if (err.result && err.result.message) { jitsu.log.error(err.result.message); } else { jitsu.log.error('The Nodejitsu cloud is currently at capacity. Please try again later.'); } } else if (!skip) { jitsu.log.error('Error running command ' + command.magenta); if (!jitsu.config.get('nolog')) { jitsu.logFile.log(err); } if (err.result) { if (err.result.message) { jitsu.log.error(err.result.message); } if (err.result.error && typeof err.result.error == 'string') { if (~err.result.error.indexOf('matching versions')) { jitsu.log.error(err.result.error); jitsu.log.error("Do not use a specific engine version, try a generic one (eg: 0.8.x or 0.10.x)"); } else { jitsu.log.error(err.result.error); } } if (err.result.errors && Array.isArray(err.result.errors)) { errors = { connection: err.result.errors.filter(function (err) { return err.blame === 'connection'; }), application: err.result.errors.filter(function (err) { return err.blame === 'application'; }), solenoid: err.result.errors.filter(function (err) { return err.blame === 'solenoid'; }) }; if (errors.application.length) { return appError(errors.application[0]); } else if (errors.solenoid.length) { return solenoidError(errors.solenoid[0]) } return errors.connection.length ? unknownError('Error contacting drone(s):', errors.connection[0].stack) : unknownError('Error returned from Nodejitsu:', err.result.errors[0].stack); } else if (err.result.stack) { return unknownError('Error returned from Nodejitsu:', err.result.stack); } } else { if (err.stack && !shallow) { if (err.message && err.message === 'socket hang up' && err.code && err.code === 'ECONNRESET') { jitsu.log.info('The nodejitsu api reset the connection'); jitsu.log.help('This error may be due to the application or the drone server'); } else if (err.message && err.message === 'ETIMEDOUT'){ jitsu.log.info( 'jitsu\'s client request timed out before the server ' + 'could respond. Please increase your client timeout'); jitsu.log.help('(Example: `jitsu config set timeout 480000`)'); jitsu.log.help('This error may be due to network connection problems'); } else { err.stack.split('\n').forEach(function (trace) { jitsu.log.error(trace); }); } return; } } if (err.message) { jitsu.log.error(err.message); } } jitsu.log.help("For help with this error contact Nodejitsu Support:"); jitsu.log.help(" webchat: <http://webchat.nodejitsu.com/>"); jitsu.log.help(" irc: <irc://chat.freenode.net/#nodejitsu>"); jitsu.log.help(" email: <support@nodejitsu.com>"); jitsu.log.help(""); jitsu.log.help(" Copy and paste this output to a gist (http://gist.github.com/)"); jitsu.log.info('Nodejitsu '.grey + 'not ok'.red.bold); };
"use strict"; function interpLinear(i, i0, v0, v1) { var d = i - i0; return v0 * (1 - d) + v1 * d; } function interpNearest(i, i0, v0, v1) { return (i - i0) < 0.5 ? v0 : v1; } class AudioResampler { constructor(channels, sourceRate, targetRate, interpolation) { if (channels <= 0) throw new TypeError("Invalid channel count"); this.channels = channels; this.sourceRate = sourceRate; this.targetRate = targetRate; this.interpolation = interpolation || "linear"; const interp = { linear: interpLinear, nearest: interpNearest, }; if (!interp[this.interpolation]) throw new Error("Unknown interpolation type"); this.interp = interp[this.interpolation]; } process(buffer) { var ratio = this.sourceRate / this.targetRate; var resampled = new Float32Array(buffer.length / ratio); var bufferLength = buffer.length; var interp = this.interp; var channels = this.channels; if (channels == 1) { for (var i = 0, r = 0; i < bufferLength; i += ratio) { var i0 = Math.floor(i); var i1 = i0 + 1; while (i1 >= buffer.length) i1--; resampled[r++] = interp(i, i0, buffer[i0], buffer[i1]); } } else { var channelLength = bufferLength / channels; for (var c = 0; c < channels; c++) { for (var i = 0, r = 0; i < channelLength; i += ratio) { var ifl = Math.floor(i); var i0 = ifl * channels + c; var i1 = i0 + channels; while (i0 >= buffer.length) i0 -= channels; while (i1 >= buffer.length) i1 -= channels; resampled[r++ * channels + c] = interp(i, ifl, buffer[i0], buffer[i1]); } } } return resampled; } destroy() {} } module.exports = AudioResampler;
define(function(require) { 'use strict'; var $ = require('jquery'); var moment = require('moment'); var __ = require('orotranslation/js/translator'); var localeSettings = require('orolocale/js/locale-settings'); var locale = localeSettings.getLocale(); require('jquery-ui'); $.datepicker.regional[locale] = { closeText: __('oro.ui.datepicker.close'), // Display text for close link prevText: __('oro.ui.datepicker.prev'), // Display text for previous month link nextText: __('oro.ui.datepicker.next'), // Display text for next month link currentText: __('oro.ui.datepicker.today'), // Display text for current month link // ["January","February","March","April","May","June", "July", // "August","September","October","November","December"] // Names of months for drop-down and formatting monthNames: localeSettings.getCalendarMonthNames('wide', true), // ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] For formatting monthNamesShort: localeSettings.getCalendarMonthNames('abbreviated', true), // ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] For formatting dayNames: localeSettings.getCalendarDayOfWeekNames('wide', true), // ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] For formatting dayNamesShort: localeSettings.getCalendarDayOfWeekNames('abbreviated', true), // ["Su","Mo","Tu","We","Th","Fr","Sa"] Column headings for days starting at Sunday dayNamesMin: localeSettings.getCalendarDayOfWeekNames('narrow', true), weekHeader: __('oro.ui.datepicker.wk'), // Column header for week of the year // See format options on parseDate dateFormat: localeSettings.getVendorDateTimeFormat('jquery_ui', 'date', 'mm/dd/yy'), firstDay: localeSettings.getCalendarFirstDayOfWeek() - 1, // The first day of the week, Sun = 0, Mon = 1, ... //isRTL: false, // True if right-to-left language, false if left-to-right //showMonthAfterYear: false, // True if the year select precedes month, false for month then year //yearSuffix: "" // Additional text to append to the year in the month headers gotoCurrent: true, // True if today link goes back to current selection instead applyTodayDateSelection: true // Select the date on Today button click }; $.datepicker.setDefaults($.datepicker.regional[locale]); (function() { var _gotoToday = $.datepicker._gotoToday; var _updateDatepicker = $.datepicker._updateDatepicker; /** * Select today Date takes in account system timezone * @inheritDoc */ $.datepicker._gotoToday = function(id) { var inst = this._getInst($(id)[0]); var now = moment.tz(localeSettings.getTimeZone()); inst.currentDay = now.date(); inst.currentMonth = now.month(); inst.currentYear = now.year(); _gotoToday.apply(this, arguments); if (this._get(inst, 'applyTodayDateSelection')) { // select current day and close dropdown this._selectDate(id); inst.input.blur(); } }; /** * Today Date highlight takes in account system timezone * @inheritDoc */ $.datepicker._updateDatepicker = function(inst) { var today = moment.tz(localeSettings.getTimeZone()); _updateDatepicker.apply(this, arguments); // clear highlighted date inst.dpDiv .find('.ui-datepicker-today').removeClass('ui-datepicker-today') .find('a').removeClass('ui-state-highlight'); if (inst.drawYear === today.year() && inst.drawMonth === today.month()) { // highlighted today date in system timezone inst.dpDiv .find('td > a.ui-state-default').each(function() { if (today.date().toString() === this.innerHTML) { $(this).addClass('ui-state-highlight').parent().addClass('ui-datepicker-today'); } }); } }; })(); });
// Array.prototype.findIndex - MIT License (c) 2013 Paul Miller <http://paulmillr.com> // For all details and docs: <https://github.com/paulmillr/Array.prototype.findIndex> (function (globals) { if (Array.prototype.findIndex) return; var findIndex = function(predicate) { var list = Object(this); var length = Math.max(0, list.length) >>> 0; // ES.ToUint32; if (length === 0) return -1; if (typeof predicate !== 'function' || Object.prototype.toString.call(predicate) !== '[object Function]') { throw new TypeError('Array#findIndex: predicate must be a function'); } var thisArg = arguments.length > 1 ? arguments[1] : undefined; for (var i = 0; i < length; i++) { if (predicate.call(thisArg, list[i], i, list)) return i; } return -1; }; if (Object.defineProperty) { try { Object.defineProperty(Array.prototype, 'findIndex', { value: findIndex, configurable: true, writable: true }); } catch(e) {} } if (!Array.prototype.findIndex) { Array.prototype.findIndex = findIndex; } }(this));
YUI.add('aui-viewport', function (A, NAME) { var Lang = A.Lang, getClassName = A.getClassName, defaults = A.namespace('config.viewport'), CSS_PREFIX = getClassName('view') + A.config.classNameDelimiter, DEFAULTS_COLUMNS = defaults.columns || (defaults.columns = { 12: 960, 9: 720, 6: 480, 4: 320 }), DEFAULTS_MIN_COLUMNS = defaults.minColumns || (defaults.minColumns = 4), DOC_EL = A.config.doc.documentElement, WIN = A.getWin(), REGEX_CLASSNAMES = new RegExp('(\\s|\\b)+' + CSS_PREFIX + '(lt|gt)*\\d+(\\b|\\s)+', 'g'); var viewportChange = function(event) { var buffer = []; var oldClassNames = DOC_EL.className.replace(REGEX_CLASSNAMES, ''); var classNames = oldClassNames; var viewportWidth = DOC_EL.clientWidth; var viewportMaxColumns = DEFAULTS_MIN_COLUMNS; var gtLt; var col; for (var i in DEFAULTS_COLUMNS) { col = DEFAULTS_COLUMNS[i]; if (viewportWidth >= col) { gtLt = 'gt'; viewportMaxColumns = Math.max(viewportMaxColumns, col); } else { gtLt = 'lt'; } buffer.push(CSS_PREFIX + gtLt + col); } buffer.push(CSS_PREFIX + viewportMaxColumns); classNames += ' ' + buffer.join(' '); if (oldClassNames != classNames) { DOC_EL.className = classNames; } }; var resizeHandle = WIN.on('resize', A.debounce(viewportChange, 50)); var orientationHandle = WIN.on('orientationchange', viewportChange); viewportChange(); A.Viewport = { viewportChange: viewportChange, _orientationHandle: orientationHandle, _resizeHandle: resizeHandle }; }, '2.5.0', {"requires": ["aui-node", "aui-component"]});
import { meta as metaFor } from './meta'; import { assert, runInDebug, deprecate } from './debug'; import isEnabled from './features'; let runInTransaction, didRender, assertNotRendered; let raise = assert; if (isEnabled('ember-glimmer-allow-backtracking-rerender')) { raise = (message, test) => { deprecate(message, test, { id: 'ember-views.render-double-modify', until: '3.0.0' }); }; } let implication; if (isEnabled('ember-glimmer-allow-backtracking-rerender')) { implication = 'will be removed in Ember 3.0.'; } else if (isEnabled('ember-glimmer-detect-backtracking-rerender')) { implication = 'is no longer supported. See https://github.com/emberjs/ember.js/issues/13948 for more details.'; } if (isEnabled('ember-glimmer-detect-backtracking-rerender') || isEnabled('ember-glimmer-allow-backtracking-rerender')) { let counter = 0; let inTransaction = false; let shouldReflush; runInTransaction = function(context, methodName) { shouldReflush = false; inTransaction = true; context[methodName](); inTransaction = false; counter++; return shouldReflush; }; didRender = function(object, key, reference) { if (!inTransaction) { return; } let meta = metaFor(object); let lastRendered = meta.writableLastRendered(); lastRendered[key] = counter; runInDebug(() => { let lastRenderedFrom = meta.writableLastRenderedFrom(); lastRenderedFrom[key] = reference; }); }; assertNotRendered = function(object, key, _meta) { let meta = _meta || metaFor(object); let lastRendered = meta.readableLastRendered(); if (lastRendered && lastRendered[key] === counter) { raise( (function() { let ref = meta.readableLastRenderedFrom(); let parts = []; let lastRef = ref[key]; let label; if (lastRef) { while (lastRef && lastRef._propertyKey) { parts.unshift(lastRef._propertyKey); lastRef = lastRef._parentReference; } label = parts.join(); } else { label = 'the same value'; } return `You modified ${parts.join('.')} twice on ${object} in a single render. This was unreliable and slow in Ember 1.x and ${implication}`; }()), false); shouldReflush = true; } }; } else { runInTransaction = function() { throw new Error('Cannot call runInTransaction without Glimmer'); }; didRender = function() { throw new Error('Cannot call didRender without Glimmer'); }; assertNotRendered = function() { throw new Error('Cannot call assertNotRendered without Glimmer'); }; } export { runInTransaction as default, didRender, assertNotRendered };
import config from '@boldr/config'; const welcomeEmail = verificationToken => ` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <body> <div style='margin: 0; padding: 0; width: 100%; font-family: Trebuchet MS, sans-serif;'> <div style='background-color: #f2f2f2; padding: 45px;'> <div style='background-color: #ffffff; padding: 40px; text-align: center;'> <p style='color: #5f5f5f;'>Click the big button below to activate your account.</p> <a href="${config.get('siteUrl')}/account/verify/${verificationToken}" style='background-color: #288feb; color: #fff; padding: 14px; text-decoration: none; border-radius: 5px; margin-top: 20px; display: inline-block;'>Activate Account</a> </div> <h3 style='color: #5f5f5f; text-align: center; margin-top: 30px;'>BoldrCMS Team</h3></div></div> </body> </html> `; const forgotPasswordEmail = verificationToken => ` <div style='margin: 0; padding: 0; width: 100%; font-family: Trebuchet MS, sans-serif;'> <div style='background-color: #f2f2f2; padding: 45px;'> <div style='background-color: #ffffff; padding: 40px; text-align: center;'> <p style='color: #5f5f5f;'>Click the big button below to finish resetting your password.</p> <a href="${config.get('siteUrl')}/account/reset-password/${verificationToken}" style='background-color: #288feb; color: #fff; padding: 14px; text-decoration: none; border-radius: 5px; margin-top: 20px; display: inline-block;'>Reset password</a> </div> <h3 style='color: #5f5f5f; text-align: center; margin-top: 30px;'>BoldrCMS Team</h3></div></div> `; const passwordModifiedEmail = () => ` <div style='margin: 0; padding: 0; width: 100%; font-family: Trebuchet MS, sans-serif;'> <div style='background-color: #f2f2f2; padding: 45px;'> <div style='background-color: #ffffff; padding: 40px; text-align: center;'> <p style='color: #5f5f5f;'>Click the big button below to activate your account.</p> style='background-color: #288feb; color: #fff; padding: 14px; text-decoration: none; border-radius: 5px; margin-top: 20px; display: inline-block;'>Activate Account</a> </div> <h3 style='color: #5f5f5f; text-align: center; margin-top: 30px;'>BoldrCMS Team</h3></div></div> `; export { welcomeEmail, forgotPasswordEmail, passwordModifiedEmail };
'use strict'; describe("ngAnimate $animateCss", function() { beforeEach(module('ngAnimate')); beforeEach(module('ngAnimateMock')); function assertAnimationRunning(element, not) { var className = element.attr('class'); var regex = /\b\w+-active\b/; not ? expect(className).toMatch(regex) : expect(className).not.toMatch(regex); } function getPossiblyPrefixedStyleValue(element, styleProp) { var value = element.css(prefix + styleProp); if (isUndefined(value)) value = element.css(styleProp); return value; } function keyframeProgress(element, duration, delay) { browserTrigger(element, 'animationend', { timeStamp: Date.now() + ((delay || 1) * 1000), elapsedTime: duration }); } function transitionProgress(element, duration, delay) { browserTrigger(element, 'transitionend', { timeStamp: Date.now() + ((delay || 1) * 1000), elapsedTime: duration }); } var fakeStyle = { color: 'blue' }; var ss, prefix, triggerAnimationStartFrame; beforeEach(module(function() { return function($document, $sniffer, $$rAF, $animate) { prefix = '-' + $sniffer.vendorPrefix.toLowerCase() + '-'; ss = createMockStyleSheet($document, prefix); $animate.enabled(true); triggerAnimationStartFrame = function() { $$rAF.flush(); }; }; })); afterEach(function() { if (ss) { ss.destroy(); } }); it("should return false if neither transitions or keyframes are supported by the browser", inject(function($animateCss, $sniffer, $rootElement, $document) { var animator; var element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); $sniffer.transitions = $sniffer.animations = false; animator = $animateCss(element, { duration: 10, to: { 'background': 'red' } }); expect(animator.$$willAnimate).toBeFalsy(); })); describe('when active', function() { if (!browserSupportsCssAnimations()) return; it("should not attempt an animation if animations are globally disabled", inject(function($animateCss, $animate, $rootElement, $document) { $animate.enabled(false); var animator, element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); animator = $animateCss(element, { duration: 10, to: { 'height': '100px' } }); expect(animator.$$willAnimate).toBeFalsy(); })); it("should silently quit the animation and not throw when an element has no parent during preparation", inject(function($animateCss, $rootScope, $document, $rootElement) { var element = angular.element('<div></div>'); expect(function() { $animateCss(element, { duration: 1000, event: 'fake', to: fakeStyle }).start(); }).not.toThrow(); expect(element).not.toHaveClass('fake'); triggerAnimationStartFrame(); expect(element).not.toHaveClass('fake-active'); })); it("should silently quit the animation and not throw when an element has no parent before starting", inject(function($animateCss, $$rAF, $rootScope, $document, $rootElement) { var element = angular.element('<div></div>'); angular.element($document[0].body).append($rootElement); $rootElement.append(element); $animateCss(element, { duration: 1000, addClass: 'wait-for-it', to: fakeStyle }).start(); element.remove(); expect(function() { triggerAnimationStartFrame(); }).not.toThrow(); })); describe("rAF usage", function() { it("should buffer all requests into a single requestAnimationFrame call", inject(function($animateCss, $$rAF, $rootScope, $document, $rootElement) { angular.element($document[0].body).append($rootElement); var count = 0; var runners = []; function makeRequest() { var element = angular.element('<div></div>'); $rootElement.append(element); var runner = $animateCss(element, { duration: 5, to: fakeStyle }).start(); runner.then(function() { count++; }); runners.push(runner); } makeRequest(); makeRequest(); makeRequest(); expect(count).toBe(0); triggerAnimationStartFrame(); forEach(runners, function(runner) { runner.end(); }); $rootScope.$digest(); expect(count).toBe(3); })); it("should cancel previous requests to rAF to avoid premature flushing", function() { var count = 0; module(function($provide) { $provide.value('$$rAF', function() { return function cancellationFn() { count++; }; }); }); inject(function($animateCss, $$rAF, $document, $rootElement) { angular.element($document[0].body).append($rootElement); function makeRequest() { var element = angular.element('<div></div>'); $rootElement.append(element); $animateCss(element, { duration: 5, to: fakeStyle }).start(); } makeRequest(); makeRequest(); makeRequest(); expect(count).toBe(2); }); }); }); describe("animator and runner", function() { var animationDuration = 5; var element, animator; beforeEach(inject(function($animateCss, $rootElement, $document) { element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); animator = $animateCss(element, { event: 'enter', structural: true, duration: animationDuration, to: fakeStyle }); })); it('should expose start and end functions for the animator object', inject(function() { expect(typeof animator.start).toBe('function'); expect(typeof animator.end).toBe('function'); })); it('should expose end, cancel, resume and pause methods on the runner object', inject(function() { var runner = animator.start(); triggerAnimationStartFrame(); expect(typeof runner.end).toBe('function'); expect(typeof runner.cancel).toBe('function'); expect(typeof runner.resume).toBe('function'); expect(typeof runner.pause).toBe('function'); })); it('should start the animation', inject(function() { expect(element).not.toHaveClass('ng-enter-active'); animator.start(); triggerAnimationStartFrame(); expect(element).toHaveClass('ng-enter-active'); })); it('should end the animation when called from the animator object', inject(function() { animator.start(); triggerAnimationStartFrame(); animator.end(); expect(element).not.toHaveClass('ng-enter-active'); })); it('should end the animation when called from the runner object', inject(function() { var runner = animator.start(); triggerAnimationStartFrame(); runner.end(); expect(element).not.toHaveClass('ng-enter-active'); })); it('should permanently close the animation if closed before the next rAF runs', inject(function() { var runner = animator.start(); runner.end(); triggerAnimationStartFrame(); expect(element).not.toHaveClass('ng-enter-active'); })); it('should return a runner object at the start of the animation that contains a `then` method', inject(function($rootScope) { var runner = animator.start(); triggerAnimationStartFrame(); expect(isPromiseLike(runner)).toBeTruthy(); var resolved; runner.then(function() { resolved = true; }); runner.end(); $rootScope.$digest(); expect(resolved).toBeTruthy(); })); it('should cancel the animation and reject', inject(function($rootScope) { var rejected; var runner = animator.start(); triggerAnimationStartFrame(); runner.then(noop, function() { rejected = true; }); runner.cancel(); $rootScope.$digest(); expect(rejected).toBeTruthy(); })); it('should run pause, but not effect the transition animation', inject(function() { var blockingDelay = '-' + animationDuration + 's'; expect(element.css('transition-delay')).toEqual(blockingDelay); var runner = animator.start(); triggerAnimationStartFrame(); expect(element.css('transition-delay')).not.toEqual(blockingDelay); runner.pause(); expect(element.css('transition-delay')).not.toEqual(blockingDelay); })); it('should pause the transition, have no effect, but not end it', inject(function() { var runner = animator.start(); triggerAnimationStartFrame(); runner.pause(); browserTrigger(element, 'transitionend', { timeStamp: Date.now(), elapsedTime: 5 }); expect(element).toHaveClass('ng-enter-active'); })); it('should resume the animation', inject(function() { var runner = animator.start(); triggerAnimationStartFrame(); runner.pause(); browserTrigger(element, 'transitionend', { timeStamp: Date.now(), elapsedTime: 5 }); expect(element).toHaveClass('ng-enter-active'); runner.resume(); expect(element).not.toHaveClass('ng-enter-active'); })); it('should pause and resume a keyframe animation using animation-play-state', inject(function($animateCss) { element.attr('style', ''); ss.addRule('.ng-enter', '-webkit-animation:1.5s keyframe_animation;' + 'animation:1.5s keyframe_animation;'); animator = $animateCss(element, { event: 'enter', structural: true }); var runner = animator.start(); triggerAnimationStartFrame(); runner.pause(); expect(getPossiblyPrefixedStyleValue(element, 'animation-play-state')).toEqual('paused'); runner.resume(); expect(element.attr('style')).toBeFalsy(); })); it('should remove the animation-play-state style if the animation is closed', inject(function($animateCss) { element.attr('style', ''); ss.addRule('.ng-enter', '-webkit-animation:1.5s keyframe_animation;' + 'animation:1.5s keyframe_animation;'); animator = $animateCss(element, { event: 'enter', structural: true }); var runner = animator.start(); triggerAnimationStartFrame(); runner.pause(); expect(getPossiblyPrefixedStyleValue(element, 'animation-play-state')).toEqual('paused'); runner.end(); expect(element.attr('style')).toBeFalsy(); })); }); describe("CSS", function() { describe("detected styles", function() { var element, options; function assertAnimationComplete(bool) { var assert = expect(element); if (bool) { assert = assert.not; } assert.toHaveClass('ng-enter'); assert.toHaveClass('ng-enter-active'); } beforeEach(inject(function($rootElement, $document) { element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); options = { event: 'enter', structural: true }; })); it("should always return an object even if no animation is detected", inject(function($animateCss) { ss.addRule('.some-animation', 'background:red;'); element.addClass('some-animation'); var animator = $animateCss(element, options); expect(animator).toBeTruthy(); expect(isFunction(animator.start)).toBeTruthy(); expect(animator.end).toBeTruthy(); expect(animator.$$willAnimate).toBe(false); })); it("should close the animation immediately, but still return an animator object if no animation is detected", inject(function($animateCss) { ss.addRule('.another-fake-animation', 'background:blue;'); element.addClass('another-fake-animation'); var animator = $animateCss(element, { event: 'enter', structural: true }); expect(element).not.toHaveClass('ng-enter'); expect(isFunction(animator.start)).toBeTruthy(); })); they("should close the animation, but still accept $prop callbacks if no animation is detected", ['done', 'then'], function(method) { inject(function($animateCss, $animate, $rootScope) { ss.addRule('.the-third-fake-animation', 'background:green;'); element.addClass('another-fake-animation'); var animator = $animateCss(element, { event: 'enter', structural: true }); var done = false; animator.start()[method](function() { done = true; }); expect(done).toBe(false); $animate.flush(); if (method === 'then') { $rootScope.$digest(); } expect(done).toBe(true); }); }); they("should close the animation, but still accept recognize runner.$prop if no animation is detected", ['done(cancel)', 'catch'], function(method) { inject(function($animateCss, $rootScope) { ss.addRule('.the-third-fake-animation', 'background:green;'); element.addClass('another-fake-animation'); var animator = $animateCss(element, { event: 'enter', structural: true }); var cancelled = false; var runner = animator.start(); if (method === 'catch') { runner.catch(function() { cancelled = true; }); } else { runner.done(function(status) { cancelled = status === false; }); } expect(cancelled).toBe(false); runner.cancel(); if (method === 'catch') { $rootScope.$digest(); } expect(cancelled).toBe(true); }); }); it("should use the highest transition duration value detected in the CSS class", inject(function($animateCss) { ss.addRule('.ng-enter', 'transition:1s linear all;' + 'transition-duration:10s, 15s, 20s;'); var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); transitionProgress(element, 10); assertAnimationComplete(false); transitionProgress(element, 15); assertAnimationComplete(false); transitionProgress(element, 20); assertAnimationComplete(true); })); it("should use the highest transition delay value detected in the CSS class", inject(function($animateCss) { ss.addRule('.ng-enter', 'transition:1s linear all;' + 'transition-delay:10s, 15s, 20s;'); var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); transitionProgress(element, 1, 10); assertAnimationComplete(false); transitionProgress(element, 1, 15); assertAnimationComplete(false); transitionProgress(element, 1, 20); assertAnimationComplete(true); })); it("should only close when both the animation delay and duration have passed", inject(function($animateCss) { ss.addRule('.ng-enter', 'transition:10s 5s linear all;'); var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); transitionProgress(element, 10, 2); assertAnimationComplete(false); transitionProgress(element, 9, 6); assertAnimationComplete(false); transitionProgress(element, 10, 5); assertAnimationComplete(true); })); it("should use the highest keyframe duration value detected in the CSS class", inject(function($animateCss) { ss.addRule('.ng-enter', 'animation:animation 1s, animation 2s, animation 3s;' + '-webkit-animation:animation 1s, animation 2s, animation 3s;'); var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); keyframeProgress(element, 1); assertAnimationComplete(false); keyframeProgress(element, 2); assertAnimationComplete(false); keyframeProgress(element, 3); assertAnimationComplete(true); })); it("should use the highest keyframe delay value detected in the CSS class", inject(function($animateCss) { ss.addRule('.ng-enter', 'animation:animation 1s 2s, animation 1s 10s, animation 1s 1000ms;' + '-webkit-animation:animation 1s 2s, animation 1s 10s, animation 1s 1000ms;'); var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); keyframeProgress(element, 1, 1); assertAnimationComplete(false); keyframeProgress(element, 1, 2); assertAnimationComplete(false); keyframeProgress(element, 1, 10); assertAnimationComplete(true); })); it("should use the highest keyframe duration value detected in the CSS class with respect to the animation-iteration-count property", inject(function($animateCss) { ss.addRule('.ng-enter', 'animation:animation 1s 2s 3, animation 1s 10s 2, animation 1s 1000ms infinite;' + '-webkit-animation:animation 1s 2s 3, animation 1s 10s 2, animation 1s 1000ms infinite;'); var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); keyframeProgress(element, 1, 1); assertAnimationComplete(false); keyframeProgress(element, 1, 2); assertAnimationComplete(false); keyframeProgress(element, 3, 10); assertAnimationComplete(true); })); it("should use the highest duration value when both transitions and keyframes are used", inject(function($animateCss) { ss.addRule('.ng-enter', 'transition:1s linear all;' + 'transition-duration:10s, 15s, 20s;' + 'animation:animation 1s, animation 2s, animation 3s 0s 7;' + '-webkit-animation:animation 1s, animation 2s, animation 3s 0s 7;'); var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); transitionProgress(element, 10); keyframeProgress(element, 10); assertAnimationComplete(false); transitionProgress(element, 15); keyframeProgress(element, 15); assertAnimationComplete(false); transitionProgress(element, 20); keyframeProgress(element, 20); assertAnimationComplete(false); // 7 * 3 = 21 transitionProgress(element, 21); keyframeProgress(element, 21); assertAnimationComplete(true); })); it("should use the highest delay value when both transitions and keyframes are used", inject(function($animateCss) { ss.addRule('.ng-enter', 'transition:1s linear all;' + 'transition-delay:10s, 15s, 20s;' + 'animation:animation 1s 2s, animation 1s 16s, animation 1s 19s;' + '-webkit-animation:animation 1s 2s, animation 1s 16s, animation 1s 19s;'); var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); transitionProgress(element, 1, 10); keyframeProgress(element, 1, 10); assertAnimationComplete(false); transitionProgress(element, 1, 16); keyframeProgress(element, 1, 16); assertAnimationComplete(false); transitionProgress(element, 1, 19); keyframeProgress(element, 1, 19); assertAnimationComplete(false); transitionProgress(element, 1, 20); keyframeProgress(element, 1, 20); assertAnimationComplete(true); })); }); describe("staggering", function() { it("should apply a stagger based when an active ng-EVENT-stagger class with a transition-delay is detected", inject(function($animateCss, $document, $rootElement, $timeout) { angular.element($document[0].body).append($rootElement); ss.addRule('.ng-enter-stagger', 'transition-delay:0.2s'); ss.addRule('.ng-enter', 'transition:2s linear all'); var elements = []; var i; var elm; for (i = 0; i < 5; i++) { elm = angular.element('<div></div>'); elements.push(elm); $rootElement.append(elm); $animateCss(elm, { event: 'enter', structural: true }).start(); expect(elm).not.toHaveClass('ng-enter-stagger'); expect(elm).toHaveClass('ng-enter'); } triggerAnimationStartFrame(); expect(elements[0]).toHaveClass('ng-enter-active'); for (i = 1; i < 5; i++) { elm = elements[i]; expect(elm).not.toHaveClass('ng-enter-active'); $timeout.flush(200); expect(elm).toHaveClass('ng-enter-active'); browserTrigger(elm, 'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 2 }); expect(elm).not.toHaveClass('ng-enter'); expect(elm).not.toHaveClass('ng-enter-active'); expect(elm).not.toHaveClass('ng-enter-stagger'); } })); it("should apply a stagger based when for all provided addClass/removeClass CSS classes", inject(function($animateCss, $document, $rootElement, $timeout) { angular.element($document[0].body).append($rootElement); ss.addRule('.red-add-stagger,' + '.blue-remove-stagger,' + '.green-add-stagger', 'transition-delay:0.2s'); ss.addRule('.red-add,' + '.blue-remove,' + '.green-add', 'transition:2s linear all'); var elements = []; var i; var elm; for (i = 0; i < 5; i++) { elm = angular.element('<div class="blue"></div>'); elements.push(elm); $rootElement.append(elm); $animateCss(elm, { addClass: 'red green', removeClass: 'blue' }).start(); } triggerAnimationStartFrame(); for (i = 0; i < 5; i++) { elm = elements[i]; expect(elm).not.toHaveClass('red-add-stagger'); expect(elm).not.toHaveClass('green-add-stagger'); expect(elm).not.toHaveClass('blue-remove-stagger'); expect(elm).toHaveClass('red-add'); expect(elm).toHaveClass('green-add'); expect(elm).toHaveClass('blue-remove'); } expect(elements[0]).toHaveClass('red-add-active'); expect(elements[0]).toHaveClass('green-add-active'); expect(elements[0]).toHaveClass('blue-remove-active'); for (i = 1; i < 5; i++) { elm = elements[i]; expect(elm).not.toHaveClass('red-add-active'); expect(elm).not.toHaveClass('green-add-active'); expect(elm).not.toHaveClass('blue-remove-active'); $timeout.flush(200); expect(elm).toHaveClass('red-add-active'); expect(elm).toHaveClass('green-add-active'); expect(elm).toHaveClass('blue-remove-active'); browserTrigger(elm, 'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 2 }); expect(elm).not.toHaveClass('red-add-active'); expect(elm).not.toHaveClass('green-add-active'); expect(elm).not.toHaveClass('blue-remove-active'); expect(elm).not.toHaveClass('red-add-stagger'); expect(elm).not.toHaveClass('green-add-stagger'); expect(elm).not.toHaveClass('blue-remove-stagger'); } })); it("should block the transition animation between start and animate when staggered", inject(function($animateCss, $document, $rootElement) { angular.element($document[0].body).append($rootElement); ss.addRule('.ng-enter-stagger', 'transition-delay:0.2s'); ss.addRule('.ng-enter', 'transition:2s linear all;'); var element; var i; var elms = []; for (i = 0; i < 5; i++) { element = angular.element('<div class="transition-animation"></div>'); $rootElement.append(element); $animateCss(element, { event: 'enter', structural: true }).start(); elms.push(element); } triggerAnimationStartFrame(); for (i = 0; i < 5; i++) { element = elms[i]; if (i === 0) { expect(element.attr('style')).toBeFalsy(); } else { expect(element.css('transition-delay')).toContain('-2s'); } } })); it("should block (pause) the keyframe animation between start and animate when staggered", inject(function($animateCss, $document, $rootElement) { angular.element($document[0].body).append($rootElement); ss.addPossiblyPrefixedRule('.ng-enter-stagger', 'animation-delay:0.2s'); ss.addPossiblyPrefixedRule('.ng-enter', 'animation:my_animation 2s;'); var i, element, elements = []; for (i = 0; i < 5; i++) { element = angular.element('<div class="transition-animation"></div>'); $rootElement.append(element); $animateCss(element, { event: 'enter', structural: true }).start(); elements.push(element); } triggerAnimationStartFrame(); for (i = 0; i < 5; i++) { element = elements[i]; if (i === 0) { // the first element is always run right away expect(element.attr('style')).toBeFalsy(); } else { expect(getPossiblyPrefixedStyleValue(element, 'animation-play-state')).toBe('paused'); } } })); it("should not apply a stagger if the transition delay value is inherited from a earlier CSS class", inject(function($animateCss, $document, $rootElement) { angular.element($document[0].body).append($rootElement); ss.addRule('.transition-animation', 'transition:2s 5s linear all;'); for (var i = 0; i < 5; i++) { var element = angular.element('<div class="transition-animation"></div>'); $rootElement.append(element); $animateCss(element, { event: 'enter', structural: true }).start(); triggerAnimationStartFrame(); expect(element).toHaveClass('ng-enter-active'); } })); it("should apply a stagger only if the transition duration value is zero when inherited from a earlier CSS class", inject(function($animateCss, $document, $rootElement) { angular.element($document[0].body).append($rootElement); ss.addRule('.transition-animation', 'transition:2s 5s linear all;'); ss.addRule('.transition-animation.ng-enter-stagger', 'transition-duration:0s; transition-delay:0.2s;'); var element, i, elms = []; for (i = 0; i < 5; i++) { element = angular.element('<div class="transition-animation"></div>'); $rootElement.append(element); elms.push(element); $animateCss(element, { event: 'enter', structural: true }).start(); } triggerAnimationStartFrame(); for (i = 1; i < 5; i++) { element = elms[i]; expect(element).not.toHaveClass('ng-enter-active'); } })); it("should ignore animation staggers if only transition animations were detected", inject(function($animateCss, $document, $rootElement) { angular.element($document[0].body).append($rootElement); ss.addRule('.ng-enter-stagger', prefix + 'animation-delay:0.2s'); ss.addRule('.transition-animation', 'transition:2s 5s linear all;'); for (var i = 0; i < 5; i++) { var element = angular.element('<div class="transition-animation"></div>'); $rootElement.append(element); $animateCss(element, { event: 'enter', structural: true }).start(); triggerAnimationStartFrame(); expect(element).toHaveClass('ng-enter-active'); } })); it("should ignore transition staggers if only keyframe animations were detected", inject(function($animateCss, $document, $rootElement) { angular.element($document[0].body).append($rootElement); ss.addRule('.ng-enter-stagger', 'transition-delay:0.2s'); ss.addPossiblyPrefixedRule('.transition-animation', 'animation: 2s 5s my_animation;'); for (var i = 0; i < 5; i++) { var elm = angular.element('<div class="transition-animation"></div>'); $rootElement.append(elm); var animator = $animateCss(elm, { event: 'enter', structural: true }).start(); triggerAnimationStartFrame(); expect(elm).toHaveClass('ng-enter-active'); } })); it("should start on the highest stagger value if both transition and keyframe staggers are used together", inject(function($animateCss, $document, $rootElement, $timeout, $browser) { angular.element($document[0].body).append($rootElement); ss.addPossiblyPrefixedRule('.ng-enter-stagger', 'transition-delay: 0.5s; ' + 'animation-delay: 1s'); ss.addPossiblyPrefixedRule('.ng-enter', 'transition: 10s linear all; ' + 'animation: 20s my_animation'); var i, elm, elements = []; for (i = 0; i < 5; i++) { elm = angular.element('<div></div>'); elements.push(elm); $rootElement.append(elm); $animateCss(elm, { event: 'enter', structural: true }).start(); expect(elm).toHaveClass('ng-enter'); } triggerAnimationStartFrame(); expect(elements[0]).toHaveClass('ng-enter-active'); for (i = 1; i < 5; i++) { elm = elements[i]; expect(elm).not.toHaveClass('ng-enter-active'); $timeout.flush(500); expect(elm).not.toHaveClass('ng-enter-active'); $timeout.flush(500); expect(elm).toHaveClass('ng-enter-active'); } })); it("should apply the closing timeout ontop of the stagger timeout", inject(function($animateCss, $document, $rootElement, $timeout, $browser) { angular.element($document[0].body).append($rootElement); ss.addRule('.ng-enter-stagger', 'transition-delay:1s;'); ss.addRule('.ng-enter', 'transition:10s linear all;'); var elm, i, elms = []; for (i = 0; i < 5; i++) { elm = angular.element('<div></div>'); elms.push(elm); $rootElement.append(elm); $animateCss(elm, { event: 'enter', structural: true }).start(); triggerAnimationStartFrame(); } for (i = 1; i < 2; i++) { elm = elms[i]; expect(elm).toHaveClass('ng-enter'); $timeout.flush(1000); $timeout.flush(15000); expect(elm).not.toHaveClass('ng-enter'); } })); it("should apply the closing timeout ontop of the stagger timeout with an added delay", inject(function($animateCss, $document, $rootElement, $timeout, $browser) { angular.element($document[0].body).append($rootElement); ss.addRule('.ng-enter-stagger', 'transition-delay:1s;'); ss.addRule('.ng-enter', 'transition:10s linear all; transition-delay:50s;'); var elm, i, elms = []; for (i = 0; i < 5; i++) { elm = angular.element('<div></div>'); elms.push(elm); $rootElement.append(elm); $animateCss(elm, { event: 'enter', structural: true }).start(); triggerAnimationStartFrame(); } for (i = 1; i < 2; i++) { elm = elms[i]; expect(elm).toHaveClass('ng-enter'); $timeout.flush(1000); $timeout.flush(65000); expect(elm).not.toHaveClass('ng-enter'); } })); it("should issue a stagger if a stagger value is provided in the options", inject(function($animateCss, $document, $rootElement, $timeout) { angular.element($document[0].body).append($rootElement); ss.addRule('.ng-enter', 'transition:2s linear all'); var elm, i, elements = []; for (i = 0; i < 5; i++) { elm = angular.element('<div></div>'); elements.push(elm); $rootElement.append(elm); $animateCss(elm, { event: 'enter', structural: true, stagger: 0.5 }).start(); expect(elm).toHaveClass('ng-enter'); } triggerAnimationStartFrame(); expect(elements[0]).toHaveClass('ng-enter-active'); for (i = 1; i < 5; i++) { elm = elements[i]; expect(elm).not.toHaveClass('ng-enter-active'); $timeout.flush(500); expect(elm).toHaveClass('ng-enter-active'); browserTrigger(elm, 'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 2 }); expect(elm).not.toHaveClass('ng-enter'); expect(elm).not.toHaveClass('ng-enter-active'); expect(elm).not.toHaveClass('ng-enter-stagger'); } })); it("should only add/remove classes once the stagger timeout has passed", inject(function($animateCss, $document, $rootElement, $timeout) { angular.element($document[0].body).append($rootElement); var element = angular.element('<div class="green"></div>'); $rootElement.append(element); $animateCss(element, { addClass: 'red', removeClass: 'green', duration: 5, stagger: 0.5, staggerIndex: 3 }).start(); triggerAnimationStartFrame(); expect(element).toHaveClass('green'); expect(element).not.toHaveClass('red'); $timeout.flush(1500); expect(element).not.toHaveClass('green'); expect(element).toHaveClass('red'); })); }); describe("closing timeout", function() { it("should close off the animation after 150% of the animation time has passed", inject(function($animateCss, $document, $rootElement, $timeout) { ss.addRule('.ng-enter', 'transition:10s linear all;'); var element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); var animator = $animateCss(element, { event: 'enter', structural: true }); animator.start(); triggerAnimationStartFrame(); expect(element).toHaveClass('ng-enter'); expect(element).toHaveClass('ng-enter-active'); $timeout.flush(15000); expect(element).not.toHaveClass('ng-enter'); expect(element).not.toHaveClass('ng-enter-active'); })); it("should close off the animation after 150% of the animation time has passed and consider the detected delay value", inject(function($animateCss, $document, $rootElement, $timeout) { ss.addRule('.ng-enter', 'transition:10s linear all; transition-delay:30s;'); var element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); var animator = $animateCss(element, { event: 'enter', structural: true }); animator.start(); triggerAnimationStartFrame(); expect(element).toHaveClass('ng-enter'); expect(element).toHaveClass('ng-enter-active'); $timeout.flush(45000); expect(element).not.toHaveClass('ng-enter'); expect(element).not.toHaveClass('ng-enter-active'); })); it("should still resolve the animation once expired", inject(function($animateCss, $document, $rootElement, $timeout, $animate, $rootScope) { ss.addRule('.ng-enter', 'transition:10s linear all;'); var element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); var animator = $animateCss(element, { event: 'enter', structural: true }); var failed, passed; animator.start().then(function() { passed = true; }, function() { failed = true; }); triggerAnimationStartFrame(); $timeout.flush(15000); $animate.flush(); $rootScope.$digest(); expect(passed).toBe(true); })); it("should not resolve/reject after passing if the animation completed successfully", inject(function($animateCss, $document, $rootElement, $timeout, $rootScope, $animate) { ss.addRule('.ng-enter', 'transition:10s linear all;'); var element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); var animator = $animateCss(element, { event: 'enter', structural: true }); var failed, passed; animator.start().then( function() { passed = true; }, function() { failed = true; } ); triggerAnimationStartFrame(); browserTrigger(element, 'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 10 }); $animate.flush(); $rootScope.$digest(); expect(passed).toBe(true); expect(failed).not.toBe(true); $timeout.flush(15000); expect(passed).toBe(true); expect(failed).not.toBe(true); })); it("should close all stacked animations after the last timeout runs on the same element", inject(function($animateCss, $document, $rootElement, $timeout, $animate) { var now = 0; spyOn(Date, 'now').and.callFake(function() { return now; }); var cancelSpy = spyOn($timeout, 'cancel').and.callThrough(); var doneSpy = jasmine.createSpy(); ss.addRule('.elm', 'transition:1s linear all;'); ss.addRule('.elm.red', 'background:red;'); ss.addRule('.elm.blue', 'transition:2s linear all; background:blue;'); ss.addRule('.elm.green', 'background:green;'); var element = angular.element('<div class="elm"></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); // timeout will be at 1500s animate(element, 'red', doneSpy); expect(doneSpy).not.toHaveBeenCalled(); fastForwardClock(500); //1000s left to go // timeout will not be at 500 + 3000s = 3500s animate(element, 'blue', doneSpy); expect(doneSpy).not.toHaveBeenCalled(); expect(cancelSpy).toHaveBeenCalled(); cancelSpy.calls.reset(); // timeout will not be set again since the former animation is longer animate(element, 'green', doneSpy); expect(doneSpy).not.toHaveBeenCalled(); expect(cancelSpy).not.toHaveBeenCalled(); // this will close the animations fully fastForwardClock(3500); $animate.flush(); expect(doneSpy).toHaveBeenCalled(); expect(doneSpy).toHaveBeenCalledTimes(3); function fastForwardClock(time) { now += time; $timeout.flush(time); } function animate(element, klass, onDone) { var animator = $animateCss(element, { addClass: klass }).start(); animator.done(onDone); triggerAnimationStartFrame(); return animator; } })); it("should not throw an error any pending timeout requests resolve after the element has already been removed", inject(function($animateCss, $document, $rootElement, $timeout, $animate) { var element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); ss.addRule('.red', 'transition:1s linear all;'); $animateCss(element, { addClass: 'red' }).start(); triggerAnimationStartFrame(); element.remove(); expect(function() { $timeout.flush(); }).not.toThrow(); })); it("should consider a positive options.delay value for the closing timeout", inject(function($animateCss, $rootElement, $timeout, $document) { var element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); var options = { delay: 3, duration: 3, to: { height: '100px' } }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); // At this point, the animation should still be running (closing timeout is 7500ms ... duration * 1.5 + delay => 7.5) $timeout.flush(7000); expect(getPossiblyPrefixedStyleValue(element, 'transition-delay')).toBe('3s'); expect(getPossiblyPrefixedStyleValue(element, 'transition-duration')).toBe('3s'); // Let's flush the remaining amount of time for the timeout timer to kick in $timeout.flush(500); expect(getPossiblyPrefixedStyleValue(element, 'transition-duration')).toBeOneOf('', '0s'); expect(getPossiblyPrefixedStyleValue(element, 'transition-delay')).toBeOneOf('', '0s'); })); it("should ignore a boolean options.delay value for the closing timeout", inject(function($animateCss, $rootElement, $timeout, $document) { var element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); var options = { delay: true, duration: 3, to: { height: '100px' } }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); // At this point, the animation should still be running (closing timeout is 4500ms ... duration * 1.5 => 4.5) $timeout.flush(4000); expect(getPossiblyPrefixedStyleValue(element, 'transition-delay')).toBeOneOf('initial', '0s'); expect(getPossiblyPrefixedStyleValue(element, 'transition-duration')).toBe('3s'); // Let's flush the remaining amount of time for the timeout timer to kick in $timeout.flush(500); expect(getPossiblyPrefixedStyleValue(element, 'transition-duration')).toBeOneOf('', '0s'); expect(getPossiblyPrefixedStyleValue(element, 'transition-delay')).toBeOneOf('', '0s'); })); it("should cancel the timeout when the animation is ended normally", inject(function($animateCss, $document, $rootElement, $timeout) { ss.addRule('.ng-enter', 'transition:10s linear all;'); var element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); var animator = $animateCss(element, { event: 'enter', structural: true }); animator.start(); triggerAnimationStartFrame(); expect(element).toHaveClass('ng-enter'); expect(element).toHaveClass('ng-enter-active'); animator.end(); expect(element.data(ANIMATE_TIMER_KEY)).toBeUndefined(); $timeout.flush(); expect(function() {$timeout.verifyNoPendingTasks();}).not.toThrow(); })); }); describe("getComputedStyle", function() { var count; var acceptableTimingsData = { transitionDuration: "10s" }; beforeEach(module(function($provide) { count = {}; $provide.value('$window', extend({}, window, { document: angular.element(window.document), getComputedStyle: function(node) { var key = node.className.indexOf('stagger') >= 0 ? 'stagger' : 'normal'; count[key] = count[key] || 0; count[key]++; return acceptableTimingsData; } })); return function($document, $rootElement) { angular.element($document[0].body).append($rootElement); }; })); it("should cache frequent calls to getComputedStyle before the next animation frame kicks in", inject(function($animateCss, $document, $rootElement) { var i, elm, animator; for (i = 0; i < 5; i++) { elm = angular.element('<div></div>'); $rootElement.append(elm); animator = $animateCss(elm, { event: 'enter', structural: true }); var runner = animator.start(); } expect(count.normal).toBe(1); for (i = 0; i < 5; i++) { elm = angular.element('<div></div>'); $rootElement.append(elm); animator = $animateCss(elm, { event: 'enter', structural: true }); animator.start(); } expect(count.normal).toBe(1); triggerAnimationStartFrame(); expect(count.normal).toBe(2); for (i = 0; i < 5; i++) { elm = angular.element('<div></div>'); $rootElement.append(elm); animator = $animateCss(elm, { event: 'enter', structural: true }); animator.start(); } expect(count.normal).toBe(3); })); it("should cache frequent calls to getComputedStyle for stagger animations before the next animation frame kicks in", inject(function($animateCss, $document, $rootElement, $$rAF) { var element = angular.element('<div></div>'); $rootElement.append(element); var animator = $animateCss(element, { event: 'enter', structural: true }); animator.start(); triggerAnimationStartFrame(); expect(count.stagger).toBeUndefined(); var i, elm; for (i = 0; i < 5; i++) { elm = angular.element('<div></div>'); $rootElement.append(elm); animator = $animateCss(elm, { event: 'enter', structural: true }); animator.start(); } expect(count.stagger).toBe(1); for (i = 0; i < 5; i++) { elm = angular.element('<div></div>'); $rootElement.append(elm); animator = $animateCss(elm, { event: 'enter', structural: true }); animator.start(); } expect(count.stagger).toBe(1); $$rAF.flush(); for (i = 0; i < 5; i++) { elm = angular.element('<div></div>'); $rootElement.append(elm); animator = $animateCss(elm, { event: 'enter', structural: true }); animator.start(); } triggerAnimationStartFrame(); expect(count.stagger).toBe(2); })); }); describe('transitionend/animationend event listeners', function() { var element, elementOnSpy, elementOffSpy, progress; function setStyles(event) { switch (event) { case TRANSITIONEND_EVENT: ss.addRule('.ng-enter', 'transition: 10s linear all;'); progress = transitionProgress; break; case ANIMATIONEND_EVENT: ss.addRule('.ng-enter', '-webkit-animation: animation 10s;' + 'animation: animation 10s;'); progress = keyframeProgress; break; } } beforeEach(inject(function($rootElement, $document) { element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); elementOnSpy = spyOn(element, 'on').and.callThrough(); elementOffSpy = spyOn(element, 'off').and.callThrough(); })); they('should remove the $prop event listeners on cancel', [TRANSITIONEND_EVENT, ANIMATIONEND_EVENT], function(event) { inject(function($animateCss) { setStyles(event); var animator = $animateCss(element, { event: 'enter', structural: true }); var runner = animator.start(); triggerAnimationStartFrame(); expect(elementOnSpy).toHaveBeenCalledOnce(); expect(elementOnSpy.calls.mostRecent().args[0]).toBe(event); runner.cancel(); expect(elementOffSpy).toHaveBeenCalledOnce(); expect(elementOffSpy.calls.mostRecent().args[0]).toBe(event); }); }); they("should remove the $prop event listener when the animation is closed", [TRANSITIONEND_EVENT, ANIMATIONEND_EVENT], function(event) { inject(function($animateCss) { setStyles(event); var animator = $animateCss(element, { event: 'enter', structural: true }); var runner = animator.start(); triggerAnimationStartFrame(); expect(elementOnSpy).toHaveBeenCalledOnce(); expect(elementOnSpy.calls.mostRecent().args[0]).toBe(event); progress(element, 10); expect(elementOffSpy).toHaveBeenCalledOnce(); expect(elementOffSpy.calls.mostRecent().args[0]).toBe(event); }); }); they("should remove the $prop event listener when the closing timeout occurs", [TRANSITIONEND_EVENT, ANIMATIONEND_EVENT], function(event) { inject(function($animateCss, $timeout) { setStyles(event); var animator = $animateCss(element, { event: 'enter', structural: true }); animator.start(); triggerAnimationStartFrame(); expect(elementOnSpy).toHaveBeenCalledOnce(); expect(elementOnSpy.calls.mostRecent().args[0]).toBe(event); $timeout.flush(15000); expect(elementOffSpy).toHaveBeenCalledOnce(); expect(elementOffSpy.calls.mostRecent().args[0]).toBe(event); }); }); they("should not add or remove $prop event listeners when no animation styles are detected", [TRANSITIONEND_EVENT, ANIMATIONEND_EVENT], function(event) { inject(function($animateCss, $timeout) { progress = event === TRANSITIONEND_EVENT ? transitionProgress : keyframeProgress; // Make sure other event listeners are not affected var otherEndSpy = jasmine.createSpy('otherEndSpy'); element.on(event, otherEndSpy); expect(elementOnSpy).toHaveBeenCalledOnce(); elementOnSpy.calls.reset(); var animator = $animateCss(element, { event: 'enter', structural: true }); expect(animator.$$willAnimate).toBeFalsy(); // This will close the animation because no styles have been detected var runner = animator.start(); triggerAnimationStartFrame(); expect(elementOnSpy).not.toHaveBeenCalled(); expect(elementOffSpy).not.toHaveBeenCalled(); progress(element, 10); expect(otherEndSpy).toHaveBeenCalledOnce(); }); }); }); }); it('should avoid applying the same cache to an element a follow-up animation is run on the same element', inject(function($animateCss, $rootElement, $document) { function endTransition(element, elapsedTime) { browserTrigger(element, 'transitionend', { timeStamp: Date.now(), elapsedTime: elapsedTime }); } function startAnimation(element, duration, color) { $animateCss(element, { duration: duration, to: { background: color } }).start(); triggerAnimationStartFrame(); } var element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); startAnimation(element, 0.5, 'red'); expect(element.attr('style')).toContain('transition'); endTransition(element, 0.5); expect(element.attr('style')).not.toContain('transition'); startAnimation(element, 0.8, 'blue'); expect(element.attr('style')).toContain('transition'); // Trigger an extra transitionend event that matches the original transition endTransition(element, 0.5); expect(element.attr('style')).toContain('transition'); endTransition(element, 0.8); expect(element.attr('style')).not.toContain('transition'); })); it("should clear cache if no animation so follow-up animation on the same element will not be from cache", inject(function($animateCss, $rootElement, $document, $$rAF) { var element = angular.element('<div class="rclass"></div>'); var options = { event: 'enter', structural: true }; $rootElement.append(element); angular.element($document[0].body).append($rootElement); var animator = $animateCss(element, options); expect(animator.$$willAnimate).toBeFalsy(); $$rAF.flush(); ss.addRule('.ng-enter', '-webkit-animation:3.5s keyframe_animation;' + 'animation:3.5s keyframe_animation;'); animator = $animateCss(element, options); expect(animator.$$willAnimate).toBeTruthy(); })); it('should apply a custom temporary class when a non-structural animation is used', inject(function($animateCss, $rootElement, $document) { var element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); $animateCss(element, { event: 'super', duration: 1000, to: fakeStyle }).start(); expect(element).toHaveClass('super'); triggerAnimationStartFrame(); expect(element).toHaveClass('super-active'); })); describe("structural animations", function() { they('should decorate the element with the ng-$prop CSS class', ['enter', 'leave', 'move'], function(event) { inject(function($animateCss, $rootElement, $document) { var element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); $animateCss(element, { event: event, structural: true, duration: 1000, to: fakeStyle }); expect(element).toHaveClass('ng-' + event); }); }); they('should decorate the element with the ng-$prop-active CSS class', ['enter', 'leave', 'move'], function(event) { inject(function($animateCss, $rootElement, $document) { var element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); var animator = $animateCss(element, { event: event, structural: true, duration: 1000, to: fakeStyle }); animator.start(); triggerAnimationStartFrame(); expect(element).toHaveClass('ng-' + event + '-active'); }); }); they('should remove the ng-$prop and ng-$prop-active CSS classes from the element once the animation is done', ['enter', 'leave', 'move'], function(event) { inject(function($animateCss, $rootElement, $document) { var element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); var animator = $animateCss(element, { event: event, structural: true, duration: 1, to: fakeStyle }); animator.start(); triggerAnimationStartFrame(); browserTrigger(element, 'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); expect(element).not.toHaveClass('ng-' + event); expect(element).not.toHaveClass('ng-' + event + '-active'); }); }); they('should allow additional CSS classes to be added and removed alongside the $prop animation', ['enter', 'leave', 'move'], function(event) { inject(function($animateCss, $rootElement) { var element = angular.element('<div class="green"></div>'); $rootElement.append(element); var animator = $animateCss(element, { event: event, structural: true, duration: 1, to: fakeStyle, addClass: 'red', removeClass: 'green' }); animator.start(); triggerAnimationStartFrame(); expect(element).toHaveClass('ng-' + event); expect(element).toHaveClass('ng-' + event + '-active'); expect(element).toHaveClass('red'); expect(element).toHaveClass('red-add'); expect(element).toHaveClass('red-add-active'); expect(element).not.toHaveClass('green'); expect(element).toHaveClass('green-remove'); expect(element).toHaveClass('green-remove-active'); }); }); they('should place a CSS transition block after the preparation function to block accidental style changes', ['enter', 'leave', 'move', 'addClass', 'removeClass'], function(event) { inject(function($animateCss, $rootElement, $document) { var element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); ss.addRule('.cool-animation', 'transition:1.5s linear all;'); element.addClass('cool-animation'); var data = {}; if (event === 'addClass') { data.addClass = 'green'; } else if (event === 'removeClass') { element.addClass('red'); data.removeClass = 'red'; } else { data.event = event; } var animator = $animateCss(element, data); expect(element.css('transition-delay')).toMatch('-1.5s'); animator.start(); triggerAnimationStartFrame(); expect(element.attr('style')).toBeFalsy(); }); }); they('should not place a CSS transition block if options.skipBlocking is provided', ['enter', 'leave', 'move', 'addClass', 'removeClass'], function(event) { inject(function($animateCss, $rootElement, $document, $window) { var element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); ss.addRule('.cool-animation', 'transition:1.5s linear all;'); element.addClass('cool-animation'); var data = {}; if (event === 'addClass') { data.addClass = 'green'; } else if (event === 'removeClass') { element.addClass('red'); data.removeClass = 'red'; } else { data.event = event; } var blockSpy = spyOn($window, 'blockTransitions').and.callThrough(); data.skipBlocking = true; var animator = $animateCss(element, data); expect(blockSpy).not.toHaveBeenCalled(); expect(element.attr('style')).toBeFalsy(); animator.start(); triggerAnimationStartFrame(); expect(element.attr('style')).toBeFalsy(); // just to prove it works data.skipBlocking = false; $animateCss(element, { addClass: 'test' }); expect(blockSpy).toHaveBeenCalled(); }); }); they('should place a CSS transition block after the preparation function even if a duration is provided', ['enter', 'leave', 'move', 'addClass', 'removeClass'], function(event) { inject(function($animateCss, $rootElement, $document) { var element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); ss.addRule('.cool-animation', 'transition:1.5s linear all;'); element.addClass('cool-animation'); var data = {}; if (event === 'addClass') { data.addClass = 'green'; } else if (event === 'removeClass') { element.addClass('red'); data.removeClass = 'red'; } else { data.event = event; } data.duration = 10; var animator = $animateCss(element, data); expect(element.css('transition-delay')).toMatch('-10s'); expect(element.css('transition-duration')).toMatch(''); animator.start(); triggerAnimationStartFrame(); expect(element.attr('style')).not.toContain('transition-delay'); expect(element.css('transition-property')).toContain('all'); expect(element.css('transition-duration')).toContain('10s'); }); }); it('should allow multiple events to be animated at the same time', inject(function($animateCss, $rootElement, $document) { var element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); $animateCss(element, { event: ['enter', 'leave', 'move'], structural: true, duration: 1, to: fakeStyle }).start(); triggerAnimationStartFrame(); expect(element).toHaveClass('ng-enter'); expect(element).toHaveClass('ng-leave'); expect(element).toHaveClass('ng-move'); expect(element).toHaveClass('ng-enter-active'); expect(element).toHaveClass('ng-leave-active'); expect(element).toHaveClass('ng-move-active'); browserTrigger(element, 'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); expect(element).not.toHaveClass('ng-enter'); expect(element).not.toHaveClass('ng-leave'); expect(element).not.toHaveClass('ng-move'); expect(element).not.toHaveClass('ng-enter-active'); expect(element).not.toHaveClass('ng-leave-active'); expect(element).not.toHaveClass('ng-move-active'); })); it('should not break when running anchored animations without duration', inject(function($animate, $document, $rootElement) { var element1 = angular.element('<div class="item" ng-animate-ref="test">Item 1</div>'); var element2 = angular.element('<div class="item" ng-animate-ref="test">Item 2</div>'); angular.element($document[0].body).append($rootElement); $rootElement.append(element1); expect($rootElement.text()).toBe('Item 1'); $animate.leave(element1); $animate.enter(element2, $rootElement); $animate.flush(); expect($rootElement.text()).toBe('Item 2'); }) ); }); describe("class-based animations", function() { they('should decorate the element with the class-$prop CSS class', ['add', 'remove'], function(event) { inject(function($animateCss, $rootElement) { var element = angular.element('<div></div>'); $rootElement.append(element); var options = {}; options[event + 'Class'] = 'class'; options.duration = 1000; options.to = fakeStyle; $animateCss(element, options); expect(element).toHaveClass('class-' + event); }); }); they('should decorate the element with the class-$prop-active CSS class', ['add', 'remove'], function(event) { inject(function($animateCss, $rootElement) { var element = angular.element('<div></div>'); $rootElement.append(element); var options = {}; options[event + 'Class'] = 'class'; options.duration = 1000; options.to = fakeStyle; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); expect(element).toHaveClass('class-' + event + '-active'); }); }); they('should remove the class-$prop-add and class-$prop-active CSS classes from the element once the animation is done', ['enter', 'leave', 'move'], function(event) { inject(function($animateCss, $rootElement, $document) { var element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); var options = {}; options.event = event; options.duration = 10; options.to = fakeStyle; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); browserTrigger(element, 'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 10 }); expect(element).not.toHaveClass('ng-' + event); expect(element).not.toHaveClass('ng-' + event + '-active'); }); }); they('should allow the class duration styles to be recalculated once started if the CSS classes being applied result new transition styles', ['add', 'remove'], function(event) { inject(function($animateCss, $rootElement, $document) { var element = angular.element('<div></div>'); if (event == 'add') { ss.addRule('.natural-class', 'transition:1s linear all;'); } else { ss.addRule('.natural-class', 'transition:0s linear none;'); ss.addRule('.base-class', 'transition:1s linear none;'); element.addClass('base-class'); element.addClass('natural-class'); } $rootElement.append(element); angular.element($document[0].body).append($rootElement); var options = {}; options[event + 'Class'] = 'natural-class'; var runner = $animateCss(element, options); runner.start(); triggerAnimationStartFrame(); expect(element).toHaveClass('natural-class-' + event); expect(element).toHaveClass('natural-class-' + event + '-active'); browserTrigger(element, 'transitionend', { timeStamp: Date.now(), elapsedTime: 1 }); expect(element).not.toHaveClass('natural-class-' + event); expect(element).not.toHaveClass('natural-class-' + event + '-active'); }); }); they('should force the class-based values to be applied early if no options.applyClassEarly is used as an option', ['enter', 'leave', 'move'], function(event) { inject(function($animateCss, $rootElement, $document) { ss.addRule('.blue.ng-' + event, 'transition:2s linear all;'); var element = angular.element('<div class="red"></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); var runner = $animateCss(element, { addClass: 'blue', applyClassesEarly: true, removeClass: 'red', event: event, structural: true }); runner.start(); expect(element).toHaveClass('ng-' + event); expect(element).toHaveClass('blue'); expect(element).not.toHaveClass('red'); triggerAnimationStartFrame(); expect(element).toHaveClass('ng-' + event); expect(element).toHaveClass('ng-' + event + '-active'); expect(element).toHaveClass('blue'); expect(element).not.toHaveClass('red'); browserTrigger(element, 'transitionend', { timeStamp: Date.now(), elapsedTime: 2 }); expect(element).not.toHaveClass('ng-' + event); expect(element).not.toHaveClass('ng-' + event + '-active'); expect(element).toHaveClass('blue'); expect(element).not.toHaveClass('red'); }); }); }); describe("options", function() { var element; beforeEach(module(function() { return function($rootElement, $document) { angular.element($document[0].body).append($rootElement); element = angular.element('<div></div>'); $rootElement.append(element); }; })); it("should not alter the provided options input in any way throughout the animation", inject(function($animateCss) { var initialOptions = { from: { height: '50px' }, to: { width: '50px' }, addClass: 'one', removeClass: 'two', duration: 10, delay: 10, structural: true, keyframeStyle: '1s rotate', transitionStyle: '1s linear', stagger: 0.5, staggerIndex: 3 }; var copiedOptions = copy(initialOptions); expect(copiedOptions).toEqual(initialOptions); var animator = $animateCss(element, copiedOptions); expect(copiedOptions).toEqual(initialOptions); var runner = animator.start(); expect(copiedOptions).toEqual(initialOptions); triggerAnimationStartFrame(); expect(copiedOptions).toEqual(initialOptions); runner.end(); expect(copiedOptions).toEqual(initialOptions); })); it("should not create a copy of the provided options if they have already been prepared earlier", inject(function($animate, $animateCss) { var options = { from: { height: '50px' }, to: { width: '50px' }, addClass: 'one', removeClass: 'two' }; options.$$prepared = true; var runner = $animateCss(element, options).start(); runner.end(); $animate.flush(); expect(options.addClass).toBeFalsy(); expect(options.removeClass).toBeFalsy(); expect(options.to).toBeFalsy(); expect(options.from).toBeFalsy(); })); describe("[$$skipPreparationClasses]", function() { it('should not apply and remove the preparation classes to the element when true', inject(function($animateCss) { var options = { duration: 3000, to: fakeStyle, event: 'event', structural: true, addClass: 'klass', $$skipPreparationClasses: true }; var animator = $animateCss(element, options); expect(element).not.toHaveClass('klass-add'); expect(element).not.toHaveClass('ng-event'); var runner = animator.start(); triggerAnimationStartFrame(); expect(element).not.toHaveClass('klass-add'); expect(element).not.toHaveClass('ng-event'); expect(element).toHaveClass('klass-add-active'); expect(element).toHaveClass('ng-event-active'); element.addClass('klass-add ng-event'); runner.end(); expect(element).toHaveClass('klass-add'); expect(element).toHaveClass('ng-event'); expect(element).not.toHaveClass('klass-add-active'); expect(element).not.toHaveClass('ng-event-active'); })); }); describe("[duration]", function() { it("should be applied for a transition directly", inject(function($animateCss, $rootElement) { var element = angular.element('<div></div>'); $rootElement.append(element); var options = { duration: 3000, to: fakeStyle, event: 'enter', structural: true }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); var style = element.attr('style'); expect(style).toContain('3000s'); expect(style).toContain('linear'); })); it("should be applied to a CSS keyframe animation directly if keyframes are detected within the CSS class", inject(function($animateCss, $rootElement) { ss.addRule('.ng-enter', '-webkit-animation:1.5s keyframe_animation;' + 'animation:1.5s keyframe_animation;'); var options = { duration: 5, event: 'enter', structural: true }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); expect(getPossiblyPrefixedStyleValue(element, 'animation-duration')).toEqual('5s'); })); it("should remove all inline keyframe styling when an animation completes if a custom duration was applied", inject(function($animateCss, $rootElement) { ss.addRule('.ng-enter', '-webkit-animation:1.5s keyframe_animation;' + 'animation:1.5s keyframe_animation;'); var options = { duration: 5, event: 'enter', structural: true }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); browserTrigger(element, 'animationend', { timeStamp: Date.now() + 5000, elapsedTime: 5 }); expect(element.attr('style')).toBeFalsy(); })); it("should remove all inline keyframe delay styling when an animation completes if a custom duration was applied", inject(function($animateCss, $rootElement) { ss.addRule('.ng-enter', '-webkit-animation:1.5s keyframe_animation;' + 'animation:1.5s keyframe_animation;'); var options = { delay: 5, event: 'enter', structural: true }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); expect(getPossiblyPrefixedStyleValue(element, 'animation-delay')).toEqual('5s'); browserTrigger(element, 'animationend', { timeStamp: Date.now() + 5000, elapsedTime: 1.5 }); expect(element.attr('style')).toBeFalsy(); })); it("should not prepare the animation at all if a duration of zero is provided", inject(function($animateCss, $rootElement) { ss.addRule('.ng-enter', '-webkit-transition:1s linear all;' + 'transition:1s linear all;'); var options = { duration: 0, event: 'enter', structural: true }; var animator = $animateCss(element, options); expect(animator.$$willAnimate).toBeFalsy(); })); it("should apply a transition and keyframe duration directly if both transitions and keyframe classes are detected", inject(function($animateCss, $rootElement) { ss.addRule('.ng-enter', '-webkit-animation:3s keyframe_animation;' + 'animation:3s keyframe_animation;' + 'transition:5s linear all;'); var options = { duration: 4, event: 'enter', structural: true }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); var style = element.attr('style'); expect(style).toMatch(/animation(?:-duration)?:\s*4s/); expect(element.css('transition-duration')).toMatch('4s'); expect(element.css('transition-property')).toMatch('all'); expect(style).toContain('linear'); })); }); describe("[delay]", function() { it("should be applied for a transition directly", inject(function($animateCss, $rootElement) { var element = angular.element('<div></div>'); $rootElement.append(element); var options = { duration: 3000, delay: 500, to: fakeStyle, event: 'enter', structural: true }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); var prop = element.css('transition-delay'); expect(prop).toEqual('500s'); })); it("should return false for the animator if a delay is provided but not a duration", inject(function($animateCss, $rootElement) { var element = angular.element('<div></div>'); $rootElement.append(element); var options = { delay: 500, to: fakeStyle, event: 'enter', structural: true }; var animator = $animateCss(element, options); expect(animator.$$willAnimate).toBeFalsy(); })); it("should override the delay value present in the CSS class", inject(function($animateCss, $rootElement) { ss.addRule('.ng-enter', '-webkit-transition:1s linear all;' + 'transition:1s linear all;' + '-webkit-transition-delay:10s;' + 'transition-delay:10s;'); var element = angular.element('<div></div>'); $rootElement.append(element); var options = { delay: 500, event: 'enter', structural: true }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); var prop = element.css('transition-delay'); expect(prop).toEqual('500s'); })); it("should allow the delay value to zero if provided", inject(function($animateCss, $rootElement) { ss.addRule('.ng-enter', '-webkit-transition:1s linear all;' + 'transition:1s linear all;' + '-webkit-transition-delay:10s;' + 'transition-delay:10s;'); var element = angular.element('<div></div>'); $rootElement.append(element); var options = { delay: 0, event: 'enter', structural: true }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); var prop = element.css('transition-delay'); expect(prop).toEqual('0s'); })); it("should be applied to a CSS keyframe animation if detected within the CSS class", inject(function($animateCss, $rootElement) { ss.addRule('.ng-enter', '-webkit-animation:1.5s keyframe_animation;' + 'animation:1.5s keyframe_animation;'); var options = { delay: 400, event: 'enter', structural: true }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); expect(getPossiblyPrefixedStyleValue(element, 'animation-delay')).toEqual('400s'); expect(element.attr('style')).not.toContain('transition-delay'); })); it("should apply a transition and keyframe delay if both transitions and keyframe classes are detected", inject(function($animateCss, $rootElement) { ss.addRule('.ng-enter', '-webkit-animation:3s keyframe_animation;' + 'animation:3s keyframe_animation;' + 'transition:5s linear all;'); var options = { delay: 10, event: 'enter', structural: true }; var animator = $animateCss(element, options); expect(element.css('transition-delay')).toContain('-5s'); expect(element.attr('style')).not.toContain('animation-delay'); animator.start(); triggerAnimationStartFrame(); expect(getPossiblyPrefixedStyleValue(element, 'animation-delay')).toEqual('10s'); expect(element.css('transition-delay')).toEqual('10s'); })); it("should apply the keyframe and transition duration value before the CSS classes are applied", function() { var classSpy = jasmine.createSpy(); module(function($provide) { $provide.value('$$jqLite', { addClass: function() { classSpy(); }, removeClass: function() { classSpy(); } }); }); inject(function($animateCss, $rootElement) { element.addClass('element'); ss.addRule('.element', '-webkit-animation:3s keyframe_animation;' + 'animation:3s keyframe_animation;' + 'transition:5s linear all;'); var options = { delay: 2, duration: 2, addClass: 'superman', $$skipPreparationClasses: true, structural: true }; var animator = $animateCss(element, options); expect(element.attr('style') || '').not.toContain('animation-delay'); expect(element.attr('style') || '').not.toContain('transition-delay'); expect(classSpy).not.toHaveBeenCalled(); //redefine the classSpy to assert that the delay values have been //applied before the classes are added var assertionsRun = false; classSpy = function() { assertionsRun = true; expect(getPossiblyPrefixedStyleValue(element, 'animation-delay')).toEqual('2s'); expect(element.css('transition-delay')).toEqual('2s'); expect(element).not.toHaveClass('superman'); }; animator.start(); triggerAnimationStartFrame(); expect(assertionsRun).toBe(true); }); }); it("should apply blocking before the animation starts, but then apply the detected delay when options.delay is true", inject(function($animateCss, $rootElement) { ss.addRule('.ng-enter', 'transition:2s linear all; transition-delay: 1s;'); var options = { delay: true, event: 'enter', structural: true }; var animator = $animateCss(element, options); expect(element.css('transition-delay')).toEqual('-2s'); animator.start(); triggerAnimationStartFrame(); expect(element.attr('style') || '').not.toContain('transition-delay'); })); it("should consider a negative value when delay:true is used with a keyframe animation", inject(function($animateCss, $rootElement) { ss.addPossiblyPrefixedRule('.ng-enter', 'animation: 2s keyframe_animation; ' + 'animation-delay: -1s;'); var options = { delay: true, event: 'enter', structural: true }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); expect(getPossiblyPrefixedStyleValue(element, 'animation-delay')).toContain('-1s'); })); they("should consider a negative value when a negative option delay is provided for a $prop animation", { 'transition': function() { return { prop: 'transition-delay', css: 'transition:2s linear all' }; }, 'keyframe': function() { return { prop: 'animation-delay', css: 'animation: 2s keyframe_animation' }; } }, function(testDetailsFactory) { inject(function($animateCss, $rootElement) { var testDetails = testDetailsFactory(prefix); ss.addPossiblyPrefixedRule('.ng-enter', testDetails.css); var options = { delay: -2, event: 'enter', structural: true }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); expect(getPossiblyPrefixedStyleValue(element, testDetails.prop)).toContain('-2s'); }); }); they("should expect the $propend event to always return the full duration even when negative values are used", { 'transition': function() { return { event: 'transitionend', css: 'transition:5s linear all; transition-delay: -2s' }; }, 'animation': function() { return { event: 'animationend', css: 'animation: 5s keyframe_animation; animation-delay: -2s;' }; } }, function(testDetailsFactory) { inject(function($animateCss, $rootElement) { var testDetails = testDetailsFactory(); var event = testDetails.event; ss.addPossiblyPrefixedRule('.ng-enter', testDetails.css); var options = { event: 'enter', structural: true }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); // 5 + (-2s) = 3 browserTrigger(element, event, { timeStamp: Date.now(), elapsedTime: 3 }); assertAnimationRunning(element, true); // 5 seconds is the full animation browserTrigger(element, event, { timeStamp: Date.now(), elapsedTime: 5 }); assertAnimationRunning(element); }); }); }); describe("[transitionStyle]", function() { it("should apply the transition directly onto the element and animate accordingly", inject(function($animateCss, $rootElement) { var options = { transitionStyle: '5.5s linear all', event: 'enter', structural: true }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); var style = element.attr('style'); expect(element.css('transition-duration')).toMatch('5.5s'); expect(element.css('transition-property')).toMatch('all'); expect(style).toContain('linear'); expect(element).toHaveClass('ng-enter'); expect(element).toHaveClass('ng-enter-active'); browserTrigger(element, 'transitionend', { timeStamp: Date.now() + 10000, elapsedTime: 5.5 }); expect(element).not.toHaveClass('ng-enter'); expect(element).not.toHaveClass('ng-enter-active'); expect(element.attr('style')).toBeFalsy(); })); it("should give priority to the provided duration value, but only update the duration style itself", inject(function($animateCss, $rootElement) { var options = { transitionStyle: '5.5s ease-in color', duration: 4, event: 'enter', structural: true }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); var style = element.attr('style'); expect(element.css('transition-duration')).toMatch('4s'); expect(element.css('transition-property')).toMatch('color'); expect(style).toContain('ease-in'); })); it("should give priority to the provided delay value, but only update the delay style itself", inject(function($animateCss, $rootElement) { var options = { transitionStyle: '5.5s 4s ease-in color', delay: 20, event: 'enter', structural: true }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); var style = element.attr('style'); expect(element.css('transition-delay')).toMatch('20s'); expect(element.css('transition-duration')).toMatch('5.5s'); expect(element.css('transition-property')).toMatch('color'); expect(style).toContain('ease-in'); })); it("should execute the animation only if there is any provided CSS styling to go with the transition", inject(function($animateCss, $rootElement) { var options = { transitionStyle: '6s 4s ease-out all' }; $animateCss(element, options).start(); triggerAnimationStartFrame(); expect(getPossiblyPrefixedStyleValue(element, 'transition-delay')).not.toEqual('4s'); expect(getPossiblyPrefixedStyleValue(element, 'transition-duration')).not.toEqual('6s'); options.to = { color: 'brown' }; $animateCss(element, options).start(); triggerAnimationStartFrame(); expect(getPossiblyPrefixedStyleValue(element, 'transition-delay')).toEqual('4s'); expect(getPossiblyPrefixedStyleValue(element, 'transition-duration')).toEqual('6s'); })); }); describe("[keyframeStyle]", function() { it("should apply the keyframe animation directly onto the element and animate accordingly", inject(function($animateCss, $rootElement) { var options = { keyframeStyle: 'my_animation 5.5s', event: 'enter', structural: true }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); var detectedStyle = element.attr('style'); expect(detectedStyle).toContain('5.5s'); expect(detectedStyle).toContain('my_animation'); expect(element).toHaveClass('ng-enter'); expect(element).toHaveClass('ng-enter-active'); browserTrigger(element, 'animationend', { timeStamp: Date.now() + 10000, elapsedTime: 5.5 }); expect(element).not.toHaveClass('ng-enter'); expect(element).not.toHaveClass('ng-enter-active'); expect(element.attr('style')).toBeFalsy(); })); it("should give priority to the provided duration value, but only update the duration style itself", inject(function($animateCss, $rootElement) { var options = { keyframeStyle: 'my_animation 5.5s', duration: 50, event: 'enter', structural: true }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); var detectedStyle = element.attr('style'); expect(detectedStyle).toContain('50s'); expect(detectedStyle).toContain('my_animation'); })); it("should give priority to the provided delay value, but only update the duration style itself", inject(function($animateCss, $rootElement) { var options = { keyframeStyle: 'my_animation 5.5s 10s', delay: 50, event: 'enter', structural: true }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); expect(getPossiblyPrefixedStyleValue(element, 'animation-delay')).toEqual('50s'); expect(getPossiblyPrefixedStyleValue(element, 'animation-duration')).toEqual('5.5s'); expect(getPossiblyPrefixedStyleValue(element, 'animation-name')).toEqual('my_animation'); })); it("should be able to execute the animation if it is the only provided value", inject(function($animateCss, $rootElement) { var options = { keyframeStyle: 'my_animation 5.5s 10s' }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); expect(getPossiblyPrefixedStyleValue(element, 'animation-delay')).toEqual('10s'); expect(getPossiblyPrefixedStyleValue(element, 'animation-duration')).toEqual('5.5s'); expect(getPossiblyPrefixedStyleValue(element, 'animation-name')).toEqual('my_animation'); })); }); describe("[from] and [to]", function() { it("should apply from styles to an element during the preparation phase", inject(function($animateCss, $rootElement) { var options = { duration: 2.5, event: 'enter', structural: true, from: { width: '50px' }, to: { width: '100px' } }; var animator = $animateCss(element, options); expect(element.attr('style')).toMatch(/width:\s*50px/); })); it("should apply to styles to an element during the animation phase", inject(function($animateCss, $rootElement) { var options = { duration: 2.5, event: 'enter', structural: true, from: { width: '15px' }, to: { width: '25px' } }; var animator = $animateCss(element, options); var runner = animator.start(); triggerAnimationStartFrame(); runner.end(); expect(element.css('width')).toBe('25px'); })); it("should apply the union of from and to styles to the element if no animation will be run", inject(function($animateCss, $rootElement) { var options = { event: 'enter', structural: true, from: { 'width': '10px', height: '50px' }, to: { 'width': '15px' } }; var animator = $animateCss(element, options); expect(animator.$$willAnimate).toBeFalsy(); animator.start(); expect(element.css('width')).toBe('15px'); expect(element.css('height')).toBe('50px'); })); it("should retain to and from styles on an element after an animation completes", inject(function($animateCss, $rootElement) { var options = { event: 'enter', structural: true, duration: 10, from: { 'width': '10px', height: '66px' }, to: { 'width': '5px' } }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); browserTrigger(element, 'transitionend', { timeStamp: Date.now() + 10000, elapsedTime: 10 }); expect(element).not.toHaveClass('ng-enter'); expect(element.css('width')).toBe('5px'); expect(element.css('height')).toBe('66px'); })); it("should always apply the from styles before the start function is called even if no transition is detected when started", inject(function($animateCss, $rootElement) { ss.addRule('.my-class', 'transition: 0s linear color'); var options = { addClass: 'my-class', from: { height: '26px' }, to: { height: '500px' } }; var animator = $animateCss(element, options); expect(element.css('height')).toBe('26px'); animator.start(); triggerAnimationStartFrame(); expect(element.css('height')).toBe('500px'); })); it("should apply an inline transition if [to] styles and a duration are provided", inject(function($animateCss, $rootElement) { var options = { event: 'enter', structural: true, duration: 2.5, to: { background: 'red' } }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); var style = element.attr('style'); expect(element.css('transition-duration')).toMatch('2.5s'); expect(element.css('transition-property')).toMatch('all'); expect(style).toContain('linear'); })); it("should remove all inline transition styling when an animation completes", inject(function($animateCss, $rootElement) { var options = { event: 'enter', structural: true, duration: 2.5, to: { background: 'red' } }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); var style = element.attr('style'); expect(style).toContain('transition'); browserTrigger(element, 'transitionend', { timeStamp: Date.now() + 2500, elapsedTime: 2.5 }); style = element.attr('style'); expect(style).not.toContain('transition'); })); it("should retain existing styles when an inline styled animation completes", inject(function($animateCss, $rootElement) { var options = { event: 'enter', structural: true, duration: 2.5 }; element.css('font-size', '20px'); element.css('opacity', '0.5'); var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); var style = element.attr('style'); expect(style).toContain('transition'); animator.end(); style = element.attr('style'); expect(element.attr('style')).not.toContain('transition'); expect(element.css('opacity')).toEqual('0.5'); })); it("should remove all inline transition delay styling when an animation completes", inject(function($animateCss, $rootElement) { ss.addRule('.ng-enter', 'transition: 1s linear color'); var options = { event: 'enter', structural: true, delay: 5 }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); expect(element.css('transition-delay')).toEqual('5s'); browserTrigger(element, 'transitionend', { timeStamp: Date.now() + 5000, elapsedTime: 1 }); expect(element.attr('style') || '').not.toContain('transition'); })); it("should not apply an inline transition if only [from] styles and a duration are provided", inject(function($animateCss, $rootElement) { var options = { duration: 3, from: { background: 'blue' } }; var animator = $animateCss(element, options); expect(animator.$$willAnimate).toBeFalsy(); })); it("should apply a transition if [from] styles are provided with a class that is added", inject(function($animateCss, $rootElement) { var options = { addClass: 'superb', from: { background: 'blue' } }; var animator = $animateCss(element, options); expect(isFunction(animator.start)).toBe(true); })); it("should apply an inline transition if only [from] styles, but classes are added or removed and a duration is provided", inject(function($animateCss, $rootElement) { var options = { duration: 3, addClass: 'sugar', from: { background: 'yellow' } }; var animator = $animateCss(element, options); expect(animator.$$willAnimate).toBeTruthy(); })); it("should not apply an inline transition if no styles are provided", inject(function($animateCss, $rootElement) { var emptyObject = {}; var options = { duration: 3, to: emptyObject, from: emptyObject }; var animator = $animateCss(element, options); expect(animator.$$willAnimate).toBeFalsy(); })); it("should apply a transition duration if the existing transition duration's property value is not 'all'", inject(function($animateCss, $rootElement) { ss.addRule('.ng-enter', 'transition: 1s linear color'); var emptyObject = {}; var options = { event: 'enter', structural: true, to: { background: 'blue' } }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); var style = element.attr('style'); expect(element.css('transition-duration')).toMatch('1s'); expect(element.css('transition-property')).toMatch('all'); expect(style).toContain('linear'); })); it("should apply a transition duration and an animation duration if duration + styles options are provided for a matching keyframe animation", inject(function($animateCss, $rootElement) { ss.addRule('.ng-enter', '-webkit-animation:3.5s keyframe_animation;' + 'animation:3.5s keyframe_animation;'); var emptyObject = {}; var options = { event: 'enter', structural: true, duration: 10, to: { background: 'blue' } }; var animator = $animateCss(element, options); animator.start(); triggerAnimationStartFrame(); expect(element.css('transition-duration')).toMatch('10s'); expect(getPossiblyPrefixedStyleValue(element, 'animation-duration')).toEqual('10s'); })); }); describe("[easing]", function() { var element; beforeEach(inject(function($document, $rootElement) { element = angular.element('<div></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); })); it("should apply easing to a transition animation if it exists", inject(function($animateCss) { ss.addRule('.red', 'transition:1s linear all;'); var easing = 'ease-out'; var animator = $animateCss(element, { addClass: 'red', easing: easing }); animator.start(); triggerAnimationStartFrame(); var style = element.attr('style'); expect(style).toContain('ease-out'); })); it("should not apply easing to transitions nor keyframes on an element animation if nothing is detected", inject(function($animateCss) { ss.addRule('.red', ';'); var easing = 'ease-out'; var animator = $animateCss(element, { addClass: 'red', easing: easing }); animator.start(); triggerAnimationStartFrame(); expect(element.attr('style')).toBeFalsy(); })); it("should apply easing to both keyframes and transition animations if detected", inject(function($animateCss) { ss.addRule('.red', 'transition: 1s linear all;'); ss.addPossiblyPrefixedRule('.blue', 'animation: 1s my_keyframe;'); var easing = 'ease-out'; var animator = $animateCss(element, { addClass: 'red blue', easing: easing }); animator.start(); triggerAnimationStartFrame(); var style = element.attr('style'); expect(style).toMatch(/animation(?:-timing-function)?:\s*ease-out/); expect(style).toMatch(/transition(?:-timing-function)?:\s*ease-out/); })); }); describe("[cleanupStyles]", function() { it("should cleanup [from] and [to] styles that have been applied for the animation when true", inject(function($animateCss) { var runner = $animateCss(element, { duration: 1, from: { background: 'gold' }, to: { color: 'brown' }, cleanupStyles: true }).start(); assertStyleIsPresent(element, 'background', true); assertStyleIsPresent(element, 'color', false); triggerAnimationStartFrame(); assertStyleIsPresent(element, 'background', true); assertStyleIsPresent(element, 'color', true); runner.end(); assertStyleIsPresent(element, 'background', false); assertStyleIsPresent(element, 'color', false); function assertStyleIsPresent(element, style, bool) { expect(element[0].style[style])[bool ? 'toBeTruthy' : 'toBeFalsy'](); } })); it('should restore existing overidden styles already present on the element when true', inject(function($animateCss) { element.css('height', '100px'); element.css('width', '111px'); var runner = $animateCss(element, { duration: 1, from: { height: '200px', 'font-size':'66px' }, to: { height: '300px', 'font-size': '99px', width: '222px' }, cleanupStyles: true }).start(); assertStyle(element, 'height', '200px'); assertStyle(element, 'font-size', '66px'); assertStyle(element, 'width', '111px'); triggerAnimationStartFrame(); assertStyle(element, 'height', '300px'); assertStyle(element, 'width', '222px'); assertStyle(element, 'font-size', '99px'); runner.end(); assertStyle(element, 'width', '111px'); assertStyle(element, 'height', '100px'); expect(element[0].style.getPropertyValue('font-size')).not.toBe('66px'); function assertStyle(element, prop, value) { expect(element[0].style.getPropertyValue(prop)).toBe(value); } })); }); it('should round up long elapsedTime values to close off a CSS3 animation', inject(function($animateCss) { ss.addRule('.millisecond-transition.ng-leave', '-webkit-transition:510ms linear all;' + 'transition:510ms linear all;'); element.addClass('millisecond-transition'); var animator = $animateCss(element, { event: 'leave', structural: true }); animator.start(); triggerAnimationStartFrame(); expect(element).toHaveClass('ng-leave-active'); browserTrigger(element, 'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 0.50999999991 }); expect(element).not.toHaveClass('ng-leave-active'); })); }); describe('SVG', function() { it('should properly apply transitions on an SVG element', inject(function($animateCss, $rootScope, $compile, $document, $rootElement) { var element = $compile('<svg width="500" height="500">' + '<circle cx="15" cy="5" r="100" fill="orange" />' + '</svg>')($rootScope); angular.element($document[0].body).append($rootElement); $rootElement.append(element); $animateCss(element, { event: 'enter', structural: true, duration: 10 }).start(); triggerAnimationStartFrame(); expect(element).toHaveClass('ng-enter'); expect(element).toHaveClass('ng-enter-active'); browserTrigger(element, 'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 10 }); expect(element).not.toHaveClass('ng-enter'); expect(element).not.toHaveClass('ng-enter-active'); })); it('should properly remove classes from SVG elements', inject(function($animateCss) { var element = angular.element('<svg width="500" height="500">' + '<rect class="class-of-doom"></rect>' + '</svg>'); var child = element.find('rect'); var animator = $animateCss(child, { removeClass: 'class-of-doom', duration: 0 }); animator.start(); var className = child[0].getAttribute('class'); expect(className).toBe(''); })); }); }); });
/** * @fileoverview Tests for prefer-spread rule. * @author Toru Nagashima * @copyright 2015 Toru Nagashima. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var eslint = require("../../../lib/eslint"); var ESLintTester = require("eslint-tester"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ var errors = [{message: "use the spread operator instead of the \".apply()\".", type: "CallExpression"}]; var eslintTester = new ESLintTester(eslint); eslintTester.addRuleTest("lib/rules/prefer-spread", { valid: [ {code: "foo.apply(obj, args);"}, {code: "obj.foo.apply(null, args);"}, {code: "obj.foo.apply(otherObj, args);"}, {code: "a.b(x, y).c.foo.apply(a.b(x, z).c, args);"}, {code: "a.b.foo.apply(a.b.c, args);"}, // ignores non variadic. {code: "foo.apply(undefined, [1, 2]);"}, {code: "foo.apply(null, [1, 2]);"}, {code: "obj.foo.apply(obj, [1, 2]);"}, // ignores computed property. {code: "var apply; foo[apply](null, args);"}, // ignores incomplete things. {code: "foo.apply();"}, {code: "obj.foo.apply();"} ], invalid: [ {code: "foo.apply(undefined, args);", errors: errors}, {code: "foo.apply(void 0, args);", errors: errors}, {code: "foo.apply(null, args);", errors: errors}, {code: "obj.foo.apply(obj, args);", errors: errors}, {code: "a.b.c.foo.apply(a.b.c, args);", errors: errors}, {code: "a.b(x, y).c.foo.apply(a.b(x, y).c, args);", errors: errors}, {code: "[].concat.apply([ ], args);", errors: errors}, {code: "[].concat.apply([\n/*empty*/\n], args);", errors: errors} ] });
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const util = require("util"); const truncateArgs = require("../logging/truncateArgs"); const tty = process.stderr.isTTY && process.env.TERM !== "dumb"; let currentStatusMessage = undefined; let hasStatusMessage = false; let currentIndent = ""; let currentCollapsed = 0; const indent = (str, prefix, colorPrefix, colorSuffix) => { if (str === "") return str; prefix = currentIndent + prefix; if (tty) { return ( prefix + colorPrefix + str.replace(/\n/g, colorSuffix + "\n" + prefix + colorPrefix) + colorSuffix ); } else { return prefix + str.replace(/\n/g, "\n" + prefix); } }; const clearStatusMessage = () => { if (hasStatusMessage) { process.stderr.write("\x1b[2K\r"); hasStatusMessage = false; } }; const writeStatusMessage = () => { if (!currentStatusMessage) return; const l = process.stderr.columns; const args = l ? truncateArgs(currentStatusMessage, l - 1) : currentStatusMessage; const str = args.join(" "); const coloredStr = `\u001b[1m${str}\u001b[39m\u001b[22m`; process.stderr.write(`\x1b[2K\r${coloredStr}`); hasStatusMessage = true; }; const writeColored = (prefix, colorPrefix, colorSuffix) => { return (...args) => { if (currentCollapsed > 0) return; clearStatusMessage(); // @ts-expect-error const str = indent(util.format(...args), prefix, colorPrefix, colorSuffix); process.stderr.write(str + "\n"); writeStatusMessage(); }; }; const writeGroupMessage = writeColored( "<-> ", "\u001b[1m\u001b[36m", "\u001b[39m\u001b[22m" ); const writeGroupCollapsedMessage = writeColored( "<+> ", "\u001b[1m\u001b[36m", "\u001b[39m\u001b[22m" ); module.exports = { log: writeColored(" ", "\u001b[1m", "\u001b[22m"), debug: writeColored(" ", "", ""), trace: writeColored(" ", "", ""), info: writeColored("<i> ", "\u001b[1m\u001b[32m", "\u001b[39m\u001b[22m"), warn: writeColored("<w> ", "\u001b[1m\u001b[33m", "\u001b[39m\u001b[22m"), error: writeColored("<e> ", "\u001b[1m\u001b[31m", "\u001b[39m\u001b[22m"), logTime: writeColored("<t> ", "\u001b[1m\u001b[35m", "\u001b[39m\u001b[22m"), group: (...args) => { writeGroupMessage(...args); if (currentCollapsed > 0) { currentCollapsed++; } else { currentIndent += " "; } }, groupCollapsed: (...args) => { writeGroupCollapsedMessage(...args); currentCollapsed++; }, groupEnd: () => { if (currentCollapsed > 0) currentCollapsed--; else if (currentIndent.length >= 2) currentIndent = currentIndent.slice(0, currentIndent.length - 2); }, // eslint-disable-next-line node/no-unsupported-features/node-builtins profile: console.profile && (name => console.profile(name)), // eslint-disable-next-line node/no-unsupported-features/node-builtins profileEnd: console.profileEnd && (name => console.profileEnd(name)), clear: tty && // eslint-disable-next-line node/no-unsupported-features/node-builtins console.clear && (() => { clearStatusMessage(); // eslint-disable-next-line node/no-unsupported-features/node-builtins console.clear(); writeStatusMessage(); }), status: tty ? (name, ...args) => { args = args.filter(Boolean); if (name === undefined && args.length === 0) { clearStatusMessage(); currentStatusMessage = undefined; } else if ( typeof name === "string" && name.startsWith("[webpack.Progress] ") ) { currentStatusMessage = [name.slice(19), ...args]; writeStatusMessage(); } else if (name === "[webpack.Progress]") { currentStatusMessage = [...args]; writeStatusMessage(); } else { currentStatusMessage = [name, ...args]; writeStatusMessage(); } } : writeColored("<s> ", "", "") };
var assert = require('assert'), posix = require("../../lib/posix"); assert.throws(function() { posix.getgrnam(); }, /requires exactly 1 argument/); assert.throws(function() { posix.getgrnam(1, 2); }, /requires exactly 1 argument/); assert.throws(function() { posix.getgrnam("doesnotexistzzz123"); }, /group id does not exist/); assert.throws(function() { posix.getgrnam(65432); }, /group id does not exist/); var entry = posix.getgrnam("daemon"); console.log("getgrnam: " + JSON.stringify(entry)); assert.equal(entry.name, "daemon"); assert.equal(typeof(entry.gid), "number"); assert.equal(typeof(entry.passwd), "string"); assert.equal(posix.getgrnam(entry.gid).name, "daemon");
'use strict' /** * Explicit enumeration of the states a transaction can be in: * * PENDING upon instantiation (implicitly, no start time set) * RUNNING while timer is running (implicitly, start time is set but no stop * time is set). * STOPPED timer has been completed (implicitly, start time and stop time * are set, but the timer has not yet been harvested). * DEAD timer has been harvested and can only have its duration read. */ var PENDING = 1 var RUNNING = 2 var STOPPED = 3 function hrToMillis(hr) { // process.hrTime gives you [second, nanosecond] duration pairs return (hr[0] * 1e3) + (hr[1] / 1e6) } /** * A mildly tricky timer that tracks its own state and allows its duration * to be set manually. */ function Timer() { this.state = PENDING this.touched = false this.duration = null this.hrDuration = null this.hrstart = null this.durationInMillis = null } /** * Start measuring time elapsed. * * Uses process.hrtime if available, Date.now() otherwise. */ Timer.prototype.begin = function begin() { if (this.state > PENDING) return this.start = Date.now() // need to put a guard on this for compatibility with Node < 0.8 if (process.hrtime) this.hrstart = process.hrtime() this.state = RUNNING } /** * End measurement. */ Timer.prototype.end = function end() { if (this.state > RUNNING) return if (this.state === PENDING) this.begin() if (process.hrtime) this.hrDuration = process.hrtime(this.hrstart) this.touched = true this.duration = Date.now() - this.start this.state = STOPPED } /** * Update the duration of the timer without ending it.. */ Timer.prototype.touch = function touch() { this.touched = true if (this.state > RUNNING) return if (this.state === PENDING) this.begin() if (process.hrtime) this.hrDuration = process.hrtime(this.hrstart) this.duration = Date.now() - this.start } /** * End the segment if it is still running, if touched use that time instead of * "now". Returns a boolean indicating whether the end time changed. */ Timer.prototype.softEnd = function softEnd() { if (this.state > RUNNING) return false if (this.state === PENDING) this.begin() this.state = STOPPED if (this.touched) return false if (process.hrtime) this.hrDuration = process.hrtime(this.hrstart) this.touched = true this.duration = Date.now() - this.start return true } /** * @return {bool} Is this timer currently running? */ Timer.prototype.isRunning = function isRunning() { return this.state === RUNNING } /** * @return {bool} Is this timer still alive? */ Timer.prototype.isActive = function isActive() { return this.state < STOPPED } /** * @return {bool} Has the timer been touched or ended? */ Timer.prototype.hasEnd = function hasEnd() { return !!this.hrDuration } /* * Sets duration and stops the timer, since the passed-in duration will take precendence * over the measured duration. * @param {number} duration The duration the timer should report. */ Timer.prototype.overwriteDurationInMillis = overwriteDurationInMillis function overwriteDurationInMillis(duration) { this.touched = true this.durationInMillis = duration this.state = STOPPED } /** * When testing, it's convenient to be able to control time. Stops the timer * as a byproduct. * * @param {number} duration How long the timer ran. * @param {number} start When the timer started running (optional). */ Timer.prototype.setDurationInMillis = function setDurationInMillis(duration, start) { if (this.state > RUNNING) return if (this.state === PENDING) if (!start && start !== 0) this.begin() this.state = STOPPED this.durationInMillis = duration // this assignment is incorrect, process.hrtime doesn't time from epoch, which // is the assumption being made here. since hrstart isn't used // anywhere except to calculate duration, and we are setting duration // this is fine. this.hrstart = [Math.floor(start / 1e3), start % 1e3 * 1e6] this.start = start } /** * Returns how long the timer has been running (if it's still running) or * how long it ran (if it's been ended or touched). */ Timer.prototype.getDurationInMillis = function getDurationInMillis() { if (this.state === PENDING) return 0 // only set by setDurationInMillis if (this.durationInMillis !== null && this.durationInMillis >= 0) { return this.durationInMillis } // prioritize .end() and .touch() if (this.hrDuration) { return hrToMillis(this.hrDuration) } if (this.duration) { return this.duration } if (process.hrtime) { return hrToMillis(process.hrtime(this.hrstart)) } return Date.now() - this.start } /** * Get a single object containing the interval this timer was active. * * @return {Array} 2-tuple of start time in milliseconds, end time in * milliseconds. */ Timer.prototype.toRange = function toRange() { return [this.start, this.start + this.getDurationInMillis()] } /** * Abstract away the nonsense related to having both an * hrtime start time and a regular one, and always return * milliseconds since start. * * @param {Timer} other The point relative to which this timer started. * @return {number} The offset in (floating-point) milliseconds. */ Timer.prototype.startedRelativeTo = function startedRelativeTo(other) { if (this.hrstart && other.hrstart && process.hrtime) { var s = this.hrstart[0] - other.hrstart[0] var ns = this.hrstart[1] - other.hrstart[1] return hrToMillis([s, ns]) } return this.start - other.start } /** * Returns true if this timer ends after the other. */ Timer.prototype.endsAfter = function compare(other) { return (this.getDurationInMillis() + this.start) > (other.getDurationInMillis() + other.start) } module.exports = Timer
/* */ 'use strict'; var getKeys = require('./_object-keys'), gOPS = require('./_object-gops'), pIE = require('./_object-pie'), toObject = require('./_to-object'), IObject = require('./_iobject'); module.exports = require('./_fails')(function() { var a = Object.assign, A = {}, B = {}, S = Symbol(), K = 'abcdefghijklmnopqrst'; A[S] = 7; K.split('').forEach(function(k) { B[k] = k; }); return a({}, A)[S] != 7 || Object.keys(a({}, B)).join('') != K; }) ? function assign(target, source) { var T = toObject(target), aLen = arguments.length, index = 1, getSymbols = gOPS.f, isEnum = pIE.f; while (aLen > index) { var S = IObject(arguments[index++]), keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S), length = keys.length, j = 0, key; while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key]; } return T; } : Object.assign;
'use strict'; // Init the application configuration module for AngularJS application var ApplicationConfiguration = (function() { // Init module configuration options var applicationModuleName = 'mean'; var applicationModuleVendorDependencies = ['ngResource', 'ngCookies', 'ngAnimate', 'ngTouch', 'ngSanitize', 'ui.router', 'ui.bootstrap', 'ui.utils', 'ui.gravatar']; // Add a new vertical module var registerModule = function(moduleName) { // Create angular module angular.module(moduleName, []); // Add the module to the AngularJS configuration file angular.module(applicationModuleName).requires.push(moduleName); }; return { applicationModuleName: applicationModuleName, applicationModuleVendorDependencies: applicationModuleVendorDependencies, registerModule: registerModule }; })();
var assert = require('assert'); var express = require('..'); var methods = require('methods'); var request = require('supertest'); describe('res', function(){ describe('.send(null)', function(){ it('should set body to ""', function(done){ var app = express(); app.use(function(req, res){ res.send(null); }); request(app) .get('/') .expect('Content-Length', '0') .expect('', done); }) }) describe('.send(undefined)', function(){ it('should set body to ""', function(done){ var app = express(); app.use(function(req, res){ res.send(undefined); }); request(app) .get('/') .expect('', function(req, res){ res.header.should.not.have.property('content-length'); done(); }); }) }) describe('.send(code)', function(){ it('should set .statusCode', function(done){ var app = express(); app.use(function(req, res){ res.send(201).should.equal(res); }); request(app) .get('/') .expect('Created') .expect(201, done); }) }) describe('.send(code, body)', function(){ it('should set .statusCode and body', function(done){ var app = express(); app.use(function(req, res){ res.send(201, 'Created :)'); }); request(app) .get('/') .expect('Created :)') .expect(201, done); }) }) describe('.send(body, code)', function(){ it('should be supported for backwards compat', function(done){ var app = express(); app.use(function(req, res){ res.send('Bad!', 400); }); request(app) .get('/') .expect('Bad!') .expect(400, done); }) }) describe('.send(code, number)', function(){ it('should send number as json', function(done){ var app = express(); app.use(function(req, res){ res.send(200, 0.123); }); request(app) .get('/') .expect('Content-Type', 'application/json; charset=utf-8') .expect(200, '0.123', done); }) }) describe('.send(String)', function(){ it('should send as html', function(done){ var app = express(); app.use(function(req, res){ res.send('<p>hey</p>'); }); request(app) .get('/') .end(function(err, res){ res.headers.should.have.property('content-type', 'text/html; charset=utf-8'); res.text.should.equal('<p>hey</p>'); res.statusCode.should.equal(200); done(); }) }) it('should set ETag', function (done) { var app = express(); app.use(function (req, res) { var str = Array(1000).join('-'); res.send(str); }); request(app) .get('/') .expect('ETag', 'W/"3e7-8084ccd1"') .expect(200, done); }) it('should not override Content-Type', function(done){ var app = express(); app.use(function(req, res){ res.set('Content-Type', 'text/plain').send('hey'); }); request(app) .get('/') .expect('Content-Type', 'text/plain; charset=utf-8') .expect(200, 'hey', done); }) it('should override charset in Content-Type', function(done){ var app = express(); app.use(function(req, res){ res.set('Content-Type', 'text/plain; charset=iso-8859-1').send('hey'); }); request(app) .get('/') .expect('Content-Type', 'text/plain; charset=utf-8') .expect(200, 'hey', done); }) it('should keep charset in Content-Type for Buffers', function(done){ var app = express(); app.use(function(req, res){ res.set('Content-Type', 'text/plain; charset=iso-8859-1').send(new Buffer('hi')); }); request(app) .get('/') .expect('Content-Type', 'text/plain; charset=iso-8859-1') .expect(200, 'hi', done); }) }) describe('.send(Buffer)', function(){ it('should send as octet-stream', function(done){ var app = express(); app.use(function(req, res){ res.send(new Buffer('hello')); }); request(app) .get('/') .end(function(err, res){ res.headers.should.have.property('content-type', 'application/octet-stream'); res.text.should.equal('hello'); res.statusCode.should.equal(200); done(); }) }) it('should set ETag', function (done) { var app = express(); app.use(function (req, res) { var str = Array(1000).join('-'); res.send(new Buffer(str)); }); request(app) .get('/') .expect('ETag', 'W/"3e7-8084ccd1"') .expect(200, done); }) it('should not override Content-Type', function(done){ var app = express(); app.use(function(req, res){ res.set('Content-Type', 'text/plain').send(new Buffer('hey')); }); request(app) .get('/') .end(function(err, res){ res.headers.should.have.property('content-type', 'text/plain; charset=utf-8'); res.text.should.equal('hey'); res.statusCode.should.equal(200); done(); }) }) }) describe('.send(Object)', function(){ it('should send as application/json', function(done){ var app = express(); app.use(function(req, res){ res.send({ name: 'tobi' }); }); request(app) .get('/') .expect('Content-Type', 'application/json; charset=utf-8') .expect(200, '{"name":"tobi"}', done) }) }) describe('when the request method is HEAD', function(){ it('should ignore the body', function(done){ var app = express(); app.use(function(req, res){ res.send('yay'); }); request(app) .head('/') .expect('', done); }) }) describe('when .statusCode is 204', function(){ it('should strip Content-* fields, Transfer-Encoding field, and body', function(done){ var app = express(); app.use(function(req, res){ res.status(204).set('Transfer-Encoding', 'chunked').send('foo'); }); request(app) .get('/') .end(function(err, res){ res.headers.should.not.have.property('content-type'); res.headers.should.not.have.property('content-length'); res.headers.should.not.have.property('transfer-encoding'); res.text.should.equal(''); done(); }) }) }) describe('when .statusCode is 304', function(){ it('should strip Content-* fields, Transfer-Encoding field, and body', function(done){ var app = express(); app.use(function(req, res){ res.status(304).set('Transfer-Encoding', 'chunked').send('foo'); }); request(app) .get('/') .end(function(err, res){ res.headers.should.not.have.property('content-type'); res.headers.should.not.have.property('content-length'); res.headers.should.not.have.property('transfer-encoding'); res.text.should.equal(''); done(); }) }) }) it('should always check regardless of length', function(done){ var app = express(); var etag = '"asdf"'; app.use(function(req, res, next){ res.set('ETag', etag); res.send('hey'); }); request(app) .get('/') .set('If-None-Match', etag) .expect(304, done); }) it('should respond with 304 Not Modified when fresh', function(done){ var app = express(); var etag = '"asdf"'; app.use(function(req, res){ var str = Array(1000).join('-'); res.set('ETag', etag); res.send(str); }); request(app) .get('/') .set('If-None-Match', etag) .expect(304, done); }) it('should not perform freshness check unless 2xx or 304', function(done){ var app = express(); var etag = '"asdf"'; app.use(function(req, res, next){ res.status(500); res.set('ETag', etag); res.send('hey'); }); request(app) .get('/') .set('If-None-Match', etag) .expect('hey') .expect(500, done); }) it('should not support jsonp callbacks', function(done){ var app = express(); app.use(function(req, res){ res.send({ foo: 'bar' }); }); request(app) .get('/?callback=foo') .expect('{"foo":"bar"}', done); }) describe('"etag" setting', function () { describe('when enabled', function () { it('should send ETag', function (done) { var app = express(); app.use(function (req, res) { res.send('kajdslfkasdf'); }); app.enable('etag'); request(app) .get('/') .expect('ETag', 'W/"c-5aee35d8"') .expect(200, done); }); methods.forEach(function (method) { if (method === 'connect') return; it('should send ETag in response to ' + method.toUpperCase() + ' request', function (done) { var app = express(); app[method]('/', function (req, res) { res.send('kajdslfkasdf'); }); request(app) [method]('/') .expect('ETag', 'W/"c-5aee35d8"') .expect(200, done); }) }); it('should send ETag for empty string response', function (done) { var app = express(); app.use(function (req, res) { res.send(''); }); app.enable('etag'); request(app) .get('/') .expect('ETag', 'W/"0-0"') .expect(200, done); }) it('should send ETag for long response', function (done) { var app = express(); app.use(function (req, res) { var str = Array(1000).join('-'); res.send(str); }); app.enable('etag'); request(app) .get('/') .expect('ETag', 'W/"3e7-8084ccd1"') .expect(200, done); }); it('should not override ETag when manually set', function (done) { var app = express(); app.use(function (req, res) { res.set('etag', '"asdf"'); res.send(200); }); app.enable('etag'); request(app) .get('/') .expect('ETag', '"asdf"') .expect(200, done); }); it('should not send ETag for res.send()', function (done) { var app = express(); app.use(function (req, res) { res.send(); }); app.enable('etag'); request(app) .get('/') .expect(shouldNotHaveHeader('ETag')) .expect(200, done); }) }); describe('when disabled', function () { it('should send no ETag', function (done) { var app = express(); app.use(function (req, res) { var str = Array(1000).join('-'); res.send(str); }); app.disable('etag'); request(app) .get('/') .expect(shouldNotHaveHeader('ETag')) .expect(200, done); }); it('should send ETag when manually set', function (done) { var app = express(); app.disable('etag'); app.use(function (req, res) { res.set('etag', '"asdf"'); res.send(200); }); request(app) .get('/') .expect('ETag', '"asdf"') .expect(200, done); }); }); describe('when "strong"', function () { it('should send strong ETag', function (done) { var app = express(); app.set('etag', 'strong'); app.use(function (req, res) { res.send('hello, world!'); }); request(app) .get('/') .expect('ETag', '"Otu60XkfuuPskIiUxJY4cA=="') .expect(200, done); }) }) describe('when "weak"', function () { it('should send weak ETag', function (done) { var app = express(); app.set('etag', 'weak'); app.use(function (req, res) { res.send('hello, world!'); }); request(app) .get('/') .expect('ETag', 'W/"d-58988d13"') .expect(200, done) }) }) describe('when a function', function () { it('should send custom ETag', function (done) { var app = express(); app.set('etag', function (body, encoding) { var chunk = !Buffer.isBuffer(body) ? new Buffer(body, encoding) : body; chunk.toString().should.equal('hello, world!'); return '"custom"'; }); app.use(function (req, res) { res.send('hello, world!'); }); request(app) .get('/') .expect('ETag', '"custom"') .expect(200, done); }) it('should not send falsy ETag', function (done) { var app = express(); app.set('etag', function (body, encoding) { return undefined; }); app.use(function (req, res) { res.send('hello, world!'); }); request(app) .get('/') .expect(shouldNotHaveHeader('ETag')) .expect(200, done); }) }) }) }) function shouldNotHaveHeader(header) { return function (res) { assert.ok(!(header.toLowerCase() in res.headers), 'should not have header ' + header) } }
/* Highcharts JS v7.1.1 (2019-04-09) Sankey diagram module (c) 2010-2019 Torstein Honsi License: www.highcharts.com/license */ (function(d){"object"===typeof module&&module.exports?(d["default"]=d,module.exports=d):"function"===typeof define&&define.amd?define("highcharts/modules/sankey",["highcharts"],function(n){d(n);d.Highcharts=n;return d}):d("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(d){function n(e,d,t,h){e.hasOwnProperty(d)||(e[d]=h.apply(null,t))}d=d?d._modules:{};n(d,"mixins/nodes.js",[d["parts/Globals.js"]],function(e){var d=e.pick,t=e.defined,h=e.Point;e.NodesMixin={createNode:function(k){function h(b, c){return e.find(b,function(b){return b.id===c})}var a=h(this.nodes,k),q=this.pointClass,b;a||(b=this.options.nodes&&h(this.options.nodes,k),a=(new q).init(this,e.extend({className:"highcharts-node",isNode:!0,id:k,y:1},b)),a.linksTo=[],a.linksFrom=[],a.formatPrefix="node",a.name=a.name||a.options.id,a.mass=d(a.options.mass,a.options.marker&&a.options.marker.radius,this.options.marker&&this.options.marker.radius,4),a.getSum=function(){var b=0,c=0;a.linksTo.forEach(function(c){b+=c.weight});a.linksFrom.forEach(function(b){c+= b.weight});return Math.max(b,c)},a.offset=function(b,c){for(var g=0,f=0;f<a[c].length;f++){if(a[c][f]===b)return g;g+=a[c][f].weight}},a.hasShape=function(){var b=0;a.linksTo.forEach(function(c){c.outgoing&&b++});return!a.linksTo.length||b!==a.linksTo.length},this.nodes.push(a));return a},generatePoints:function(){var k={},h=this.chart;e.Series.prototype.generatePoints.call(this);this.nodes||(this.nodes=[]);this.colorCounter=0;this.nodes.forEach(function(a){a.linksFrom.length=0;a.linksTo.length=0; a.level=void 0});this.points.forEach(function(a){t(a.from)&&(k[a.from]||(k[a.from]=this.createNode(a.from)),k[a.from].linksFrom.push(a),a.fromNode=k[a.from],h.styledMode?a.colorIndex=d(a.options.colorIndex,k[a.from].colorIndex):a.color=a.options.color||k[a.from].color);t(a.to)&&(k[a.to]||(k[a.to]=this.createNode(a.to)),k[a.to].linksTo.push(a),a.toNode=k[a.to]);a.name=a.name||a.id},this);this.nodeLookup=k},setData:function(){this.nodes&&(this.nodes.forEach(function(e){e.destroy()}),this.nodes.length= 0);e.Series.prototype.setData.apply(this,arguments)},destroy:function(){this.data=[].concat(this.points||[],this.nodes);return e.Series.prototype.destroy.apply(this,arguments)},setNodeState:function(){var e=arguments;(this.isNode?this.linksTo.concat(this.linksFrom):[this.fromNode,this.toNode]).forEach(function(d){h.prototype.setState.apply(d,e);d.isNode||(d.fromNode.graphic&&h.prototype.setState.apply(d.fromNode,e),d.toNode.graphic&&h.prototype.setState.apply(d.toNode,e))});h.prototype.setState.apply(this, e)}}});n(d,"mixins/tree-series.js",[d["parts/Globals.js"]],function(e){var d=e.extend,t=e.isArray,h=e.isObject,k=e.isNumber,n=e.merge,a=e.pick;return{getColor:function(d,b){var g=b.index,c=b.mapOptionsToLevel,p=b.parentColor,f=b.parentColorIndex,u=b.series,m=b.colors,l=b.siblings,v=u.points,h=u.chart.options.chart,k,q,r,n;if(d){v=v[d.i];d=c[d.level]||{};if(c=v&&d.colorByPoint)q=v.index%(m?m.length:h.colorCount),k=m&&m[q];if(!u.chart.styledMode){m=v&&v.options.color;h=d&&d.color;if(r=p)r=(r=d&&d.colorVariation)&& "brightness"===r.key?e.color(p).brighten(g/l*r.to).get():p;r=a(m,h,k,r,u.color)}n=a(v&&v.options.colorIndex,d&&d.colorIndex,q,f,b.colorIndex)}return{color:r,colorIndex:n}},getLevelOptions:function(a){var b=null,g,c,p,f;if(h(a))for(b={},p=k(a.from)?a.from:1,f=a.levels,c={},g=h(a.defaults)?a.defaults:{},t(f)&&(c=f.reduce(function(b,c){var a,f;h(c)&&k(c.level)&&(f=n({},c),a="boolean"===typeof f.levelIsConstant?f.levelIsConstant:g.levelIsConstant,delete f.levelIsConstant,delete f.level,c=c.level+(a?0: p-1),h(b[c])?d(b[c],f):b[c]=f);return b},{})),f=k(a.to)?a.to:1,a=0;a<=f;a++)b[a]=n({},g,h(c[a])?c[a]:{});return b},setTreeValues:function b(g,c){var p=c.before,f=c.idRoot,u=c.mapIdToNode[f],m=c.points[g.i],l=m&&m.options||{},e=0,h=[];d(g,{levelDynamic:g.level-(("boolean"===typeof c.levelIsConstant?c.levelIsConstant:1)?0:u.level),name:a(m&&m.name,""),visible:f===g.id||("boolean"===typeof c.visible?c.visible:!1)});"function"===typeof p&&(g=p(g,c));g.children.forEach(function(a,f){var p=d({},c);d(p, {index:f,siblings:g.children.length,visible:g.visible});a=b(a,p);h.push(a);a.visible&&(e+=a.val)});g.visible=0<e||g.visible;p=a(l.value,e);d(g,{children:h,childrenTotal:e,isLeaf:g.visible&&!e,val:p});return g},updateRootId:function(b){var g;h(b)&&(g=h(b.options)?b.options:{},g=a(b.rootNode,g.rootId,""),h(b.userOptions)&&(b.userOptions.rootId=g),b.rootNode=g);return g}}});n(d,"modules/sankey.src.js",[d["parts/Globals.js"],d["mixins/tree-series.js"]],function(e,d){var n=d.getLevelOptions,h=e.defined, k=e.isObject,I=e.merge;d=e.seriesType;var a=e.pick,q=e.Point;d("sankey","column",{borderWidth:0,colorByPoint:!0,curveFactor:.33,dataLabels:{enabled:!0,backgroundColor:"none",crop:!1,nodeFormat:void 0,nodeFormatter:function(){return this.point.name},format:void 0,formatter:function(){},inside:!0},inactiveOtherPoints:!0,linkOpacity:.5,nodeWidth:20,nodePadding:10,showInLegend:!1,states:{hover:{linkOpacity:1},inactive:{linkOpacity:.1,opacity:.1,animation:{duration:50}}},tooltip:{followPointer:!0,headerFormat:'\x3cspan style\x3d"font-size: 10px"\x3e{series.name}\x3c/span\x3e\x3cbr/\x3e', pointFormat:"{point.fromNode.name} \u2192 {point.toNode.name}: \x3cb\x3e{point.weight}\x3c/b\x3e\x3cbr/\x3e",nodeFormat:"{point.name}: \x3cb\x3e{point.sum}\x3c/b\x3e\x3cbr/\x3e"}},{isCartesian:!1,invertable:!0,forceDL:!0,orderNodes:!0,createNode:e.NodesMixin.createNode,setData:e.NodesMixin.setData,destroy:e.NodesMixin.destroy,getNodePadding:function(){return this.options.nodePadding},createNodeColumn:function(){var b=this.chart,a=[],c=this.getNodePadding();a.sum=function(){return this.reduce(function(b, c){return b+c.getSum()},0)};a.offset=function(b,f){for(var g=0,d,p=0;p<a.length;p++){d=a[p].getSum()*f+c;if(a[p]===b)return{relativeTop:g+e.relativeLength(b.options.offset||0,d)};g+=d}};a.top=function(a){var f=this.reduce(function(b,f){0<b&&(b+=c);return b+=f.getSum()*a},0);return(b.plotSizeY-f)/2};return a},createNodeColumns:function(){var b=[];this.nodes.forEach(function(c){var a=-1,f,g,d;if(!e.defined(c.options.column))if(0===c.linksTo.length)c.column=0;else{for(g=0;g<c.linksTo.length;g++)d=c.linksTo[0], d.fromNode.column>a&&(f=d.fromNode,a=f.column);c.column=a+1;"hanging"===f.options.layout&&(c.hangsFrom=f,c.column+=f.linksFrom.findIndex(function(b){return b.toNode===c}))}b[c.column]||(b[c.column]=this.createNodeColumn());b[c.column].push(c)},this);for(var a=0;a<b.length;a++)void 0===b[a]&&(b[a]=this.createNodeColumn());return b},hasData:function(){return!!this.processedXData.length},pointAttribs:function(b,g){var c=this.mapOptionsToLevel[(b.isNode?b.level:b.fromNode.level)||0],d=b.options,f=c.states[g]|| {};g=["colorByPoint","borderColor","borderWidth","linkOpacity"].reduce(function(b,g){b[g]=a(f[g],d[g],c[g]);return b},{});var u=a(f.color,d.color,g.colorByPoint?b.color:c.color);return b.isNode?{fill:u,stroke:g.borderColor,"stroke-width":g.borderWidth}:{fill:e.color(u).setOpacity(g.linkOpacity).get()}},generatePoints:function(){function b(a,c){void 0===a.level&&(a.level=c,a.linksFrom.forEach(function(a){b(a.toNode,c+1)}))}e.NodesMixin.generatePoints.apply(this,arguments);this.orderNodes&&(this.nodes.filter(function(b){return 0=== b.linksTo.length}).forEach(function(a){b(a,0)}),e.stableSort(this.nodes,function(b,a){return b.level-a.level}))},translateNode:function(b,g){var c=this.translationFactor,d=this.chart,f=this.options,e=b.getSum(),m=Math.round(e*c),l=Math.round(f.borderWidth)%2/2,h=g.offset(b,c);g=Math.floor(a(h.absoluteTop,g.top(c)+h.relativeTop))+l;l=Math.floor(this.colDistance*b.column+f.borderWidth/2)+l;l=d.inverted?d.plotSizeX-l:l;c=Math.round(this.nodeWidth);b.sum=e;b.shapeType="rect";b.nodeX=l;b.nodeY=g;b.shapeArgs= d.inverted?{x:l-c,y:d.plotSizeY-g-m,width:b.options.height||f.height||c,height:b.options.width||f.width||m}:{x:l,y:g,width:b.options.width||f.width||c,height:b.options.height||f.height||m};b.shapeArgs.display=b.hasShape()?"":"none";d=this.mapOptionsToLevel[b.level];f=b.options;f=k(f)?f.dataLabels:{};d=k(d)?d.dataLabels:{};d=I({style:{}},d,f);b.dlOptions=d;b.plotY=1},translateLink:function(b){var a=b.fromNode,c=b.toNode,d=this.chart,f=this.translationFactor,e=b.weight*f,m=this.options,l=a.offset(b, "linksFrom")*f,h=(d.inverted?-this.colDistance:this.colDistance)*m.curveFactor,l=a.nodeY+l,m=a.nodeX,f=this.nodeColumns[c.column].top(f)+c.offset(b,"linksTo")*f+this.nodeColumns[c.column].offset(c,f).relativeTop,k=this.nodeWidth,c=c.column*this.colDistance,n=b.outgoing,q=c>m;d.inverted&&(l=d.plotSizeY-l,f=d.plotSizeY-f,c=d.plotSizeX-c,k=-k,e=-e,q=m>c);b.shapeType="path";b.linkBase=[l,l+e,f,f+e];if(q)b.shapeArgs={d:["M",m+k,l,"C",m+k+h,l,c-h,f,c,f,"L",c+(n?k:0),f+e/2,"L",c,f+e,"C",c-h,f+e,m+k+h,l+ e,m+k,l+e,"z"]};else{var h=c-20-e,n=c-20,q=c,r=m+k,x=r+20,t=x+e,D=l,y=l+e,B=y+20,d=B+(d.plotHeight-l-e),w=d+20,A=w+e,C=f,z=C+e,E=z+20,F=w+.7*e,G=q-.7*e,H=r+.7*e;b.shapeArgs={d:["M",r,D,"C",H,D,t,y-.7*e,t,B,"L",t,d,"C",t,F,H,A,r,A,"L",q,A,"C",G,A,h,F,h,d,"L",h,E,"C",h,z-.7*e,G,C,q,C,"L",q,z,"C",n,z,n,z,n,E,"L",n,d,"C",n,w,n,w,q,w,"L",r,w,"C",x,w,x,w,x,d,"L",x,B,"C",x,y,x,y,r,y,"z"]}}b.dlBox={x:m+(c-m+k)/2,y:l+(f-l)/2,height:e,width:0};b.y=b.plotY=1;b.color||(b.color=a.color)},translate:function(){this.processedXData|| this.processData();this.generatePoints();this.nodeColumns=this.createNodeColumns();this.nodeWidth=e.relativeLength(this.options.nodeWidth,this.chart.plotSizeX);var b=this,a=this.chart,c=this.options,d=this.nodeWidth,f=this.nodeColumns,h=this.getNodePadding();this.translationFactor=f.reduce(function(b,d){return Math.min(b,(a.plotSizeY-c.borderWidth-(d.length-1)*h)/d.sum())},Infinity);this.colDistance=(a.plotSizeX-d-c.borderWidth)/(f.length-1);b.mapOptionsToLevel=n({from:1,levels:c.levels,to:f.length- 1,defaults:{borderColor:c.borderColor,borderRadius:c.borderRadius,borderWidth:c.borderWidth,color:b.color,colorByPoint:c.colorByPoint,levelIsConstant:!0,linkColor:c.linkColor,linkLineWidth:c.linkLineWidth,linkOpacity:c.linkOpacity,states:c.states}});f.forEach(function(a){a.forEach(function(c){b.translateNode(c,a)})},this);this.nodes.forEach(function(a){a.linksFrom.forEach(function(a){b.translateLink(a);a.allowShadow=!1})})},render:function(){var a=this.points;this.points=this.points.concat(this.nodes|| []);e.seriesTypes.column.prototype.render.call(this);this.points=a},animate:e.Series.prototype.animate},{applyOptions:function(a,d){q.prototype.applyOptions.call(this,a,d);h(this.options.level)&&(this.options.column=this.column=this.options.level);return this},setState:e.NodesMixin.setNodeState,getClassName:function(){return(this.isNode?"highcharts-node ":"highcharts-link ")+q.prototype.getClassName.call(this)},isValid:function(){return this.isNode||"number"===typeof this.weight}})});n(d,"masters/modules/sankey.src.js", [],function(){})}); //# sourceMappingURL=sankey.js.map
import React from 'react'; import DatePicker from 'material-ui/DatePicker'; export default class DatePickerExampleControlled extends React.Component { constructor(props) { super(props); this.state = { controlledDate: null, }; } handleChange = (event, date) => { this.setState({ controlledDate: date, }); }; render() { return ( <DatePicker hintText="Controlled Date Input" value={this.state.controlledDate} onChange={this.handleChange} /> ); } }
/*! * jQuery JavaScript Library v2.0.3 -sizzle,-wrap,-css,-event-alias,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-offset,-dimensions * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-07T17:15Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Support: IE9 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "2.0.3 -sizzle,-wrap,-css,-event-alias,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-offset,-dimensions", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler and self cleanup method completed = function() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } // Support: Safari <= 5.1 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Support: Firefox <20 // The try/catch suppresses exceptions thrown when attempting to access // the "constructor" property of certain host objects, ie. |window.location| // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 try { if ( obj.constructor && !core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } } catch ( e ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: JSON.parse, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, trim: function( text ) { return text == null ? "" : core_trim.call( text ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : core_indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: Date.now, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /* * Optional (non-Sizzle) selector module for custom builds. * * Note that this DOES NOT SUPPORT many documented jQuery * features in exchange for its smaller size: * * Attribute not equal selector * Positional selectors (:first; :eq(n); :odd; etc.) * Type selectors (:input; :checkbox; :button; etc.) * State-based selectors (:animated; :visible; :hidden; etc.) * :has(selector) * :not(complex selector) * custom selectors via Sizzle extensions * Leading combinators (e.g., $collection.find("> *")) * Reliable functionality on XML fragments * Requiring all parts of a selector to match elements under context * (e.g., $div.find("div > *") now matches children of $div) * Matching against non-elements * Reliable sorting of disconnected nodes * querySelectorAll bug fixes (e.g., unreliable :focus on WebKit) * * If any of these are unacceptable tradeoffs, either use Sizzle or * customize this stub for the project's specific needs. */ var selector_hasDuplicate, matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector, selector_sortOrder = function( a, b ) { // Flag for duplicate removal if ( a === b ) { selector_hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 ) { // Choose the first element that is related to our document if ( a === document || jQuery.contains(document, a) ) { return -1; } if ( b === document || jQuery.contains(document, b) ) { return 1; } // Maintain original order return 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; }; jQuery.extend({ find: function( selector, context, results, seed ) { var elem, nodeType, i = 0; results = results || []; context = context || document; // Same basic safeguard as Sizzle if ( !selector || typeof selector !== "string" ) { return results; } // Early return if context is not an element or document if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( seed ) { while ( (elem = seed[i++]) ) { if ( jQuery.find.matchesSelector(elem, selector) ) { results.push( elem ); } } } else { jQuery.merge( results, context.querySelectorAll(selector) ); } return results; }, unique: function( results ) { var elem, duplicates = [], i = 0, j = 0; selector_hasDuplicate = false; results.sort( selector_sortOrder ); if ( selector_hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }, text: function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += jQuery.text( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements return elem.textContent; } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }, contains: function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && adown.contains(bup) ); }, isXMLDoc: function( elem ) { return (elem.ownerDocument || elem).documentElement.nodeName !== "HTML"; }, expr: { attrHandle: {}, match: { bool: /^(?:checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped)$/i, needsContext: /^[\x20\t\r\n\f]*[>+~]/ } } }); jQuery.extend( jQuery.find, { matches: function( expr, elements ) { return jQuery.find( expr, null, null, elements ); }, matchesSelector: function( elem, expr ) { return matches.call( elem, expr ); }, attr: function( elem, name ) { return elem.getAttribute( name ); } }); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var input = document.createElement("input"), fragment = document.createDocumentFragment(), div = document.createElement("div"), select = document.createElement("select"), opt = select.appendChild( document.createElement("option") ); // Finish early in limited environments if ( !input.type ) { return support; } input.type = "checkbox"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // Will be defined later support.reliableMarginRight = true; support.boxSizingReliable = true; support.pixelPosition = false; // Make sure checked status is properly cloned // Support: IE9, IE10 input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement("input"); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment.appendChild( input ); // Support: Safari 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: Firefox, Chrome, Safari // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) support.focusinBubbles = "onfocusin" in window; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box", body = document.getElementsByTagName("body")[ 0 ]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; // Check box-sizing and margin behavior. body.appendChild( container ).appendChild( div ); div.innerHTML = ""; // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } body.removeChild( container ); }); return support; })( {} ); /* Implementation Summary 1. Enforce API surface and semantic compatibility with 1.9.x branch 2. Improve the module's maintainability by reducing the storage paths to a single mechanism. 3. Use the same single mechanism to support "private" and "user" data. 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) 5. Avoid exposing implementation details on user objects (eg. expando properties) 6. Provide a clear path for implementation upgrade to WeakMap in 2014 */ var data_user, data_priv, rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType ? owner.nodeType === 1 || owner.nodeType === 9 : true; }; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( core_rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; // These may be used throughout the jQuery core codebase data_user = new Data(); data_priv = new Data(); jQuery.extend({ acceptData: Data.accepts, hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, elem = this[ 0 ], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return jQuery.access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? JSON.parse( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE6-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ // Temporarily disable this handler to check existence (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; // Restore handler jQuery.expr.attrHandle[ name ] = fn; return ret; }; }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return core_indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return core_indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because core_push.apply(_, arraylike) throws core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !jQuery.support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, i = 0, l = elems.length, fragment = context.createDocumentFragment(), nodes = []; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, events, type, key, j, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( Data.accepts( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { events = Object.keys( data.events || {} ); if ( events.length ) { for ( j = 0; (type = events[j]) !== undefined; j++ ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var l = elems.length, i = 0; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } // If there is a window object, that at least has a document property, // define jQuery and $ identifiers if ( typeof window === "object" && typeof window.document === "object" ) { window.jQuery = window.$ = jQuery; } })( window );
/** * @license Highcharts JS v7.0.1 (2018-12-19) * * Indicator series type for Highstock * * (c) 2010-2018 Kacper Madej * * 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(typeof Highcharts !== 'undefined' ? Highcharts : undefined); } }(function (Highcharts) { (function (H) { /* * * * (c) 2010-2018 Kacper Madej * * License: www.highcharts.com/license * * */ var seriesType = H.seriesType, isArray = H.isArray; // Utils: function populateAverage(xVal, yVal, i, period, index) { /* Calculated as: (Closing Price [today] - Closing Price [n days ago]) / Closing Price [n days ago] * 100 Return y as null when avoiding division by zero */ var nDaysAgoY, rocY; if (index < 0) { // y data given as an array of values nDaysAgoY = yVal[i - period]; rocY = nDaysAgoY ? (yVal[i] - nDaysAgoY) / nDaysAgoY * 100 : null; } else { // y data given as an array of arrays and the index should be used nDaysAgoY = yVal[i - period][index]; rocY = nDaysAgoY ? (yVal[i][index] - nDaysAgoY) / nDaysAgoY * 100 : null; } return [xVal[i], rocY]; } /** * The ROC series type. * * @private * @class * @name Highcharts.seriesTypes.roc * * @augments Highcharts.Series */ seriesType('roc', 'sma', /** * Rate of change indicator (ROC). The indicator value for each point * is defined as: * * `(C - Cn) / Cn * 100` * * where: `C` is the close value of the point of the same x in the * linked series and `Cn` is the close value of the point `n` periods * ago. `n` is set through [period](#plotOptions.roc.params.period). * * This series requires `linkedTo` option to be set. * * @sample stock/indicators/roc * Rate of change indicator * * @extends plotOptions.sma * @since 6.0.0 * @product highstock * @optionparent plotOptions.roc */ { params: { index: 3, period: 9 } }, /** * @lends Highcharts.Series# */ { nameBase: 'Rate of Change', getValues: function (series, params) { var period = params.period, xVal = series.xData, yVal = series.yData, yValLen = yVal ? yVal.length : 0, ROC = [], xData = [], yData = [], i, index = -1, ROCPoint; // Period is used as a number of time periods ago, so we need more // (at least 1 more) data than the period value if (xVal.length <= period) { return false; } // Switch index for OHLC / Candlestick / Arearange if (isArray(yVal[0])) { index = params.index; } // i = period <-- skip first N-points // Calculate value one-by-one for each period in visible data for (i = period; i < yValLen; i++) { ROCPoint = populateAverage(xVal, yVal, i, period, index); ROC.push(ROCPoint); xData.push(ROCPoint[0]); yData.push(ROCPoint[1]); } return { values: ROC, xData: xData, yData: yData }; } } ); /** * A `ROC` series. If the [type](#series.wma.type) option is not * specified, it is inherited from [chart.type](#chart.type). * * Rate of change indicator (ROC). The indicator value for each point * is defined as: * * `(C - Cn) / Cn * 100` * * where: `C` is the close value of the point of the same x in the * linked series and `Cn` is the close value of the point `n` periods * ago. `n` is set through [period](#series.roc.params.period). * * This series requires `linkedTo` option to be set. * * @extends series,plotOptions.roc * @since 6.0.0 * @product highstock * @excluding dataParser, dataURL * @apioption series.roc */ }(Highcharts)); return (function () { }()); }));
(function(r,k){"object"===typeof exports&&"object"===typeof module?module.exports=k():"function"===typeof define&&define.amd?define([],k):"object"===typeof exports?exports.RxPlayer=k():r.RxPlayer=k()})(this,function(){return function(r){function k(n){if(c[n])return c[n].exports;var p=c[n]={exports:{},id:n,loaded:!1};r[n].call(p.exports,p,p.exports,k);p.loaded=!0;return p.exports}var c={};k.m=r;k.c=c;k.p="";return k(0)}([function(r,k,c){r.exports=c(32)},function(r,k){function c(a,b){for(var f=-1,h= a?a.length:0;++f<h;)if(a[f]===b)return f;return-1}function n(a){return!!a&&"object"==typeof a&&"[object Date]"==h.call(a)||!1}function p(a){return!!a&&"function"==typeof a||!1}function g(a){return"number"==typeof a}function a(a){return!!a&&"object"==typeof a||!1}function b(a){return"string"==typeof a}function q(b){for(var f=arguments,h=1;h<f.length;h++){var d=f[h];if(a(d))for(var l=B(d),c=0,q=l.length;c<q;c++)b[l[c]]=d[l[c]]}return b}function t(a,b){for(var f=a?a.length:0,h=-1,d=Array(f);++h<f;)d[h]= b(a[h],h);return d}function d(a,b,f){for(var h=a?a.length:0,d=-1;++d<h;)f=b(f,a[d],d);return f}function v(a,b){for(var f=a?a.length:0,h=-1,d=[];++h<f;)b(a[h],h)&&d.push(a[h]);return d}function w(a,f){for(var h in a)if(f.hasOwnProperty(h)){var d=a[h],l=f[h];b(d)||g(d)||n(d)?a[h]=l:y(d)?(d.length=0,G.apply(d,l)):a[h]=w(d,l)}return a}var l=Object.prototype,h=l.toString,f=l.hasOwnProperty,y=Array.isArray,G=Array.prototype.push,B=Object.keys||function(a){var b=[],f;for(f in a)a.hasOwnProperty(f)&&b.push(a[f]); return b},l=function(){var a=0;return function(b){b||(b="");return""+b+a++}}();r.exports={chunk:function(a,b){for(var f=[],h=0,d=-1,l=a?a.length:0;++d<l;)f[h]?f[h].length===b?f[++h]=[a[d]]:f[h].push(a[d]):f[h]=[a[d]];return f},compact:function(a){return v(a,function(a){return null!=a})},contains:function(a,b){return-1<c(a,b)},cloneArray:function(a){for(var b=a?a.length:0,f=-1,h=Array(b);++f<b;)h[f]=a[f];return h},cloneObject:function(a){return q({},a)},defaults:function(a,b){for(var f in b)"undefined"== typeof a[f]&&(a[f]=b[f]);return a},each:function(a,b){for(var f=a?a.length:0,h=-1;++h<f;)b(a[h],h)},extend:q,values:function(a){for(var b=B(a),f=-1,h=b.length,d=Array(h);++f<h;)d[f]=a[b[f]];return d},filter:v,find:function(a,b){for(var f=-1,h=a?a.length:0;++f<h;)if(b(a[f],f))return a[f]},between:function(a,b,f){for(var h=-1,d=a?a.length:0;++h<d;)if(a[h][b]<=f&&a[h+1]&&f<a[h+1][b])return a[h]},findLast:function(a,b){for(var f=a?a.length:0;0<=--f;)if(b(a[f],f))return a[f]},flatten:function(a,b){for(var f= b?t(a,b):a,h=-1,d=f?f.length:0,l=[];++h<d;){var c=f[h];if(c&&"object"==typeof c&&"number"==typeof c.length){var q=-1,y=c.length,g=l.length;for(l.length+=y;++q<y;)l[g++]=c[q]}else l.push(c)}return l},groupBy:function(a,b){var f;f=p(b)?b:function(a){return a[b]};return d(a,function(a,b){var h=f(b);(y(a[h])?a[h]:a[h]=[]).push(b);return a},{})},identity:function(a){return a},indexOf:c,isArray:y,isDate:n,isFunction:p,isNumber:g,isObject:a,isString:b,isPromise:function(a){return!!a&&"function"==typeof a.then}, isObservable:function(a){return!!a&&"function"==typeof a.subscribe},keys:B,last:function(a){return a[a.length-1]},map:t,memoize:function(a,b){var h=function I(){var h=I.cache,d=b?b.apply(this,arguments):arguments[0];return f.call(h,d)?h[d]:h[d]=a.apply(this,arguments)};h.cache={};return h},noop:function(){},pad:function(a,b){a=a.toString();return a.length>=b?a:(Array(b+1).join("0")+a).slice(-b)},pick:function(a,b){return d(b,function(b,f){f in a&&(b[f]=a[f]);return b},{})},pluck:function(a,b){return t(a, function(a){return a[b]})},reduce:d,simpleMerge:w,sortedIndex:function(a,b,f){var h=0,d=a?a.length:h;for(b=f(b);h<d;){var l=h+d>>>1;f(a[l])<b?h=l+1:d=l}return h},sortedMerge:function(a,b,f){for(var h=0,d=0,l=0,c=a.length,q=b.length,y=[];h<c&&d<q;)a[h][f]<=b[d][f]?(y[l]=a[h],h++,l++):0<l&&b[d][f]<=y[l-1][f]?d++:(y[l]=b[d],d++,l++);if(h<c)for(f=h;f<c;f++)y[l]=a[f],l++;else for(f=d;f<q;f++)y[l]=b[f],l++;return y},tryCatch:function(a){try{return a()}catch(b){return b}},uniqueId:l}},function(r,k){function c(p){this.name= "AssertionError";this.message=p;Error.captureStackTrace&&Error.captureStackTrace(this,c)}function n(p,g){if(!p)throw new c(g);}c.prototype=Error();n.equal=function(c,g,a){return n(c===g,a)};n.iface=function(c,g,a){n(c,g+" should be an object");for(var b in a)n.equal(typeof c[b],a[b],g+" should have property "+b+" as a "+a[b])};r.exports=n},function(r,k,c){c(5);r.exports=c(12)},function(r,k){function c(){}var n={NONE:0,ERROR:1,WARNING:2,INFO:3,DEBUG:4},p=function(){};c.error=p;c.warn=p;c.info=p;c.debug= p;c.setLevel=function(g){"string"==typeof g&&(g=n[g]);c.error=g>=n.ERROR?console.error.bind(console):p;c.warn=g>=n.WARNING?console.warn.bind(console):p;c.info=g>=n.INFO?console.info.bind(console):p;c.debug=g>=n.DEBUG?console.log.bind(console):p};r.exports=c},function(r,k,c){k=c(12);var n=k.Observable,p=k.SingleAssignmentDisposable;k=k.config;var g=n.fromEvent,a=n.merge,b=n.timer,q=c(20).getBackedoffDelay,t=c(1),d=t.isArray,v=t.map,w=t.noop,l=c(21);k.useNativeEvents=!0;c=n.prototype;c.log=function(){return this}; c.each=function(a){return this.subscribe(a,w)};var h=function(a,b){return a===b};c.changes=function(a){return this.distinctUntilChanged(a,h)};c.customDebounce=function(a,b){var h=this;return n.create(function(d){var c=l(function(a){return d.onNext(a)},a,b),q=h.subscribe(c,function(a){return d.onError(a)},function(){return d.onCompleted()});return function(){c.dispose();q.dispose()}})};c.simpleTimeout=function(a){var b=1>=arguments.length||void 0===arguments[1]?"timeout":arguments[1],h=this;return n.create(function(d){var l= new p,c=setTimeout(function(){return d.onError(Error(b))},a);l.setDisposable(h.subscribe(function(a){clearTimeout(c);d.onNext(a)},function(a){return d.onError(a)},function(a){return d.onCompleted()}));return function(){clearTimeout(c);l.dispose()}})};r.exports={on:function(b,h){return d(h)?a(v(h,function(a){return g(b,a)})):g(b,h)},first:function(a){return a.take(1)},only:function(a){return n.never().startWith(a)},retryWithBackoff:function(a,h){var d=h.retryDelay,c=h.totalRetry,g=h.shouldRetry,t= h.resetDelay,v=0,n;n=0<t?l(function(){return v=0},t):w;return function L(){for(var h=0,l=arguments.length,y=Array(l);h<l;h++)y[h]=arguments[h];return a.apply(null,y)["catch"](function(a){if(g&&!g(a,v)||v++>=c)throw a;a=q(d,v);return b(a).flatMap(function(){n();return L.apply(null,y)})})}}}},function(r,k,c){r.exports=c(48).Promise},function(r,k,c){function n(a){for(var b=a.length,c=new Uint8Array(b),g=0;g<b;g++)c[g]=a.charCodeAt(g)&255;return c}function p(a,b){b||(b="");for(var c="",g=0;g<a.byteLength;g++)c+= (a[g]>>>4).toString(16),c+=(a[g]&15).toString(16),b.length&&(c+=b);return c}var g=c(2);r.exports={totalBytes:function(a){for(var b=0,c=0;c<a.length;c++)b+=a[c].byteLength;return b},strToBytes:n,bytesToStr:function(a){return String.fromCharCode.apply(null,a)},bytesToUTF16Str:function(a){for(var b="",c=a.length,g=0;g<c;g+=2)b+=String.fromCharCode(a[g]);return b},hexToBytes:function(a){for(var b=a.length,c=new Uint8Array(b/2),g=0,d=0;g<b;g+=2,d++)c[d]=parseInt(a.substr(g,2),16)&255;return c},bytesToHex:p, concat:function(){for(var a=arguments.length,b=-1,c=0,g;++b<a;)g=arguments[b],c+="number"===typeof g?g:g.length;for(var c=new Uint8Array(c),d=0,b=-1;++b<a;)g=arguments[b],"number"===typeof g?d+=g:0<g.length&&(c.set(g,d),d+=g.length);return c},be2toi:function(a,b){return(a[0+b]<<8)+(a[1+b]<<0)},be4toi:function(a,b){return 16777216*a[0+b]+65536*a[1+b]+256*a[2+b]+a[3+b]},be8toi:function(a,b){return 4294967296*(16777216*a[0+b]+65536*a[1+b]+256*a[2+b]+a[3+b])+16777216*a[4+b]+65536*a[5+b]+256*a[6+b]+a[7+ b]},le2toi:function(a,b){return(a[0+b]<<0)+(a[1+b]<<8)},le4toi:function(a,b){return a[0+b]+256*a[1+b]+65536*a[2+b]+16777216*a[3+b]},le8toi:function(a,b){return a[0+b]+256*a[1+b]+65536*a[2+b]+16777216*a[3+b]+(a[4+b]+256*a[5+b]+65536*a[6+b]+16777216*a[7+b]*4294967296)},itobe2:function(a){return new Uint8Array([a>>>8&255,a&255])},itobe4:function(a){return new Uint8Array([a>>>24&255,a>>>16&255,a>>>8&255,a&255])},itobe8:function(a){var b=a%4294967296;a=(a-b)/4294967296;return new Uint8Array([a>>>24&255, a>>>16&255,a>>>8&255,a&255,b>>>24&255,b>>>16&255,b>>>8&255,b&255])},itole2:function(a){return new Uint8Array([a&255,a>>>8&255])},itole4:function(a){return new Uint8Array([a&255,a>>>8&255,a>>>16&255,a>>>24&255])},itole8:function(a){var b=a%4294967296;a=(a-b)/4294967296;return new Uint8Array([a&255,a>>>8&255,a>>>16&255,a>>>24&255,b&255,b>>>8&255,b>>>16&255,b>>>24&255])},guidToUuid:function(a){g.equal(a.length,16,"UUID length should be 16");var b=n(a);a=b[0];var c=b[1],t=b[2],d=b[3],v=b[4],w=b[5],l= b[6],h=b[7],f=b.subarray(8,10),b=b.subarray(10,16),y=new Uint8Array(16);y[0]=d;y[1]=t;y[2]=c;y[3]=a;y[4]=w;y[5]=v;y[6]=h;y[7]=l;y.set(f,8);y.set(b,10);return p(y)},toBase64URL:function(a){return btoa(a).replace(/\=+$/,"")}}},function(r,k,c){function n(a){return a&&"function"==typeof a.then?a:w.resolve(a)}function p(a){return function(){var b;try{b=a.apply(this,arguments)}catch(h){return w.reject(h)}return n(b)}}function g(a,b){return v.flatten(a,function(a){return v.map(b||L,function(b){return b+ a})})}function a(a,b){return v.find(b,function(b){var h;h=document.createElement(a.tagName);b="on"+b;b in h?h=!0:(h.setAttribute(b,"return;"),h=v.isFunction(h[b]));return h})}function b(b,h){var f;b=g(b,h);return function(h){return h instanceof S?("undefined"==typeof f&&(f=a(h,b)||null),f?F(h,f):B()):K(h,b)}}function q(a,b){function h(){var a=0>=arguments.length||void 0===arguments[0]?{}:arguments[0];a.errorCode&&(a={systemCode:a.systemCode,code:a.errorCode.code});this.name="KeySessionError";this.mediaKeyError= a;this.message="MediaKeyError code:"+a.code+" and systemCode:"+a.systemCode}h.prototype=Error();return function(f,d){var c=v.isFunction(b)?b.call(this):this,l=X(c),g=U(c).map(function(a){throw new h(c.error||a);});try{return a.call(this,f,d),G(l,g).take(1).toPromise()}catch(y){return w.reject(y)}}}function t(a,b){if(b instanceof ca)return b._setVideo(a);if(a.setMediaKeys)return a.setMediaKeys(b);if(null!==b){if(a.WebkitSetMediaKeys)return a.WebkitSetMediaKeys(b);if(a.mozSetMediaKeys)return a.mozSetMediaKeys(b); if(a.msSetMediaKeys)return new w(function(h,f){1<=a.readyState?(a.msSetMediaKeys(b),h()):a.addEventListener("loadedmetatdata",function(){try{a.msSetMediaKeys(b)}catch(d){return f(d)}finally{a.removeEventListener("loadedmetatdata")}h()})});throw Error("compat: cannot find setMediaKeys method");}}function d(){return!!(x.fullscreenElement||x.mozFullScreenElement||x.webkitFullscreenElement||x.msFullscreenElement)}var v=c(1);c(4);var w=c(6),l=c(10);k=c(7);var h=k.bytesToStr,f=k.strToBytes,y=c(2);k=c(3).Observable; var G=k.merge,B=k.never,F=k.fromEvent,E=k.just,K=c(5).on,x=document,I=window,L=["","webkit","moz","ms"],S=I.HTMLElement;c=I.HTMLVideoElement;var Q=I.MediaSource||I.MozMediaSource||I.WebKitMediaSource||I.MSMediaSource,O=I.MediaKeys||I.MozMediaKeys||I.WebKitMediaKeys||I.MSMediaKeys;k="Microsoft Internet Explorer"==navigator.appName||"Netscape"==navigator.appName&&/Trident\//.test(navigator.userAgent);var ca=v.noop,M;navigator.requestMediaKeySystemAccess&&(M=function(a,b){return navigator.requestMediaKeySystemAccess(a, b)});k=b(k?["progress"]:["loadedmetadata"]);var Z=b(["sourceopen","webkitsourceopen"]),V=b(["encrypted","needkey"]),aa=b(["keymessage","message"]),X=b(["keyadded","ready"]),U=b(["keyerror","error"]),R=b(["keystatuseschange"]),V={onEncrypted:V,onKeyMessage:aa,onKeyStatusesChange:R,onKeyError:U};if(!M&&c.prototype.webkitGenerateKeyRequest){var da=function(a,b){var h=this;l.call(this);this._vid=a;this._key=b;this._con=G(aa(a),X(a),U(a)).subscribe(function(a){return h.trigger(a.type,a)})};da.prototype= v.extend({},l.prototype,{generateRequest:p(function(a,b){this._vid.webkitGenerateKeyRequest(this._key,b)}),update:q(function(a,b){if(0<=this._key.indexOf("clearkey")){var d=JSON.parse(h(a)),c=f(atob(d.keys[0].k)),d=f(atob(d.keys[0].kid));this._vid.webkitAddKey(this._key,c,d,b)}else this._vid.webkitAddKey(this._key,a,null,b)}),close:p(function(){this._con&&this._con.dispose();this._vid=this._con=null})});ca=function(a){this.ks_=a};ca.prototype={_setVideo:function(a){this._vid=a},createSession:function(){return new da(this._vid, this.ks_)}};var la=function(a){var b=x.querySelector("video")||x.createElement("video");return b&&b.canPlayType?!!b.canPlayType("video/mp4",a):!1};M=function(a,b){if(!la(a))return w.reject();for(var h=function(h){var f=b[h];h=f.initDataTypes;var c=f.sessionTypes,l=f.distinctiveIdentifier,g=f.persistentState;if(d=(d=(d=(d=(d=!0,!h||v.find(h,function(a){return"cenc"===a})))&&(!c||v.filter(c,function(a){return"temporary"===a}).length===c.length))&&"required"!==l)&&"required"!==g)return{v:w.resolve({createMediaKeys:function(){return w.resolve(new ca(a), f)}})}},f=0;f<b.length;f++){var d,c=h(f);if("object"===typeof c)return c.v}return w.reject()}}else if(O&&!M){var ta=function(a){l.call(this);this._mk=a};ta.prototype=v.extend(l.prototype,{generateRequest:p(function(a,b){var h=this;this._ss=this._mk.memCreateSession("video/mp4",b);this._con=G(aa(this._ss),X(this._ss),U(this._ss)).subscribe(function(a){return h.trigger(a.type,a)})}),update:q(function(a,b){y(this._ss);this._ss.update(a,b)},function(){return this._ss}),close:p(function(){this._ss&&(this._ss.close(), this._ss=null,this._con.dispose(),this._con=null)})});O.prototype.alwaysRenew=!0;O.prototype.memCreateSession=O.prototype.createSession;O.prototype.createSession=function(){return new ta(this)};M=function(a,b){if(!O.isTypeSupported(a))return w.reject();for(var h=function(h){var f=b[h];h=f.initDataTypes;var c=f.distinctiveIdentifier;if(d=(d=(d=!0,!h||v.find(h,function(a){return"cenc"===a})))&&"required"!==c)return{v:w.resolve({createMediaKeys:function(){return w.resolve(new ca(a),f)}})}},f=0;f<b.length;f++){var d, c=h(f);if("object"===typeof c)return c.v}return w.reject()}}O||(R=function(){throw Error("eme: MediaKeys is not available");},O={create:R,isTypeSupported:R});I.WebKitSourceBuffer&&!I.WebKitSourceBuffer.prototype.addEventListener&&(R=I.WebKitSourceBuffer.prototype,v.extend(R,l.prototype),R.__listeners=[],R.appendBuffer=function(a){if(this.updating)throw Error("SourceBuffer updating");this.trigger("updatestart");this.updating=!0;try{this.append(a)}catch(b){this.__emitUpdate("error",b);return}this.__emitUpdate("update")}, R.__emitUpdate=function(a,b){var h=this;setTimeout(function(){h.trigger(a,b);h.updating=!1;h.trigger("updateend")},0)});R=b(["fullscreenchange","FullscreenChange"],L.concat("MS"));r.exports={HTMLVideoElement_:c,MediaSource_:Q,isCodecSupported:function(a){return!!Q&&Q.isTypeSupported(a)},sourceOpen:function(a){return"open"==a.readyState?E():Z(a).take(1)},loadedMetadataEvent:k,requestMediaKeySystemAccess:M,setMediaKeys:function(a,b){return n(t(a,b))},emeEvents:V,isFullscreen:d,onFullscreenChange:R, requestFullscreen:function(a){if(!d()){if(a.requestFullscreen)return a.requestFullscreen();if(a.msRequestFullscreen)return a.msRequestFullscreen();if(a.mozRequestFullScreen)return a.mozRequestFullScreen();if(a.webkitRequestFullscreen)return a.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT)}},exitFullscreen:function(){if(d()){if(x.exitFullscreen)return x.exitFullscreen();if(x.msExitFullscreen)return x.msExitFullscreen();if(x.mozCancelFullScreen)return x.mozCancelFullScreen();if(x.webkitExitFullscreen)return x.webkitExitFullscreen()}}, videoSizeChange:function(){return K(I,"resize")},visibilityChange:function(){var a;null!=x.hidden?a="":null!=x.mozHidden?a="moz":null!=x.msHidden?a="ms":null!=x.webkitHidden&&(a="webkit");var b=a?a+"Hidden":"hidden";return K(x,a+"visibilitychange").map(function(){return x[b]})}}},function(r,k,c){function n(a){if(d.isArray(a))return a;for(var b=-1,f=a.length,c=Array(f);++b<f;)c[b]={start:a.start(b),end:a.end(b),bitrate:0};return c}function p(a,b){return a.start<=b&&b<a.end}function g(b,h){for(var f= 0;f<h.length;f++)if(a(b,h[f]))return h[f];return null}function a(a,b){return p(a,b.start)||p(a,b.end)||p(b,a.start)}function b(a,b){return p(a,b.start)&&p(a,b.end)}function q(a,b){return Math.abs(b.start-a.end)<w||Math.abs(b.end-a.start)<w}function t(a,b,f){var d=Math.min(a.start,b.start);a=Math.max(a.end,b.end);return{start:d,end:a,bitrate:f}}var d=c(1),v=c(2),w=1/60;k=function(){function d(a){if(!(this instanceof d))throw new TypeError("Cannot call a class as a function");this.ranges=a?n(a):[]; this.length=this.ranges.length}d.prototype.start=function(a){return this.ranges[a].start};d.prototype.end=function(a){return this.ranges[a].end};d.prototype.hasRange=function(a,b){for(var d=a+b,c=0;c<this.ranges.length;c++){var g=this.ranges[c],l=g.start,g=g.end;if(l-a<=w&&a-g<=w&&l-d<=w&&d-g<=w)return this.ranges[c]}return null};d.prototype.getRange=function(a){for(var b=0;b<this.ranges.length;b++)if(p(this.ranges[b],a))return this.ranges[b];return null};d.prototype.getGap=function(a){var b=this.getRange(a); return b?b.end-a:Infinity};d.prototype.getLoaded=function(a){var b=this.getRange(a);return b?a-b.start:0};d.prototype.getSize=function(a){return(a=this.getRange(a))?a.end-a.start:0};d.prototype.getNextRangeGap=function(a){for(var b=this.ranges,d=-1,c;++d<b.length;){var g=b[d].start;if(g>a){c=g;break}}return null!=c?c-a:Infinity};d.prototype.insert=function(d,f,c){var g=this.ranges;v(f<=c);if(f!=c){d={start:f,end:c,bitrate:d};for(f=0;f<g.length;f++){c=g[f];var l=a(d,c),n=q(d,c);if(l||n)if(d.bitrate=== c.bitrate)d=t(d,c,c.bitrate),g.splice(f--,1);else if(l)if(b(c,d))g.splice(++f,0,d),l=c.end,c.end=d.start,d={start:d.end,end:l,bitrate:c.bitrate};else if(b(d,c))g.splice(f--,1);else if(c.start<d.start)c.end=d.start;else{c.start=d.end;break}else break;else if(0===f){if(d.end<=g[0].start)break}else if(g[f-1].end<=d.start&&d.end<=c.start)break}g.splice(f,0,d);for(d=0;d<g.length;d++)f=g[d],f.start===f.end&&g.splice(d++,1);for(d=1;d<g.length;d++)f=g[d-1],c=g[d],f.bitrate===c.bitrate&&q(f,c)&&(f=t(f,c,c.bitrate), g.splice(--d,2,f))}this.length=this.ranges.length;return this.ranges};d.prototype.remove=function(a,b){this.intersect(new d([{start:0,end:a},{start:b,end:Infinity}]))};d.prototype.equals=function(a){var b;a:{b=this.ranges;a=a.ranges;for(var d=0;d<b.length;d++){var c=b[d],l=g(c,a);if(!l||l.start>c.start||l.end<c.end){b=!1;break a}}b=!0}return b};d.prototype.intersect=function(a){var b=this.ranges;a=a.ranges;for(var d=0;d<b.length;d++){var c=b[d],l=g(c,a);l?(l.start>c.start&&(c.start=l.start),l.end< c.end&&(c.end=l.end)):b.splice(d--,1)}this.length=this.ranges.length;return this.ranges};return d}();r.exports={bufferedToArray:n,BufferedRanges:k}},function(r,k,c){function n(){this.__listeners={}}var p=c(1),g=c(2);n.prototype.addEventListener=function(a,b){g("function"==typeof b,"eventemitter: second argument should be a function");this.__listeners[a]||(this.__listeners[a]=[]);this.__listeners[a].push(b)};n.prototype.removeEventListener=function(a,b){if(0===arguments.length)this.__listeners={}; else if(this.__listeners.hasOwnProperty(a))if(1===arguments.length)delete this.__listeners[a];else{var c=this.__listeners[a],g=c.indexOf(b);~g&&c.splice(g,1);c.length||delete this.__listeners[a]}};n.prototype.trigger=function(a,b){if(this.__listeners.hasOwnProperty(a)){var c=this.__listeners[a].slice();p.each(c,function(a){try{a(b)}catch(d){console.error(d,d.stack)}})}};n.prototype.on=n.prototype.addEventListener;n.prototype.off=n.prototype.removeEventListener;r.exports=n},function(r,k){var c=/^(?:[a-z]+:)?\/\//i, n=/\/[\.]{1,2}\//;r.exports={resolveURL:function(){var p=arguments.length;if(0===p)return"";for(var g="",a=0;a<p;a++){var b=arguments[a];"string"===typeof b&&""!==b&&(c.test(b)?g=b:("/"===b[0]&&(b=b.substr(1)),"/"===g[g.length-1]&&(g=g.substr(0,g.length-1)),g=g+"/"+b))}if(n.test(g)){p=[];g=g.split("/");a=0;for(b=g.length;a<b;a++)".."==g[a]?p.pop():"."!=g[a]&&p.push(g[a]);p=p.join("/")}else p=g;return p},parseBaseURL:function(c){var g=c.lastIndexOf("/");return 0<=g?c.substring(0,g+1):c}}},function(r, k,c){(function(n,p){function g(a){for(var e=a.length,m=Array(e),A=0;A<e;A++)m[A]=a[A];return m}function a(){try{return La.apply(this,arguments)}catch(a){return J.e=a,J}}function b(C){if(!Y(C))throw new TypeError("fn must be a function");La=C;return a}function q(a){throw a;}function t(a,e){for(var m=Array(a),A=0;A<a;A++)m[A]=e();return m}function d(a){this._s=a}function v(a){this._s=a;this._l=a.length;this._i=0}function w(a){this._a=a}function l(a){this._a=a;a=+a.length;if(isNaN(a))a=0;else if(0!== a&&"number"===typeof a&&u.isFinite(a)){var e;e=+a;e=0===e?e:isNaN(e)?e:0>e?-1:1;a=e*Math.floor(Math.abs(a));a=0>=a?0:a>cb?cb:a}this._l=a;this._i=0}function h(a){var e=a._es6shim_iterator_;if(!e&&"string"===typeof a)return a=new d(a),a._es6shim_iterator_();if(!e&&void 0!==a.length)return a=new w(a),a._es6shim_iterator_();if(!e)throw new TypeError("Object is not iterable");return a._es6shim_iterator_()}function f(a,e){this.observer=a;this.parent=e}function y(a,e){ea(a)||(a=ra);return new Ra(e,a)}function k(a, e){this.observer=a;this.parent=e}function B(a,e){this.observer=a;this.parent=e}function F(a,e){return new P(function(m){var A=new T,b=new oa;b.setDisposable(A);A.setDisposable(a.subscribe(new nb(m,b,e)));return b},a)}function E(){return!1}function K(){return[]}function x(){for(var a=arguments.length,e=Array(a),m=0;m<a;m++)e[m]=arguments[m];return e}function I(a){return function(e){return a.subscribe(e)}}function L(a,e){this.o=a;this.accumulator=e.accumulator;this.hasSeed=e.hasSeed;this.seed=e.seed; this.hasAccumulation=!1;this.accumulation=null;this.isStopped=this.hasValue=!1}function S(a,e){return function(m){var A=m;for(m=0;m<e;m++)if(A=A[a[m]],"undefined"===typeof A)return;return A}}function Q(a,e,m){return function(){for(var A=arguments.length,fa=Array(A),d=0;d<A;d++)fa[d]=arguments[d];if(Y(m)){fa=b(m).apply(e,fa);if(fa===J)return a.onError(fa.e);a.onNext(fa)}else if(1>=fa.length)a.onNext(fa[0]);else a.onNext(fa);a.onCompleted()}}function O(a,e,m){return function(){var A=arguments[0];if(A)return a.onError(A); for(var A=arguments.length,fa=[],d=1;d<A;d++)fa[d-1]=arguments[d];if(Y(m)){fa=b(m).apply(e,fa);if(fa===J)return a.onError(fa.e);a.onNext(fa)}else if(1>=fa.length)a.onNext(fa[0]);else a.onNext(fa);a.onCompleted()}}function ca(a,e,m){this._e=a;this._n=e;this._fn=m;this._e.addEventListener(this._n,this._fn,!1);this.isDisposed=!1}function M(a,e,m){var A=Object.prototype.toString.call(a);if("[object NodeList]"===A||"[object HTMLCollection]"===A){for(var A=new W,b=0,d=a.length;b<d;b++)A.add(M(a.item(b), e,m));return A}return new ca(a,e,m)}function Z(a,e){return function(){var m=arguments[0];Y(e)&&(m=e.apply(null,arguments));a.onNext(m)}}function V(a,e){return new P(function(m){return e.scheduleWithAbsolute(a,function(){m.onNext(0);m.onCompleted()})})}function aa(a,e,m){return new P(function(A){var b=a,d=Xa(e);return m.scheduleRecursiveWithAbsoluteAndState(0,b,function(a,e){if(0<d){var C=m.now();b+=d;b<=C&&(b=C+d)}A.onNext(a);e(a+1,b)})})}function X(a,e){return new P(function(m){return e.scheduleWithRelative(Xa(a), function(){m.onNext(0);m.onCompleted()})})}function U(a,e,m){return a===e?new P(function(a){return m.schedulePeriodicWithState(0,e,function(e){a.onNext(e);return e+1})}):db(function(){return aa(m.now()+a,e,m)})}function R(a,e,m){return new P(function(A){var b=!1,d=new oa,c=null,f=[],h=!1,g;g=a.materialize().timestamp(m).subscribe(function(a){"E"===a.value.kind?(f=[],f.push(a),c=a.value.exception,a=!h):(f.push({value:a.value,timestamp:a.timestamp+e}),a=!b,b=!0);if(a)if(null!==c)A.onError(c);else a= new T,d.setDisposable(a),a.setDisposable(m.scheduleRecursiveWithRelative(e,function(a){var e,C,d;if(null===c){h=!0;do e=null,0<f.length&&0>=f[0].timestamp-m.now()&&(e=f.shift().value),null!==e&&e.accept(A);while(null!==e);d=!1;C=0;0<f.length?(d=!0,C=Math.max(0,f[0].timestamp-m.now())):b=!1;e=c;h=!1;if(null!==e)A.onError(e);else d&&a(C)}}))});return new W(g,d)},a)}function da(a,e,m){return db(function(){return R(a,e-m.now(),m)})}function la(a,e){return new P(function(m){function A(){c&&(c=!1,m.onNext(d)); b&&m.onCompleted()}var b=!1,d,c=!1,f=new T;f.setDisposable(a.subscribe(function(a){c=!0;d=a},function(a){m.onError(a)},function(){b=!0;f.dispose()}));return new W(f,e.subscribe(A,function(a){m.onError(a)},A))},a)}function ta(a,e,m){return new P(function(A){function d(a,e){g[e]=a;c[e]=!0;if(f||(f=c.every(ua))){if(l)return A.onError(l);var C=b(m).apply(null,g);if(C===J)return A.onError(C.e);A.onNext(C)}h&&g[1]&&A.onCompleted()}var c=[!1,!1],f=!1,h=!1,g=Array(2),l;return new W(a.subscribe(function(a){d(a, 0)},function(a){if(g[1])A.onError(a);else l=a},function(){h=!0;g[1]&&A.onCompleted()}),e.subscribe(function(a){d(a,1)},function(a){A.onError(a)},function(){h=!0;d(!0,1)}))},a)}var u=n,D={internals:{},config:{Promise:c(6)},helpers:{}},na=D.helpers.noop=function(){},ua=D.helpers.identity=function(a){return a},Ea=D.helpers.defaultNow=Date.now,Wa=D.helpers.defaultComparer=function(a,e){return wa(a,e)},Qa=D.helpers.defaultSubComparer=function(a,e){return a>e?1:a<e?-1:0},Ka=D.helpers.defaultError=function(a){throw a; },ha=D.helpers.isPromise=function(a){return!!a&&"function"!==typeof a.subscribe&&"function"===typeof a.then},Y=D.helpers.isFunction=function(a){return"function"==typeof a||!1},J={e:{}},La;(D.EmptyError=function(){this.message="Sequence contains no elements.";this.name="EmptyError";Error.call(this)}).prototype=Error.prototype;var Ma=D.ObjectDisposedError=function(){this.message="Object has been disposed";this.name="ObjectDisposedError";Error.call(this)};Ma.prototype=Error.prototype;var ga=D.ArgumentOutOfRangeError= function(){this.message="Argument out of range";this.name="ArgumentOutOfRangeError";Error.call(this)};ga.prototype=Error.prototype;var ya=D.NotSupportedError=function(a){this.message=a||"This operation is not supported";this.name="NotSupportedError";Error.call(this)};ya.prototype=Error.prototype;var Ca=D.NotImplementedError=function(a){this.message=a||"This operation is not implemented";this.name="NotImplementedError";Error.call(this)};Ca.prototype=Error.prototype;var Fa=D.helpers.notImplemented= function(){throw new Ca;},va=D.helpers.notSupported=function(){throw new ya;},Ga=D.doneEnumerator={done:!0,value:void 0},Sa=D.helpers.isArrayLike=function(a){return a&&void 0!==a.length},sa=D.internals.bindCallback=function(a,e,m){return e?function(){return a.apply(e,arguments)}:a};D.internals.isObject=function(a){var e=typeof a;return a&&("function"==e||"object"==e)||!1};var wa=D.internals.isEqual=function(a,e){if(a===e)return!0;if(!a||!e||"object"!==typeof a||"object"!==typeof e)return!1;for(var m in a)if(a.hasOwnProperty(m)&& (!e.hasOwnProperty(m)||a[m]!==e[m]))return!1;for(m in e)if(e.hasOwnProperty(m)&&!a.hasOwnProperty(m))return!1;return!0},H=D.internals.inherits=function(a,e){function m(){this.constructor=a}m.prototype=e.prototype;a.prototype=new m},Ha=D.internals.addProperties=function(a){for(var e=1,m=arguments.length;e<m;e++){var A=arguments[e],b;for(b in A)a[b]=A[b]}},W=D.CompositeDisposable=function(){var a=[],e,m;if(Array.isArray(arguments[0]))a=arguments[0],m=a.length;else for(m=arguments.length,a=Array(m), e=0;e<m;e++)a[e]=arguments[e];for(e=0;e<m;e++)if(!ob(a[e]))throw new TypeError("Not a disposable");this.disposables=a;this.isDisposed=!1;this.length=a.length},Ya=W.prototype;Ya.add=function(a){this.isDisposed?a.dispose():(this.disposables.push(a),this.length++)};Ya.remove=function(a){var e=!1;if(!this.isDisposed){var m=this.disposables.indexOf(a);-1!==m&&(e=!0,this.disposables.splice(m,1),this.length--,a.dispose())}return e};Ya.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;for(var a= this.disposables.length,e=Array(a),m=0;m<a;m++)e[m]=this.disposables[m];this.disposables=[];for(m=this.length=0;m<a;m++)e[m].dispose()}};var Ia=D.Disposable=function(a){this.isDisposed=!1;this.action=a||na};Ia.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var pa=Ia.create=function(a){return new Ia(a)},ka=Ia.empty={dispose:na},ob=Ia.isDisposable=function(a){return a&&Y(a.dispose)},ia=Ia.checkDisposed=function(a){if(a.isDisposed)throw new Ma;},T=D.SingleAssignmentDisposable= function(){this.isDisposed=!1;this.current=null};T.prototype.getDisposable=function(){return this.current};T.prototype.setDisposable=function(a){if(this.current)throw Error("Disposable has already been assigned");var e=this.isDisposed;!e&&(this.current=a);e&&a&&a.dispose()};T.prototype.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var a=this.current;this.current=null}a&&a.dispose()};var oa=D.SerialDisposable=function(){this.isDisposed=!1;this.current=null};oa.prototype.getDisposable= function(){return this.current};oa.prototype.setDisposable=function(a){var e=this.isDisposed;if(!e){var m=this.current;this.current=a}m&&m.dispose();e&&a&&a.dispose()};oa.prototype.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var a=this.current;this.current=null}a&&a.dispose()};D.RefCountDisposable=function(){function a(e){this.disposable=e;this.disposable.count++;this.isInnerDisposed=!1}function e(a){this.underlyingDisposable=a;this.isPrimaryDisposed=this.isDisposed=!1;this.count=0} a.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))};e.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))};e.prototype.getDisposable=function(){return this.isDisposed? ka:new a(this)};return e}();var Na=D.internals.ScheduledItem=function(a,e,m,A,b){this.scheduler=a;this.state=e;this.action=m;this.dueTime=A;this.comparer=b||Qa;this.disposable=new T};Na.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())};Na.prototype.compareTo=function(a){return this.comparer(this.dueTime,a.dueTime)};Na.prototype.isCancelled=function(){return this.disposable.isDisposed};Na.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var qa= D.Scheduler=function(){function a(e,m,b,C){this.now=e;this._schedule=m;this._scheduleRelative=b;this._scheduleAbsolute=C}function e(a,e){e();return ka}a.isScheduler=function(e){return e instanceof a};var m=a.prototype;m.schedule=function(a){return this._schedule(a,e)};m.scheduleWithState=function(a,e){return this._schedule(a,e)};m.scheduleWithRelative=function(a,m){return this._scheduleRelative(m,a,e)};m.scheduleWithRelativeAndState=function(a,e,m){return this._scheduleRelative(a,e,m)};m.scheduleWithAbsolute= function(a,m){return this._scheduleAbsolute(m,a,e)};m.scheduleWithAbsoluteAndState=function(a,e,m){return this._scheduleAbsolute(a,e,m)};a.now=Ea;a.normalize=function(a){0>a&&(a=0);return a};return a}(),Xa=qa.normalize,ea=qa.isScheduler;(function(a){function e(a,e){function m(e){var b=!1,d=!1,c=a.scheduleWithState(e,function(a,e){b?C.remove(c):d=!0;A(e,m);return ka});d||(C.add(c),b=!0)}var b=e[0],A=e[1],C=new W;A(b,m);return C}function m(a,e,m){function b(e,A){var c=!1,fa=!1,f=a[m](e,A,function(a, e){c?d.remove(f):fa=!0;C(e,b);return ka});fa||(d.add(f),c=!0)}var A=e[0],C=e[1],d=new W;C(A,b);return d}function b(a,e){return m(a,e,"scheduleWithRelativeAndState")}function d(a,e){return m(a,e,"scheduleWithAbsoluteAndState")}function c(a,e){a(function(m){e(a,m)})}a.scheduleRecursive=function(a){return this.scheduleRecursiveWithState(a,c)};a.scheduleRecursiveWithState=function(a,m){return this.scheduleWithState([a,m],e)};a.scheduleRecursiveWithRelative=function(a,e){return this.scheduleRecursiveWithRelativeAndState(e, a,c)};a.scheduleRecursiveWithRelativeAndState=function(a,e,m){return this._scheduleRelative([a,m],e,b)};a.scheduleRecursiveWithAbsolute=function(a,e){return this.scheduleRecursiveWithAbsoluteAndState(e,a,c)};a.scheduleRecursiveWithAbsoluteAndState=function(a,e,m){return this._scheduleAbsolute([a,m],e,d)}})(qa.prototype);(function(a){qa.prototype.schedulePeriodic=function(a,m){return this.schedulePeriodicWithState(null,a,m)};qa.prototype.schedulePeriodicWithState=function(a,m,b){if("undefined"===typeof u.setInterval)throw new ya; m=Xa(m);var C=a,d=u.setInterval(function(){C=b(C)},m);return pa(function(){u.clearInterval(d)})}})(qa.prototype);var ma=qa.immediate=function(){return new qa(Ea,function(a,e){return e(this,a)},va,va)}(),ra=qa.currentThread=function(){function a(){for(;0<e.length;){var m=e.shift();!m.isCancelled()&&m.invoke()}}var e,m=new qa(Ea,function(m,d){var c=new Na(this,m,d,this.now());if(e)e.push(c);else{e=[c];var f=b(a)();e=null;if(f===J)return q(f.e)}return c.disposable},va,va);m.scheduleRequired=function(){return!e}; return m}();D.internals.SchedulePeriodicRecursive=function(){function a(e,b){b(0,this._period);try{this._state=this._action(this._state)}catch(C){throw this._cancel.dispose(),C;}}function e(a,e,b,C){this._scheduler=a;this._state=e;this._period=b;this._action=C}e.prototype.start=function(){var e=new T;this._cancel=e;e.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,a.bind(this)));return e};return e}();var Ja,Za,eb=function(){var a,e=na;if(u.setTimeout)a=u.setTimeout, e=u.clearTimeout;else if(u.WScript)a=function(a,e){u.WScript.Sleep(e);a()};else throw new ya;return{setTimeout:a,clearTimeout:e}}(),$a=eb.setTimeout,pb=eb.clearTimeout;(function(){function a(e){if(d)$a(function(){a(e)},0);else{var m=A[e];if(m&&(d=!0,m=b(m)(),Za(e),d=!1,m===J))return q(m.e)}}function e(){if(!u.postMessage||u.importScripts)return!1;var a=!1,e=u.onmessage;u.onmessage=function(){a=!0};u.postMessage("","*");u.onmessage=e;return a}var m=1,A={},d=!1;Za=function(a){delete A[a]};String(toString).replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/toString| for [^\]]+/g,".*?");var c=n.setImmediate;if(Y(c))Ja=function(e){var b=m++;A[b]=e;c(function(){a(b)});return b};else if("undefined"!==typeof p&&"[object process]"==={}.toString.call(p))Ja=function(e){var b=m++;A[b]=e;p.nextTick(function(){a(b)});return b};else if(e()){var f=function(e){"string"===typeof e.data&&e.data.substring(0,h.length)===h&&a(e.data.substring(h.length))},h="ms.rx.schedule"+Math.random();u.addEventListener?u.addEventListener("message",f,!1):u.attachEvent? u.attachEvent("onmessage",f):u.onmessage=f;Ja=function(a){var e=m++;A[e]=a;u.postMessage(h+currentId,"*");return e}}else if(u.MessageChannel){var g=new u.MessageChannel;g.port1.onmessage=function(e){a(e.data)};Ja=function(a){var e=m++;A[e]=a;g.port2.postMessage(e);return e}}else Ja="document"in u&&"onreadystatechange"in u.document.createElement("script")?function(e){var b=u.document.createElement("script"),d=m++;A[d]=e;b.onreadystatechange=function(){a(d);b.onreadystatechange=null;b.parentNode.removeChild(b); b=null};u.document.documentElement.appendChild(b);return d}:function(e){var b=m++;A[b]=e;$a(function(){a(b)},0);return b}})();var za=qa.timeout=qa["default"]=function(){return new qa(Ea,function(a,e){var m=this,b=new T,d=Ja(function(){!b.isDisposed&&b.setDisposable(e(m,a))});return new W(b,pa(function(){Za(d)}))},function(a,e,m){var b=this;e=qa.normalize(e);var d=new T;if(0===e)return b.scheduleWithState(a,m);var c=$a(function(){!d.isDisposed&&d.setDisposable(m(b,a))},e);return new W(d,pa(function(){pb(c)}))}, function(a,e,m){return this.scheduleWithRelativeAndState(a,e-this.now(),m)})}(),xa=D.Notification=function(){function a(e,m,b,C,d,c){this.kind=e;this.value=m;this.exception=b;this._accept=C;this._acceptObservable=d;this.toString=c}a.prototype.accept=function(a,m,b){return a&&"object"===typeof a?this._acceptObservable(a):this._accept(a,m,b)};a.prototype.toObservable=function(a){var m=this;ea(a)||(a=ma);return new P(function(b){return a.scheduleWithState(m,function(a,e){e._acceptObservable(b);"N"=== e.kind&&b.onCompleted()})})};return a}(),qb=xa.createOnNext=function(){function a(e){return e(this.value)}function e(a){return a.onNext(this.value)}function m(){return"OnNext("+this.value+")"}return function(b){return new xa("N",b,null,a,e,m)}}(),rb=xa.createOnError=function(){function a(e,m){return m(this.exception)}function e(a){return a.onError(this.exception)}function m(){return"OnError("+this.exception+")"}return function(b){return new xa("E",null,b,a,e,m)}}(),sb=xa.createOnCompleted=function(){function a(e, m,b){return b()}function e(a){return a.onCompleted()}function m(){return"OnCompleted()"}return function(){return new xa("C",null,null,a,e,m)}}(),Aa=D.Observer=function(){},Oa=Aa.create=function(a,e,m){a||(a=na);e||(e=Ka);m||(m=na);return new tb(a,e,m)},Pa=D.internals.AbstractObserver=function(a){function e(){this.isStopped=!1}H(e,a);e.prototype.next=Fa;e.prototype.error=Fa;e.prototype.completed=Fa;e.prototype.onNext=function(a){!this.isStopped&&this.next(a)};e.prototype.onError=function(a){this.isStopped|| (this.isStopped=!0,this.error(a))};e.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.completed())};e.prototype.dispose=function(){this.isStopped=!0};e.prototype.fail=function(a){return this.isStopped?!1:(this.isStopped=!0,this.error(a),!0)};return e}(Aa),tb=D.AnonymousObserver=function(a){function e(e,b,d){a.call(this);this._onNext=e;this._onError=b;this._onCompleted=d}H(e,a);e.prototype.next=function(a){this._onNext(a)};e.prototype.error=function(a){this._onError(a)};e.prototype.completed= function(){this._onCompleted()};return e}(Pa),z,N=D.Observable=function(){function a(e){this._subscribe=e}z=a.prototype;a.isObservable=function(a){return a&&Y(a.subscribe)};z.subscribe=z.forEach=function(a,m,b){return this._subscribe("object"===typeof a?a:Oa(a,m,b))};z.subscribeOnNext=function(a,m){return this._subscribe(Oa("undefined"!==typeof m?function(b){a.call(m,b)}:a))};z.subscribeOnError=function(a,m){return this._subscribe(Oa(null,"undefined"!==typeof m?function(b){a.call(m,b)}:a))};z.subscribeOnCompleted= function(a,m){return this._subscribe(Oa(null,null,"undefined"!==typeof m?function(){a.call(m)}:a))};return a}(),ub=D.internals.ScheduledObserver=function(a){function e(e,b){a.call(this);this.scheduler=e;this.observer=b;this.hasFaulted=this.isAcquired=!1;this.queue=[];this.disposable=new oa}H(e,a);e.prototype.next=function(a){var e=this;this.queue.push(function(){e.observer.onNext(a)})};e.prototype.error=function(a){var e=this;this.queue.push(function(){e.observer.onError(a)})};e.prototype.completed= function(){var a=this;this.queue.push(function(){a.observer.onCompleted()})};e.prototype.ensureActive=function(){var a=!1;!this.hasFaulted&&0<this.queue.length&&(a=!this.isAcquired,this.isAcquired=!0);a&&this.disposable.setDisposable(this.scheduler.scheduleRecursiveWithState(this,function(a,e){var m;if(0<a.queue.length){m=a.queue.shift();m=b(m)();if(m===J)return a.queue=[],a.hasFaulted=!0,q(m.e);e(a)}else a.isAcquired=!1}))};e.prototype.dispose=function(){a.prototype.dispose.call(this);this.disposable.dispose()}; return e}(Pa),ba=D.ObservableBase=function(a){function e(a){return a&&Y(a.dispose)?a:Y(a)?pa(a):ka}function m(a,m){var A=m[0],d=m[1],d=b(d.subscribeCore).call(d,A);if(d===J&&!A.fail(J.e))return q(J.e);A.setDisposable(e(d))}function A(a){a=new fb(a);var e=[a,this];ra.scheduleRequired()?ra.scheduleWithState(e,m):m(null,e);return a}function d(){a.call(this,A)}H(d,a);d.prototype.subscribeCore=Fa;return d}(N),Ta=function(a){function e(e,b,m,d){this.resultSelector=D.helpers.isFunction(m)?m:null;this.selector= D.internals.bindCallback(D.helpers.isFunction(b)?b:function(){return b},d,3);this.source=e;a.call(this)}function m(a,e,b,m){this.i=0;this.selector=e;this.resultSelector=b;this.source=m;this.isStopped=!1;this.o=a}H(e,a);e.prototype.subscribeCore=function(a){return this.source.subscribe(new m(a,this.selector,this.resultSelector,this))};m.prototype._wrapResult=function(a,e,b){return this.resultSelector?a.map(function(a,m){return this.resultSelector(e,a,b,m)},this):a};m.prototype.onNext=function(a){if(!this.isStopped){var e= this.i++,m=b(this.selector)(a,e,this.source);if(m===J)return this.o.onError(m.e);D.helpers.isPromise(m)&&(m=D.Observable.fromPromise(m));D.helpers.isArrayLike(m)&&(m=D.Observable.from(m));this.o.onNext(this._wrapResult(m,a,e))}};m.prototype.onError=function(a){this.isStopped||(this.isStopped=!0,this.o.onError(a))};m.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())};return e}(ba),Da=D.internals.Enumerable=function(){},vb=function(a){function e(e){this.sources= e;a.call(this)}function m(a,e,m){this.o=a;this.s=e;this.e=m;this.isStopped=!1}H(e,a);e.prototype.subscribeCore=function(a){var e,d=new oa,C=ma.scheduleRecursiveWithState(this.sources._es6shim_iterator_(),function(C,c){if(!e){var f=b(C.next).call(C);if(f===J)return a.onError(f.e);if(f.done)return a.onCompleted();f=f.value;ha(f)&&(f=ja(f));var h=new T;d.setDisposable(h);h.setDisposable(f.subscribe(new m(a,c,C)))}});return new W(d,C,pa(function(){e=!0}))};m.prototype.onNext=function(a){if(!this.isStopped)this.o.onNext(a)}; m.prototype.onError=function(a){this.isStopped||(this.isStopped=!0,this.o.onError(a))};m.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.s(this.e))};m.prototype.dispose=function(){this.isStopped=!0};m.prototype.fail=function(a){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(a),!0)};return e}(ba);Da.prototype.concat=function(){return new vb(this)};var wb=function(a){function e(e){this.sources=e;a.call(this)}H(e,a);e.prototype.subscribeCore=function(a){var e=this.sources._es6shim_iterator_(), d,C=new oa,c=ma.scheduleRecursiveWithState(null,function(c,f){if(!d){var h=b(e.next).call(e);if(h===J)return a.onError(h.e);if(h.done)return null!==c?a.onError(c):a.onCompleted();h=h.value;ha(h)&&(h=ja(h));var g=new T;C.setDisposable(g);g.setDisposable(h.subscribe(function(e){a.onNext(e)},f,function(){a.onCompleted()}))}});return new W(C,c,pa(function(){d=!0}))};return e}(ba);Da.prototype.catchError=function(){return new wb(this)};Da.prototype.catchErrorWhen=function(a){var e=this;return new P(function(m){var d= new Ba,c=new Ba,f=a(d).subscribe(c),h=e._es6shim_iterator_(),g,l=new oa,u=ma.scheduleRecursive(function(a){if(!g){var e=b(h.next).call(h);if(e===J)return m.onError(e.e);if(e.done)m.onCompleted();else{e=e.value;ha(e)&&(e=ja(e));var C=new T,f=new T;l.setDisposable(new W(f,C));C.setDisposable(e.subscribe(function(a){m.onNext(a)},function(e){f.setDisposable(c.subscribe(a,function(a){m.onError(a)},function(){m.onCompleted()}));d.onNext(e)},function(){m.onCompleted()}))}}});return new W(f,l,u,pa(function(){g= !0}))})};var xb=function(a){function e(a,e){this.v=a;this.c=null==e?-1:e}function m(a){this.v=a.v;this.l=a.c}H(e,a);e.prototype._es6shim_iterator_=function(){return new m(this)};m.prototype.next=function(){if(0===this.l)return Ga;0<this.l&&this.l--;return{done:!1,value:this.v}};return e}(Da),ab=Da.repeat=function(a,e){return new xb(a,e)},yb=function(a){function e(a,e,m){this.s=a;this.fn=e?sa(e,m,3):null}function m(a){this.i=-1;this.s=a.s;this.l=this.s.length;this.fn=a.fn}H(e,a);e.prototype._es6shim_iterator_= function(){return new m(this)};m.prototype.next=function(){return++this.i<this.l?{done:!1,value:this.fn?this.fn(this.s[this.i],this.i,this.s):this.s[this.i]}:Ga};return e}(Da),gb=Da.of=function(a,e,m){return new yb(a,e,m)},zb=function(a){function e(e){this.source=e;a.call(this)}function m(a){this.o=a;this.a=[];this.isStopped=!1}H(e,a);e.prototype.subscribeCore=function(a){return this.source.subscribe(new m(a))};m.prototype.onNext=function(a){this.isStopped||this.a.push(a)};m.prototype.onError=function(a){this.isStopped|| (this.isStopped=!0,this.o.onError(a))};m.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onNext(this.a),this.o.onCompleted())};m.prototype.dispose=function(){this.isStopped=!0};m.prototype.fail=function(a){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(a),!0)};return e}(ba);z.toArray=function(){return new zb(this)};N.create=function(a,e){return new P(a,e)};var db=N.defer=function(a){return new P(function(e){var m;try{m=a()}catch(b){return bb(b).subscribe(e)}ha(m)&& (m=ja(m));return m.subscribe(e)})},hb=function(a){function e(e){this.scheduler=e;a.call(this)}function m(a,e){this.observer=a;this.scheduler=e}function b(a,e){e.onCompleted();return ka}H(e,a);e.prototype.subscribeCore=function(a){return(new m(a,this.scheduler)).run()};m.prototype.run=function(){return this.scheduler.scheduleWithState(this.observer,b)};return e}(ba),Ab=new hb(ma),Bb=N.empty=function(a){ea(a)||(a=ma);return a===ma?Ab:new hb(a)},Db=function(a){function e(e,b,d){this.iterable=e;this.mapper= b;this.scheduler=d;a.call(this)}H(e,a);e.prototype.subscribeCore=function(a){return(new Cb(a,this)).run()};return e}(ba),Cb=function(){function a(e,b){this.o=e;this.parent=b}a.prototype.run=function(){var a=h(Object(this.parent.iterable)),m=this.o,d=this.parent.mapper;return this.parent.scheduler.scheduleRecursiveWithState(0,function(c,C){var f=b(a.next).call(a);if(f===J)return m.onError(f.e);if(f.done)return m.onCompleted();f=f.value;if(Y(d)&&(f=b(d)(f,c),f===J))return m.onError(f.e);m.onNext(f); C(c+1)})};return a}(),cb=Math.pow(2,53)-1;d.prototype._es6shim_iterator_=function(){return new v(this._s)};v.prototype._es6shim_iterator_=function(){return this};v.prototype.next=function(){return this._i<this._l?{done:!1,value:this._s.charAt(this._i++)}:Ga};w.prototype._es6shim_iterator_=function(){return new l(this._a)};l.prototype._es6shim_iterator_=function(){return this};l.prototype.next=function(){return this._i<this._l?{done:!1,value:this._a[this._i++]}:Ga};var Eb=N.from=function(a,e,b,d){if(null== a)throw Error("iterable cannot be null.");if(e&&!Y(e))throw Error("mapFn when provided must be a function");if(e)var c=sa(e,b,2);ea(d)||(d=ra);return new Db(a,c,d)},Ra=function(a){function e(e,b){this.args=e;this.scheduler=b;a.call(this)}H(e,a);e.prototype.subscribeCore=function(a){return(new f(a,this)).run()};return e}(ba);f.prototype.run=function(){var a=this.observer,e=this.parent.args,b=e.length;return this.parent.scheduler.scheduleRecursiveWithState(0,function(d,c){if(d<b)a.onNext(e[d]),c(d+ 1);else a.onCompleted()})};var Fb=N.fromArray=function(a,e){ea(e)||(e=ra);return new Ra(a,e)},Gb=new (function(a){function e(){a.call(this)}H(e,a);e.prototype.subscribeCore=function(a){return ka};return e}(ba));N.never=function(){return Gb};N.of=function(){for(var a=arguments.length,e=Array(a),b=0;b<a;b++)e[b]=arguments[b];return new Ra(e,ra)};N.ofWithScheduler=function(a){for(var e=arguments.length,b=Array(e-1),d=1;d<e;d++)b[d-1]=arguments[d];return new Ra(b,a)};var Hb=function(a){function e(e,b){this.obj= e;this.keys=Object.keys(e);this.scheduler=b;a.call(this)}H(e,a);e.prototype.subscribeCore=function(a){return(new k(a,this)).run()};return e}(ba);k.prototype.run=function(){var a=this.observer,e=this.parent.obj,b=this.parent.keys,d=b.length;return this.parent.scheduler.scheduleRecursiveWithState(0,function(c,f){if(c<d){var h=b[c];a.onNext([h,e[h]]);f(c+1)}else a.onCompleted()})};N.pairs=function(a,e){e||(e=ra);return new Hb(a,e)};var Jb=function(a){function e(e,b,d){this.start=e;this.rangeCount=b; this.scheduler=d;a.call(this)}H(e,a);e.prototype.subscribeCore=function(a){return(new Ib(a,this)).run()};return e}(ba),Ib=function(){function a(e,b){this.observer=e;this.parent=b}a.prototype.run=function(){var a=this.parent.start,b=this.parent.rangeCount,d=this.observer;return this.parent.scheduler.scheduleRecursiveWithState(0,function(c,f){if(c<b)d.onNext(a+c),f(c+1);else d.onCompleted()})};return a}();N.range=function(a,e,b){ea(b)||(b=ra);return new Jb(a,e,b)};var Kb=function(a){function e(e,b, d){this.value=e;this.repeatCount=null==b?-1:b;this.scheduler=d;a.call(this)}H(e,a);e.prototype.subscribeCore=function(a){return(new B(a,this)).run()};return e}(ba);B.prototype.run=function(){var a=this.observer,e=this.parent.value;return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount,function(b,d){if(-1===b||0<b)a.onNext(e),0<b&&b--;if(0===b)return a.onCompleted();d(b)})};N.repeat=function(a,e,b){ea(b)||(b=ra);return new Kb(a,e,b)};var Lb=function(a){function e(e,b){this.value= e;this.scheduler=b;a.call(this)}function b(a,e,m){this.observer=a;this.value=e;this.scheduler=m}function d(a,e){var b=e[1];b.onNext(e[0]);b.onCompleted();return ka}H(e,a);e.prototype.subscribeCore=function(a){return(new b(a,this.value,this.scheduler)).run()};b.prototype.run=function(){var a=[this.value,this.observer];return this.scheduler===ma?d(null,a):this.scheduler.scheduleWithState(a,d)};return e}(ba);N["return"]=N.just=function(a,e){ea(e)||(e=ma);return new Lb(a,e)};var Mb=function(a){function e(e, b){this.error=e;this.scheduler=b;a.call(this)}function b(a,e){this.o=a;this.p=e}function d(a,e){e[1].onError(e[0])}H(e,a);e.prototype.subscribeCore=function(a){return(new b(a,this)).run()};b.prototype.run=function(){return this.p.scheduler.scheduleWithState([this.p.error,this.o],d)};return e}(ba),bb=N["throw"]=function(a,e){ea(e)||(e=ma);return new Mb(a,e)},nb=function(a){function e(e,b,d){this._o=e;this._s=b;this._fn=d;a.call(this)}H(e,a);e.prototype.next=function(a){this._o.onNext(a)};e.prototype.completed= function(){return this._o.onCompleted()};e.prototype.error=function(a){a=b(this._fn)(a);if(a===J)return this._o.onError(a.e);ha(a)&&(a=ja(a));var e=new T;this._s.setDisposable(e);e.setDisposable(a.subscribe(this._o))};return e}(Pa);z["catch"]=function(a){return Y(a)?F(this,a):Nb([this,a])};var Nb=N["catch"]=function(){var a;if(Array.isArray(arguments[0]))a=arguments[0];else{var e=arguments.length;a=Array(e);for(var b=0;b<e;b++)a[b]=arguments[b]}return gb(a).catchError()};z.combineLatest=function(){for(var a= arguments.length,e=Array(a),b=0;b<a;b++)e[b]=arguments[b];Array.isArray(e[0])?e[0].unshift(this):e.unshift(this);return Ob.apply(this,e)};var Ob=N.combineLatest=function(){for(var a=arguments.length,e=Array(a),b=0;b<a;b++)e[b]=arguments[b];var d=Y(e[a-1])?e.pop():x;Array.isArray(e[0])&&(e=e[0]);return new P(function(a){function b(e){c[e]=!0;if(f||(f=c.every(ua))){try{var m=d.apply(null,C)}catch(g){return a.onError(g)}a.onNext(m)}else if(h.filter(function(a,b){return b!==e}).every(ua))a.onCompleted()} for(var m=e.length,c=t(m,E),f=!1,h=t(m,E),C=Array(m),g=Array(m),l=0;l<m;l++)(function(m){var d=e[m],c=new T;ha(d)&&(d=ja(d));c.setDisposable(d.subscribe(function(a){C[m]=a;b(m)},function(e){a.onError(e)},function(){h[m]=!0;h.every(ua)&&a.onCompleted()}));g[m]=c})(l);return new W(g)},this)};z.concat=function(){for(var a=[],e=0,b=arguments.length;e<b;e++)a.push(arguments[e]);a.unshift(this);return Pb.apply(null,a)};var Qb=function(a){function e(e){this.sources=e;a.call(this)}function b(a,e){this.sources= a;this.o=e}H(e,a);e.prototype.subscribeCore=function(a){return(new b(this.sources,a)).run()};b.prototype.run=function(){var a,e=new oa,b=this.sources,m=b.length,d=this.o,c=ma.scheduleRecursiveWithState(0,function(c,f){if(!a){if(c===m)return d.onCompleted();var h=b[c];ha(h)&&(h=ja(h));var C=new T;e.setDisposable(C);C.setDisposable(h.subscribe(function(a){d.onNext(a)},function(a){d.onError(a)},function(){f(c+1)}))}});return new W(e,c,pa(function(){a=!0}))};return e}(ba),Pb=N.concat=function(){var a; if(Array.isArray(arguments[0]))a=arguments[0];else{a=Array(arguments.length);for(var e=0,b=arguments.length;e<b;e++)a[e]=arguments[e]}return new Qb(a)};z.concatAll=function(){return this.merge(1)};var Sb=function(a){function e(e,b){this.source=e;this.maxConcurrent=b;a.call(this)}H(e,a);e.prototype.subscribeCore=function(a){var e=new W;e.add(this.source.subscribe(new Rb(a,this.maxConcurrent,e)));return e};return e}(ba),Rb=function(){function a(e,b,d){this.o=e;this.max=b;this.g=d;this.done=!1;this.q= [];this.activeCount=0;this.isStopped=!1}function e(a,e){this.parent=a;this.sad=e;this.isStopped=!1}a.prototype.handleSubscribe=function(a){var b=new T;this.g.add(b);ha(a)&&(a=ja(a));b.setDisposable(a.subscribe(new e(this,b)))};a.prototype.onNext=function(a){this.isStopped||(this.activeCount<this.max?(this.activeCount++,this.handleSubscribe(a)):this.q.push(a))};a.prototype.onError=function(a){this.isStopped||(this.isStopped=!0,this.o.onError(a))};a.prototype.onCompleted=function(){this.isStopped|| (this.done=this.isStopped=!0,0===this.activeCount&&this.o.onCompleted())};a.prototype.dispose=function(){this.isStopped=!0};a.prototype.fail=function(a){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(a),!0)};e.prototype.onNext=function(a){if(!this.isStopped)this.parent.o.onNext(a)};e.prototype.onError=function(a){this.isStopped||(this.isStopped=!0,this.parent.o.onError(a))};e.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=!0;var a=this.parent;a.g.remove(this.sad); 0<a.q.length?a.handleSubscribe(a.q.shift()):(a.activeCount--,a.done&&0===a.activeCount&&a.o.onCompleted())}};e.prototype.dispose=function(){this.isStopped=!0};e.prototype.fail=function(a){return this.isStopped?!1:(this.isStopped=!0,this.parent.o.onError(a),!0)};return a}();z.merge=function(a){return"number"!==typeof a?Tb(this,a):new Sb(this,a)};var Tb=N.merge=function(){var a,e=[],b,d=arguments.length;arguments[0]?ea(arguments[0])?(a=arguments[0],b=1):(a=ma,b=0):(a=ma,b=1);for(;b<d;b++)e.push(arguments[b]); Array.isArray(e[0])&&(e=e[0]);return y(a,e).mergeAll()},ib=D.CompositeError=function(a){this.name="NotImplementedError";this.innerErrors=a;this.message="This contains multiple errors. Check the innerErrors";Error.call(this)};ib.prototype=Error.prototype;N.mergeDelayError=function(){var a;if(Array.isArray(arguments[0]))a=arguments[0];else{var e=arguments.length;a=Array(e);for(var b=0;b<e;b++)a[b]=arguments[b]}var d=y(null,a);return new P(function(a){function e(){if(0===f.length)a.onCompleted();else if(1=== f.length)a.onError(f[0]);else a.onError(new ib(f))}var b=new W,m=new T,c=!1,f=[];b.add(m);m.setDisposable(d.subscribe(function(d){var m=new T;b.add(m);ha(d)&&(d=ja(d));m.setDisposable(d.subscribe(function(e){a.onNext(e)},function(a){f.push(a);b.remove(m);c&&1===b.length&&e()},function(){b.remove(m);c&&1===b.length&&e()}))},function(a){f.push(a);c=!0;1===b.length&&e()},function(){c=!0;1===b.length&&e()}));return b})};var Ub=function(a){function e(e){this.source=e;a.call(this)}function b(a,e){this.o= a;this.g=e;this.done=this.isStopped=!1}function d(a,e){this.parent=a;this.sad=e;this.isStopped=!1}H(e,a);e.prototype.subscribeCore=function(a){var e=new W,d=new T;e.add(d);d.setDisposable(this.source.subscribe(new b(a,e)));return e};b.prototype.onNext=function(a){if(!this.isStopped){var e=new T;this.g.add(e);ha(a)&&(a=ja(a));e.setDisposable(a.subscribe(new d(this,e)))}};b.prototype.onError=function(a){this.isStopped||(this.isStopped=!0,this.o.onError(a))};b.prototype.onCompleted=function(){this.isStopped|| (this.done=this.isStopped=!0,1===this.g.length&&this.o.onCompleted())};b.prototype.dispose=function(){this.isStopped=!0};b.prototype.fail=function(a){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(a),!0)};d.prototype.onNext=function(a){if(!this.isStopped)this.parent.o.onNext(a)};d.prototype.onError=function(a){this.isStopped||(this.isStopped=!0,this.parent.o.onError(a))};d.prototype.onCompleted=function(){if(!this.isStopped){var a=this.parent;this.isStopped=!0;a.g.remove(this.sad);a.done&& 1===a.g.length&&a.o.onCompleted()}};d.prototype.dispose=function(){this.isStopped=!0};d.prototype.fail=function(a){return this.isStopped?!1:(this.isStopped=!0,this.parent.o.onError(a),!0)};return e}(ba);z.mergeAll=function(){return new Ub(this)};z.skipUntil=function(a){var e=this;return new P(function(b){var d=!1,c=new W(e.subscribe(function(a){d&&b.onNext(a)},function(a){b.onError(a)},function(){d&&b.onCompleted()}));ha(a)&&(a=ja(a));var f=new T;c.add(f);f.setDisposable(a.subscribe(function(){d= !0;f.dispose()},function(a){b.onError(a)},function(){f.dispose()}));return c},e)};var Vb=function(a){function e(e){this.source=e;a.call(this)}function b(a,e){this.o=a;this.inner=e;this.stopped=!1;this.latest=0;this.isStopped=this.hasLatest=!1}function d(a,e){this.parent=a;this.id=e;this.isStopped=!1}H(e,a);e.prototype.subscribeCore=function(a){var e=new oa;a=this.source.subscribe(new b(a,e));return new W(a,e)};b.prototype.onNext=function(a){if(!this.isStopped){var e=new T,b=++this.latest;this.hasLatest= !0;this.inner.setDisposable(e);ha(a)&&(a=ja(a));e.setDisposable(a.subscribe(new d(this,b)))}};b.prototype.onError=function(a){this.isStopped||(this.isStopped=!0,this.o.onError(a))};b.prototype.onCompleted=function(){this.isStopped||(this.stopped=this.isStopped=!0,!this.hasLatest&&this.o.onCompleted())};b.prototype.dispose=function(){this.isStopped=!0};b.prototype.fail=function(a){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(a),!0)};d.prototype.onNext=function(a){this.isStopped||this.parent.latest=== this.id&&this.parent.o.onNext(a)};d.prototype.onError=function(a){this.isStopped||(this.isStopped=!0,this.parent.latest===this.id&&this.parent.o.onError(a))};d.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.parent.latest===this.id&&(this.parent.hasLatest=!1,this.parent.isStopped&&this.parent.o.onCompleted()))};d.prototype.dispose=function(){this.isStopped=!0};d.prototype.fail=function(a){return this.isStopped?!1:(this.isStopped=!0,this.parent.o.onError(a),!0)};return e}(ba); z["switch"]=z.switchLatest=function(){return new Vb(this)};var Wb=function(a){function e(e,b){this.source=e;this.other=ha(b)?ja(b):b;a.call(this)}function b(a){this.o=a;this.isStopped=!1}H(e,a);e.prototype.subscribeCore=function(a){return new W(this.source.subscribe(a),this.other.subscribe(new b(a)))};b.prototype.onNext=function(a){if(!this.isStopped)this.o.onCompleted()};b.prototype.onError=function(a){this.isStopped||(this.isStopped=!0,this.o.onError(a))};b.prototype.onCompleted=function(){!this.isStopped&& (this.isStopped=!0)};b.prototype.dispose=function(){this.isStopped=!0};b.prototype.fail=function(a){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(a),!0)};return e}(ba);z.takeUntil=function(a){return new Wb(this,a)};z.withLatestFrom=function(){for(var a=arguments.length,e=Array(a),d=0;d<a;d++)e[d]=arguments[d];var c=e.pop(),f=this;Array.isArray(e[0])&&(e=e[0]);return new P(function(a){for(var d=e.length,m=t(d,E),h=!1,g=Array(d),C=Array(d+1),l=0;l<d;l++)(function(b){var d=e[b],c=new T; ha(d)&&(d=ja(d));c.setDisposable(d.subscribe(function(a){g[b]=a;m[b]=!0;h=m.every(ua)},function(e){a.onError(e)},na));C[b]=c})(l);l=new T;l.setDisposable(f.subscribe(function(e){e=[e].concat(g);if(h){e=b(c).apply(null,e);if(e===J)return a.onError(e.e);a.onNext(e)}},function(e){a.onError(e)},function(){a.onCompleted()}));C[d]=l;return new W(C)},this)};z.zip=function(){if(0===arguments.length)throw Error("invalid arguments");for(var a=arguments.length,e=Array(a),d=0;d<a;d++)e[d]=arguments[d];var c= Y(e[a-1])?e.pop():x;Array.isArray(e[0])&&(e=e[0]);var f=this;e.unshift(f);return new P(function(a){for(var d=e.length,m=t(d,K),h=t(d,E),g=Array(d),C=0;C<d;C++)(function(d){var C=e[d],l=new T;ha(C)&&(C=ja(C));l.setDisposable(C.subscribe(function(e){m[d].push(e);if(m.every(function(a){return 0<a.length})){e=m.map(function(a){return a.shift()});e=b(c).apply(f,e);if(e===J)return a.onError(e.e);a.onNext(e)}else if(h.filter(function(a,e){return e!==d}).every(ua))a.onCompleted()},function(e){a.onError(e)}, function(){h[d]=!0;h.every(ua)&&a.onCompleted()}));g[d]=l})(C);return new W(g)},f)};N.zip=function(){for(var a=arguments.length,e=Array(a),b=0;b<a;b++)e[b]=arguments[b];Array.isArray(e[0])&&(e=Y(e[1])?e[0].concat(e[1]):e[0]);a=e.shift();return a.zip.apply(a,e)};z.zipIterable=function(){if(0===arguments.length)throw Error("invalid arguments");for(var a=arguments.length,e=Array(a),d=0;d<a;d++)e[d]=arguments[d];var c=Y(e[a-1])?e.pop():x,f=this;e.unshift(f);return new P(function(a){for(var d=e.length, m=t(d,K),h=t(d,E),g=Array(d),l=0;l<d;l++)(function(d){var l=e[d],C=new T;(Sa(l)||isIterable(l))&&(l=Eb(l));C.setDisposable(l.subscribe(function(e){m[d].push(e);if(m.every(function(a){return 0<a.length})){e=m.map(function(a){return a.shift()});e=b(c).apply(f,e);if(e===J)return a.onError(e.e);a.onNext(e)}else if(h.filter(function(a,e){return e!==d}).every(ua))a.onCompleted()},function(e){a.onError(e)},function(){h[d]=!0;h.every(ua)&&a.onCompleted()}));g[d]=C})(l);return new W(g)},f)};z.asObservable= function(){return new P(I(this),this)};z.dematerialize=function(){var a=this;return new P(function(e){return a.subscribe(function(a){return a.accept(e)},function(a){e.onError(a)},function(){e.onCompleted()})},this)};var Yb=function(a){function e(e,b,d){this.source=e;this.keyFn=b;this.comparer=d;a.call(this)}H(e,a);e.prototype.subscribeCore=function(a){return this.source.subscribe(new Xb(a,this.keyFn,this.comparer))};return e}(ba),Xb=function(a){function e(e,b,d){this.o=e;this.keyFn=b;this.comparer= d;this.hasCurrentKey=!1;this.currentKey=null;a.call(this)}H(e,a);e.prototype.next=function(a){var e=a,d;if(Y(this.keyFn)&&(e=b(this.keyFn)(a),e===J))return this.o.onError(e.e);if(this.hasCurrentKey&&(d=b(this.comparer)(this.currentKey,e),d===J))return this.o.onError(d.e);this.hasCurrentKey&&d||(this.hasCurrentKey=!0,this.currentKey=e,this.o.onNext(a))};e.prototype.error=function(a){this.o.onError(a)};e.prototype.completed=function(){this.o.onCompleted()};return e}(Pa);z.distinctUntilChanged=function(a, e){e||(e=Wa);return new Yb(this,a,e)};var Zb=function(a){function e(e,b,d,m){this.source=e;this._oN=b;this._oE=d;this._oC=m;a.call(this)}function d(a,e){this.o=a;this.t=!e._oN||Y(e._oN)?Oa(e._oN||na,e._oE||na,e._oC||na):e._oN;this.isStopped=!1}H(e,a);e.prototype.subscribeCore=function(a){return this.source.subscribe(new d(a,this))};d.prototype.onNext=function(a){if(!this.isStopped){var e=b(this.t.onNext).call(this.t,a);if(e===J)this.o.onError(e.e);this.o.onNext(a)}};d.prototype.onError=function(a){if(!this.isStopped){this.isStopped= !0;var e=b(this.t.onError).call(this.t,a);if(e===J)return this.o.onError(e.e);this.o.onError(a)}};d.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=!0;var a=b(this.t.onCompleted).call(this.t);if(a===J)return this.o.onError(a.e);this.o.onCompleted()}};d.prototype.dispose=function(){this.isStopped=!0};d.prototype.fail=function(a){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(a),!0)};return e}(ba);z["do"]=z.tap=z.doAction=function(a,e,b){return new Zb(this,a,e,b)};z.doOnNext= z.tapOnNext=function(a,e){return this.tap("undefined"!==typeof e?function(b){a.call(e,b)}:a)};z.doOnError=z.tapOnError=function(a,e){return this.tap(na,"undefined"!==typeof e?function(b){a.call(e,b)}:a)};z.doOnCompleted=z.tapOnCompleted=function(a,e){return this.tap(na,null,"undefined"!==typeof e?function(){a.call(e)}:a)};z["finally"]=function(a){var e=this;return new P(function(d){var c=b(e.subscribe).call(e,d);return c===J?(a(),q(c.e)):pa(function(){var e=b(c.dispose).call(c);a();e===J&&q(e.e)})}, this)};var $b=function(a){function e(e){this.source=e;a.call(this)}function b(a){this.o=a;this.isStopped=!1}H(e,a);e.prototype.subscribeCore=function(a){return this.source.subscribe(new b(a))};b.prototype.onNext=na;b.prototype.onError=function(a){this.isStopped||(this.isStopped=!0,this.o.onError(a))};b.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())};b.prototype.dispose=function(){this.isStopped=!0};b.prototype.fail=function(a){return this.isStopped?!1:(this.isStopped= !0,this.observer.onError(a),!0)};return e}(ba);z.ignoreElements=function(){return new $b(this)};z.materialize=function(){var a=this;return new P(function(e){return a.subscribe(function(a){e.onNext(qb(a))},function(a){e.onNext(rb(a));e.onCompleted()},function(){e.onNext(sb());e.onCompleted()})},a)};z.repeat=function(a){return ab(this,a).concat()};z.retry=function(a){return ab(this,a).catchError()};z.retryWhen=function(a){return ab(this).catchErrorWhen(a)};var ac=function(a){function e(e,b,d,c){this.source= e;this.accumulator=b;this.hasSeed=d;this.seed=c;a.call(this)}H(e,a);e.prototype.subscribeCore=function(a){return this.source.subscribe(new L(a,this))};return e}(ba);L.prototype={onNext:function(a){if(!this.isStopped){!this.hasValue&&(this.hasValue=!0);this.hasAccumulation?this.accumulation=b(this.accumulator)(this.accumulation,a):(this.accumulation=this.hasSeed?b(this.accumulator)(this.seed,a):a,this.hasAccumulation=!0);if(this.accumulation===J)return this.o.onError(this.accumulation.e);this.o.onNext(this.accumulation)}}, onError:function(a){this.isStopped||(this.isStopped=!0,this.o.onError(a))},onCompleted:function(){this.isStopped||(this.isStopped=!0,!this.hasValue&&this.hasSeed&&this.o.onNext(this.seed),this.o.onCompleted())},dispose:function(){this.isStopped=!0},fail:function(a){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(a),!0)}};z.scan=function(){var a=!1,e,b=arguments[0];2===arguments.length&&(a=!0,e=arguments[1]);return new ac(this,b,a,e)};z.skipLast=function(a){if(0>a)throw new ga;var e=this; return new P(function(b){var d=[];return e.subscribe(function(e){d.push(e);d.length>a&&b.onNext(d.shift())},function(a){b.onError(a)},function(){b.onCompleted()})},e)};z.startWith=function(){var a,e=0;arguments.length&&ea(arguments[0])?(a=arguments[0],e=1):a=ma;for(var b=[],d=arguments.length;e<d;e++)b.push(arguments[e]);return gb([Fb(b,a),this]).concat()};z.takeLast=function(a){if(0>a)throw new ga;var e=this;return new P(function(b){var d=[];return e.subscribe(function(e){d.push(e);d.length>a&&d.shift()}, function(a){b.onError(a)},function(){for(;0<d.length;)b.onNext(d.shift());b.onCompleted()})},e)};z.flatMapConcat=z.concatMap=function(a,e,b){return(new Ta(this,a,e,b)).merge(1)};var jb=function(a){function e(e,b,d){this.source=e;this.selector=sa(b,d,3);a.call(this)}function d(a,e){return function(b,d,c){return a.call(this,e.selector(b,d,c),d,c)}}function c(a,e,b){this.o=a;this.selector=e;this.source=b;this.i=0;this.isStopped=!1}H(e,a);e.prototype.internalMap=function(a,b){return new e(this.source, d(a,this),b)};e.prototype.subscribeCore=function(a){return this.source.subscribe(new c(a,this.selector,this))};c.prototype.onNext=function(a){if(!this.isStopped){a=b(this.selector)(a,this.i++,this.source);if(a===J)return this.o.onError(a.e);this.o.onNext(a)}};c.prototype.onError=function(a){this.isStopped||(this.isStopped=!0,this.o.onError(a))};c.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())};c.prototype.dispose=function(){this.isStopped=!0};c.prototype.fail= function(a){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(a),!0)};return e}(ba);z.map=z.select=function(a,e){var b="function"===typeof a?a:function(){return a};return this instanceof jb?this.internalMap(b,e):new jb(this,b,e)};z.pluck=function(){var a=arguments.length,e=Array(a);if(0===a)throw Error("List of properties cannot be empty.");for(var b=0;b<a;b++)e[b]=arguments[b];return this.map(S(e,a))};z.flatMap=z.selectMany=function(a,e,b){return(new Ta(this,a,e,b)).mergeAll()};D.Observable.prototype.flatMapWithMaxConcurrent= function(a,e,b,d){return(new Ta(this,e,b,d)).merge(a)};D.Observable.prototype.flatMapLatest=function(a,e,b){return(new Ta(this,a,e,b)).switchLatest()};var bc=function(a){function e(e,b){this.source=e;this.skipCount=b;a.call(this)}function b(a,e){this.r=this.c=e;this.o=a;this.isStopped=!1}H(e,a);e.prototype.subscribeCore=function(a){return this.source.subscribe(new b(a,this.skipCount))};b.prototype.onNext=function(a){if(!this.isStopped)if(0>=this.r)this.o.onNext(a);else this.r--};b.prototype.onError= function(a){this.isStopped||(this.isStopped=!0,this.o.onError(a))};b.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())};b.prototype.dispose=function(){this.isStopped=!0};b.prototype.fail=function(a){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(a),!0)};return e}(ba);z.skip=function(a){if(0>a)throw new ga;return new bc(this,a)};z.skipWhile=function(a,e){var b=this,d=sa(a,e,3);return new P(function(a){var e=0,c=!1;return b.subscribe(function(f){if(!c)try{c= !d(f,e++,b)}catch(h){a.onError(h);return}c&&a.onNext(f)},function(e){a.onError(e)},function(){a.onCompleted()})},b)};z.take=function(a,e){if(0>a)throw new ga;if(0===a)return Bb(e);var b=this;return new P(function(e){var d=a;return b.subscribe(function(a){0<d--&&(e.onNext(a),0>=d&&e.onCompleted())},function(a){e.onError(a)},function(){e.onCompleted()})},b)};z.takeWhile=function(a,e){var b=this,d=sa(a,e,3);return new P(function(a){var e=0,c=!0;return b.subscribe(function(f){if(c){try{c=d(f,e++,b)}catch(h){a.onError(h); return}if(c)a.onNext(f);else a.onCompleted()}},function(e){a.onError(e)},function(){a.onCompleted()})},b)};var kb=function(a){function e(e,b,d){this.source=e;this.predicate=sa(b,d,3);a.call(this)}function d(a,e){return function(b,d,c){return e.predicate(b,d,c)&&a.call(this,b,d,c)}}function c(a,e,b){this.o=a;this.predicate=e;this.source=b;this.i=0;this.isStopped=!1}H(e,a);e.prototype.subscribeCore=function(a){return this.source.subscribe(new c(a,this.predicate,this))};e.prototype.internalFilter=function(a, b){return new e(this.source,d(a,this),b)};c.prototype.onNext=function(a){if(!this.isStopped){var e=b(this.predicate)(a,this.i++,this.source);if(e===J)return this.o.onError(e.e);e&&this.o.onNext(a)}};c.prototype.onError=function(a){this.isStopped||(this.isStopped=!0,this.o.onError(a))};c.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())};c.prototype.dispose=function(){this.isStopped=!0};c.prototype.fail=function(a){return this.isStopped?!1:(this.isStopped=!0, this.o.onError(a),!0)};return e}(ba);z.filter=z.where=function(a,e){return this instanceof kb?this.internalFilter(a,e):new kb(this,a,e)};N.fromCallback=function(a,e,b){return function(){"undefined"===typeof e&&(e=this);for(var d=arguments.length,c=Array(d),f=0;f<d;f++)c[f]=arguments[f];d=e;f=new Ua;c.push(Q(f,d,b));a.apply(d,c);return f.asObservable()}};N.fromNodeCallback=function(a,e,b){return function(){"undefined"===typeof e&&(e=this);for(var d=arguments.length,c=Array(d),f=0;f<d;f++)c[f]=arguments[f]; d=e;f=new Ua;c.push(O(f,d,b));a.apply(d,c);return f.asObservable()}};ca.prototype.dispose=function(){this.isDisposed||(this._e.removeEventListener(this._n,this._fn,!1),this.isDisposed=!0)};N.fromEvent=function(a,e,b){return a.addListener?cc(function(b){a.addListener(e,b)},function(b){a.removeListener(e,b)},b):new P(function(d){return M(a,e,Z(d,b))})};var cc=N.fromEventPattern=function(a,e,d,c){ea(c)||(c=ma);return(new P(function(c){function f(){var a=arguments[0];if(Y(d)&&(a=b(d).apply(null,arguments), a===J))return c.onError(a.e);c.onNext(a)}var h=a(f);return pa(function(){Y(e)&&e(f,h)})})).publish().refCount()},dc=function(a){function e(e){this.p=e;a.call(this)}H(e,a);e.prototype.subscribeCore=function(a){this.p.then(function(e){a.onNext(e);a.onCompleted()},function(e){a.onError(e)});return ka};return e}(ba),ja=N.fromPromise=function(a){return new dc(a)};z.toPromise=function(a){a||(a=D.config.Promise);if(!a)throw new ya("Promise type not provided nor in Rx.config.Promise");var e=this;return new a(function(a, b){var d,c=!1;e.subscribe(function(a){d=a;c=!0},b,function(){c&&a(d)})})};N.startAsync=function(a){var e;try{e=a()}catch(b){return bb(b)}return ja(e)};z.multicast=function(a,e){var b=this;return"function"===typeof a?new P(function(d){var c=b.multicast(a());return new W(e(c).subscribe(d),c.connect())},b):new ec(b,a)};z.publish=function(a){return a&&Y(a)?this.multicast(function(){return new Ba},a):this.multicast(new Ba)};z.share=function(){return this.publish().refCount()};z.publishLast=function(a){return a&& Y(a)?this.multicast(function(){return new Ua},a):this.multicast(new Ua)};z.publishValue=function(a,e){return 2===arguments.length?this.multicast(function(){return new lb(e)},a):this.multicast(new lb(a))};z.shareValue=function(a){return this.publishValue(a).refCount()};z.replay=function(a,e,b,d){return a&&Y(a)?this.multicast(function(){return new mb(e,b,d)},a):this.multicast(new mb(e,b,d))};z.shareReplay=function(a,e,b){return this.replay(null,a,e,b).refCount()};var ec=D.ConnectableObservable=function(a){function e(e, b){var d=!1,c,f=e.asObservable();this.connect=function(){d||(d=!0,c=new W(f.subscribe(b),pa(function(){d=!1})));return c};a.call(this,function(a){return b.subscribe(a)})}H(e,a);e.prototype.refCount=function(){var a,e=0,b=this;return new P(function(d){var c=1===++e,f=b.subscribe(d);c&&(a=b.connect());return function(){f.dispose();0===--e&&a.dispose()}})};return e}(N),fc=N.interval=function(a,e){return U(a,a,ea(e)?e:za)};N.timer=function(a,e,b){var d;ea(b)||(b=za);null!=e&&"number"===typeof e?d=e:ea(e)&& (b=e);return a instanceof Date&&void 0===d?V(a.getTime(),b):a instanceof Date&&void 0!==d?aa(a.getTime(),e,b):void 0===d?X(a,b):U(a,d,b)};z.delay=function(a,e){ea(e)||(e=za);return a instanceof Date?da(this,a.getTime(),e):R(this,a,e)};z.debounce=function(a,e){ea(e)||(e=za);var b=this;return new P(function(d){var c=new oa,f=!1,h,g=0,l=b.subscribe(function(b){f=!0;h=b;g++;var m=g;b=new T;c.setDisposable(b);b.setDisposable(e.scheduleWithRelative(a,function(){f&&g===m&&d.onNext(h);f=!1}))},function(a){c.dispose(); d.onError(a);f=!1;g++},function(){c.dispose();f&&d.onNext(h);d.onCompleted();f=!1;g++});return new W(l,c)},this)};z.throttle=function(a,e){return this.debounce(a,e)};z.timestamp=function(a){ea(a)||(a=za);return this.map(function(e){return{value:e,timestamp:a.now()}})};z.sample=z.throttleLatest=function(a,e){ea(e)||(e=za);return"number"===typeof a?la(this,fc(a,e)):la(this,a)};z.timeout=function(a,e,b){null!=e&&"string"!==typeof e||(e=bb(Error(e||"Timeout")));ea(b)||(b=za);var d=this,c=a instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new P(function(f){function h(){var d=g;D.setDisposable(b[c](a,function(){g===d&&(ha(e)&&(e=ja(e)),u.setDisposable(e.subscribe(f)))}))}var g=0,l=new T,u=new oa,D=new oa;u.setDisposable(l);h();l.setDisposable(d.subscribe(function(a){g++;f.onNext(a);h()},function(a){g++;f.onError(a)},function(){g++;f.onCompleted()}));return new W(u,D)},d)};z.throttleFirst=function(a,e){ea(e)||(e=za);var b=+a||0;if(0>=b)throw new RangeError("windowDuration cannot be less or equal zero."); var d=this;return new P(function(a){var c=0;return d.subscribe(function(d){var f=e.now();if(0===c||f-c>=b)c=f,a.onNext(d)},function(e){a.onError(e)},function(){a.onCompleted()})},d)};var gc=function(a){function e(a){var e=this.source.publish();a=e.subscribe(a);var b=ka,d=this.pauser.distinctUntilChanged().subscribe(function(a){a?b=e.connect():(b.dispose(),b=ka)});return new W(a,b,d)}function b(d,c){this.source=d;this.controller=new Ba;this.pauser=c&&c.subscribe?this.controller.merge(c):this.controller; a.call(this,e,d)}H(b,a);b.prototype.pause=function(){this.controller.onNext(!1)};b.prototype.resume=function(){this.controller.onNext(!0)};return b}(N);z.pausable=function(a){return new gc(this,a)};var hc=function(a){function e(a){function e(){for(;0<b.length;)a.onNext(b.shift())}var b=[],d;return ta(this.source,this.pauser.startWith(!1).distinctUntilChanged(),function(a,e){return{data:a,shouldFire:e}}).subscribe(function(c){if(void 0!==d&&c.shouldFire!=d)(d=c.shouldFire)&&e();else if(d=c.shouldFire)a.onNext(c.data); else b.push(c.data)},function(b){e();a.onError(b)},function(){e();a.onCompleted()})}function b(d,c){this.source=d;this.controller=new Ba;this.pauser=c&&c.subscribe?this.controller.merge(c):this.controller;a.call(this,e,d)}H(b,a);b.prototype.pause=function(){this.controller.onNext(!1)};b.prototype.resume=function(){this.controller.onNext(!0)};return b}(N);z.pausableBuffered=function(a){return new hc(this,a)};var jc=function(a){function e(a){return this.source.subscribe(a)}function b(d,c,f){a.call(this, e,d);this.subject=new ic(c,f);this.source=d.multicast(this.subject).refCount()}H(b,a);b.prototype.request=function(a){return this.subject.request(null==a?-1:a)};return b}(N),ic=function(a){function e(a){return this.subject.subscribe(a)}function b(d,c){null==d&&(d=!0);a.call(this,e);this.subject=new Ba;this.queue=(this.enableQueue=d)?[]:null;this.requestedCount=0;this.error=this.requestedDisposable=null;this.hasCompleted=this.hasFailed=!1;this.scheduler=c||ra}H(b,a);Ha(b.prototype,Aa,{onCompleted:function(){this.hasCompleted= !0;this.enableQueue&&0!==this.queue.length?this.queue.push(xa.createOnCompleted()):(this.subject.onCompleted(),this.disposeCurrentRequest())},onError:function(a){this.hasFailed=!0;this.error=a;this.enableQueue&&0!==this.queue.length?this.queue.push(xa.createOnError(a)):(this.subject.onError(a),this.disposeCurrentRequest())},onNext:function(a){0>=this.requestedCount?this.enableQueue&&this.queue.push(xa.createOnNext(a)):(0===this.requestedCount--&&this.disposeCurrentRequest(),this.subject.onNext(a))}, _processRequest:function(a){if(this.enableQueue)for(;0<this.queue.length&&(0<a||"N"!==this.queue[0].kind);){var e=this.queue.shift();e.accept(this.subject);"N"===e.kind?a--:(this.disposeCurrentRequest(),this.queue=[])}return a},request:function(a){this.disposeCurrentRequest();var e=this;return this.requestedDisposable=this.scheduler.scheduleWithState(a,function(a,b){var d=e._processRequest(b);if(!e.hasCompleted&&!e.hasFailed&&0<d)return e.requestedCount=d,pa(function(){e.requestedCount=0})})},disposeCurrentRequest:function(){this.requestedDisposable&& (this.requestedDisposable.dispose(),this.requestedDisposable=null)}});return b}(N);z.controlled=function(a,e){a&&ea(a)&&(e=a,a=!0);null==a&&(a=!0);return new jc(this,a,e)};z.pipe=function(a){function e(){b.resume()}var b=this.pausableBuffered();a.addListener("drain",e);b.subscribe(function(e){!a.write(String(e))&&b.pause()},function(e){a.emit("error",e)},function(){!a._isStdio&&a.end();a.removeListener("drain",e)});b.resume();return a};var P=D.AnonymousObservable=function(a){function e(a){return a&& Y(a.dispose)?a:Y(a)?pa(a):ka}function d(a,c){var f=c[0],h=c[1],h=b(h.__subscribe).call(h,f);if(h===J&&!f.fail(J.e))return q(J.e);f.setDisposable(e(h))}function c(a){a=new fb(a);var e=[a,this];ra.scheduleRequired()?ra.scheduleWithState(e,d):d(null,e);return a}function f(e,b){this.source=b;this.__subscribe=e;a.call(this,c)}H(f,a);return f}(N),fb=function(a){function e(e){a.call(this);this.observer=e;this.m=new T}H(e,a);var d=e.prototype;d.next=function(a){a=b(this.observer.onNext).call(this.observer, a);a===J&&(this.dispose(),q(a.e))};d.error=function(a){a=b(this.observer.onError).call(this.observer,a);this.dispose();a===J&&q(a.e)};d.completed=function(){var a=b(this.observer.onCompleted).call(this.observer);this.dispose();a===J&&q(a.e)};d.setDisposable=function(a){this.m.setDisposable(a)};d.getDisposable=function(){return this.m.getDisposable()};d.dispose=function(){a.prototype.dispose.call(this);this.m.dispose()};return e}(Pa),Va=function(a,e){this.subject=a;this.observer=e};Va.prototype.dispose= function(){if(!this.subject.isDisposed&&null!==this.observer){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1);this.observer=null}};var Ba=D.Subject=function(a){function e(a){ia(this);if(!this.isStopped)return this.observers.push(a),new Va(this,a);if(this.hasError)return a.onError(this.error),ka;a.onCompleted();return ka}function b(){a.call(this,e);this.isStopped=this.isDisposed=!1;this.observers=[];this.hasError=!1}H(b,a);Ha(b.prototype,Aa.prototype,{hasObservers:function(){return 0< this.observers.length},onCompleted:function(){ia(this);if(!this.isStopped){this.isStopped=!0;for(var a=0,e=g(this.observers),b=e.length;a<b;a++)e[a].onCompleted();this.observers.length=0}},onError:function(a){ia(this);if(!this.isStopped){this.isStopped=!0;this.error=a;this.hasError=!0;for(var e=0,b=g(this.observers),d=b.length;e<d;e++)b[e].onError(a);this.observers.length=0}},onNext:function(a){ia(this);if(!this.isStopped)for(var e=0,b=g(this.observers),d=b.length;e<d;e++)b[e].onNext(a)},dispose:function(){this.isDisposed= !0;this.observers=null}});b.create=function(a,e){return new kc(a,e)};return b}(N),Ua=D.AsyncSubject=function(a){function e(a){ia(this);if(!this.isStopped)return this.observers.push(a),new Va(this,a);if(this.hasError)a.onError(this.error);else{if(this.hasValue)a.onNext(this.value);a.onCompleted()}return ka}function b(){a.call(this,e);this.hasValue=this.isStopped=this.isDisposed=!1;this.observers=[];this.hasError=!1}H(b,a);Ha(b.prototype,Aa,{hasObservers:function(){ia(this);return 0<this.observers.length}, onCompleted:function(){var a,e;ia(this);if(!this.isStopped){this.isStopped=!0;var b=g(this.observers);e=b.length;if(this.hasValue)for(a=0;a<e;a++){var d=b[a];d.onNext(this.value);d.onCompleted()}else for(a=0;a<e;a++)b[a].onCompleted();this.observers.length=0}},onError:function(a){ia(this);if(!this.isStopped){this.hasError=this.isStopped=!0;this.error=a;for(var e=0,b=g(this.observers),d=b.length;e<d;e++)b[e].onError(a);this.observers.length=0}},onNext:function(a){ia(this);this.isStopped||(this.value= a,this.hasValue=!0)},dispose:function(){this.isDisposed=!0;this.value=this.exception=this.observers=null}});return b}(N),kc=D.AnonymousSubject=function(a){function e(a){return this.observable.subscribe(a)}function b(d,c){this.observer=d;this.observable=c;a.call(this,e)}H(b,a);Ha(b.prototype,Aa.prototype,{onCompleted:function(){this.observer.onCompleted()},onError:function(a){this.observer.onError(a)},onNext:function(a){this.observer.onNext(a)}});return b}(N),lb=D.BehaviorSubject=function(a){function e(a){ia(this); if(!this.isStopped)return this.observers.push(a),a.onNext(this.value),new Va(this,a);if(this.hasError)a.onError(this.error);else a.onCompleted();return ka}function b(d){a.call(this,e);this.value=d;this.observers=[];this.hasError=this.isStopped=this.isDisposed=!1}H(b,a);Ha(b.prototype,Aa,{getValue:function(){ia(this);if(this.hasError)throw this.error;return this.value},hasObservers:function(){return 0<this.observers.length},onCompleted:function(){ia(this);if(!this.isStopped){this.isStopped=!0;for(var a= 0,e=g(this.observers),b=e.length;a<b;a++)e[a].onCompleted();this.observers.length=0}},onError:function(a){ia(this);if(!this.isStopped){this.hasError=this.isStopped=!0;this.error=a;for(var e=0,b=g(this.observers),d=b.length;e<d;e++)b[e].onError(a);this.observers.length=0}},onNext:function(a){ia(this);if(!this.isStopped){this.value=a;for(var e=0,b=g(this.observers),d=b.length;e<d;e++)b[e].onNext(a)}},dispose:function(){this.isDisposed=!0;this.exception=this.value=this.observers=null}});return b}(N), mb=D.ReplaySubject=function(a){function e(a,e){return pa(function(){e.dispose();!a.isDisposed&&a.observers.splice(a.observers.indexOf(e),1)})}function b(a){a=new ub(this.scheduler,a);var d=e(this,a);ia(this);this._trim(this.scheduler.now());this.observers.push(a);for(var c=0,f=this.q.length;c<f;c++)a.onNext(this.q[c].value);if(this.hasError)a.onError(this.error);else if(this.isStopped)a.onCompleted();a.ensureActive();return d}function d(e,f,h){this.bufferSize=null==e?c:e;this.windowSize=null==f?c: f;this.scheduler=h||ra;this.q=[];this.observers=[];this.hasError=this.isDisposed=this.isStopped=!1;this.error=null;a.call(this,b)}var c=Math.pow(2,53)-1;H(d,a);Ha(d.prototype,Aa.prototype,{hasObservers:function(){return 0<this.observers.length},_trim:function(a){for(;this.q.length>this.bufferSize;)this.q.shift();for(;0<this.q.length&&a-this.q[0].interval>this.windowSize;)this.q.shift()},onNext:function(a){ia(this);if(!this.isStopped){var e=this.scheduler.now();this.q.push({interval:e,value:a});this._trim(e); for(var e=0,b=g(this.observers),d=b.length;e<d;e++){var c=b[e];c.onNext(a);c.ensureActive()}}},onError:function(a){ia(this);if(!this.isStopped){this.isStopped=!0;this.error=a;this.hasError=!0;var e=this.scheduler.now();this._trim(e);for(var e=0,b=g(this.observers),d=b.length;e<d;e++){var c=b[e];c.onError(a);c.ensureActive()}this.observers.length=0}},onCompleted:function(){ia(this);if(!this.isStopped){this.isStopped=!0;var a=this.scheduler.now();this._trim(a);for(var a=0,e=g(this.observers),b=e.length;a< b;a++){var d=e[a];d.onCompleted();d.ensureActive()}this.observers.length=0}},dispose:function(){this.isDisposed=!0;this.observers=null}});return d}(N);D.Pauser=function(a){function e(){a.call(this)}H(e,a);e.prototype.pause=function(){this.onNext(!1)};e.prototype.resume=function(){this.onNext(!0)};return e}(Ba);r.exports=D}).call(k,function(){return this}(),c(14))},function(r,k,c){(function(n){function p(a,b,d){var c=3>=arguments.length||void 0===arguments[3]?null:arguments[3];this.name="RequestError"; this.url=a;this.xhr=b;this.code=b.status;this.reason=c;this.message="request: "+d+" ("+a+")";Error.captureStackTrace&&Error.captureStackTrace(this,p)}function g(a,b){var d=b.code,c=b.method,h=b.message;this.name="RestCallMethodError";this.url=a;this.code=d;this.message="restmethodcall: webservice error status "+d+" ("+a+")"+(c?" ("+c+")":"")+(h?"\n"+h:"");Error.captureStackTrace&&Error.captureStackTrace(this,g)}function a(a,b,d){a=a.querySelector("RestCallResult");var c=+a.querySelector("Status").textContent; if(0>c)throw new g(b,{code:c,method:d});return{output:a.querySelector("Output"),status:c}}function b(a){return"rest-call-method"==a.format?d(a):v.create(function(b){function d(a){var c=a.target,f=c.status;if(200>f||300<=f)return b.onError(new p(h,c,c.statusText));var f=Date.now()-r,g;g="document"==q?(new n.DOMParser).parseFromString(c.responseText,"text/xml"):c.response;if("json"==q&&"string"==typeof g)try{g=JSON.parse(g)}catch(l){g=null}if(null==g)return b.onError(new p(h,c,'null response with format "'+ q+'" (error while parsing or wrong content-type)'));if(v){var t;if(w){t=w;for(var k={},G,da=0;da<t.length;da++)G=t[da],k[G]=c.getResponseHeader(G);t=k}b.onNext({blob:g,size:a.total,duration:f,headers:t,url:c.responseURL||h,xhr:c})}else b.onNext(g);b.onCompleted()}function c(a){b.onError(new p(h,a,"error event"))}var h=a.url,g=a.data,l=a.headers,q=a.format,v=a.withMetadata,w=a.responseHeaders,t=new XMLHttpRequest;t.open(a.method||"GET",h,!0);t.responseType="document"==q?"text":q||"text";if(l)for(var k in l)t.setRequestHeader(k, l[k]);t.addEventListener("load",d,!1);t.addEventListener("error",c,!1);var r=Date.now();t.send(g);return function(){var a=t.readyState;0<a&&4>a&&(t.removeEventListener("load",d),t.removeEventListener("error",c),t.abort());t=null}})}function q(a){return(a||"").toString().replace(w,function(a){return l[a]})}function t(a){var b="",d;for(d in a)var c=a[d],c="object"==typeof c?t(c):q(c),b=b+("<"+d+">"+c+"</"+d+">");return b}function d(d){d.method="POST";d.headers={"Content-Type":"application/xml"};d.data= h.replace("{payload}",t(d.data));d.format="document";return b(d).map(function(b){return a(b,d.url,d.ScriptInfo)})}var v=c(3).Observable;p.prototype=Error();g.prototype=Error();var w=/[&<>]/g,l={"&":"&amp;","<":"&lt;",">":"&gt;"},h='<RestCallMethod xmlns:i="http://www.w3.org/2001/XMLSchema-instance">{payload}</RestCallMethod>';b.escapeXml=q;b.RequestError=p;b.RestCallMethodError=g;b.RestCallResult=a;b.getNodeTextContent=function(a,b){var d=a.querySelector(b);return d&&d.textContent};r.exports=b}).call(k, function(){return this}())},function(r,k){function c(){q=!1;t.length?b=t.concat(b):d=-1;b.length&&n()}function n(){if(!q){var a=setTimeout(c);q=!0;for(var g=b.length;g;){t=b;for(b=[];++d<g;)t&&t[d].run();d=-1;g=b.length}t=null;q=!1;clearTimeout(a)}}function p(a,b){this.fun=a;this.array=b}function g(){}var a=r.exports={},b=[],q=!1,t,d=-1;a.nextTick=function(a){var d=Array(arguments.length-1);if(1<arguments.length)for(var c=1;c<arguments.length;c++)d[c-1]=arguments[c];b.push(new p(a,d));1!==b.length|| q||setTimeout(n,0)};p.prototype.run=function(){this.fun.apply(null,this.array)};a.title="browser";a.browser=!0;a.env={};a.argv=[];a.version="";a.versions={};a.on=g;a.addListener=g;a.once=g;a.off=g;a.removeListener=g;a.removeAllListeners=g;a.emit=g;a.binding=function(a){throw Error("process.binding is not supported");};a.cwd=function(){return"/"};a.chdir=function(a){throw Error("process.chdir is not supported");};a.umask=function(){return 0}},function(r,k,c){function n(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function"); }function p(a){var b=[],d="optional",c="optional";a.persistentLicense?(d="required",b.push("persistent-license")):b.push("temporary");a.persistentStateRequired&&(d="required");a.distinctiveIdentifierRequired&&(c="required");return{videoCapabilities:void 0,audioCapabilities:void 0,initDataTypes:["cenc"],distinctiveIdentifier:c,persistentState:d,sessionTypes:b}}function g(a){if(U&&X&&!X.alwaysRenew){var b=w.find(a,function(a){return a.type==U.type&&a.persistentLicense==U.persistentLicense&&a.persistentStateRequired=== U.persistentStateRequired&&a.distinctiveIdentifierRequired==U.distinctiveIdentifierRequired});if(b)return l.debug("eme: found compatible keySystem quickly",b),K({keySystem:b,keySystemAccess:aa})}var d=w.flatten(a,function(a){return w.map(ca[a.type],function(b){return{keyType:b,keySystem:a}})});return y.create(function(a){function b(f){if(!c)if(f>=d.length)a.onError(Error("eme: could not find a compatible key system"));else{var h=d[f],g=h.keyType,q=h.keySystem,v=[p(q)];l.debug("eme: request keysystem access "+ g+","+(f+1+" of "+d.length),v);x(g,v).then(function(b){l.info("eme: found compatible keysystem",g,v);a.onNext({keySystem:q,keySystemAccess:b});a.onCompleted()},function(){l.debug("eme: rejected access to keysystem",g,v);b(f+1)})}}var c=!1;b(0);(function(){return c=!0})})}function a(a,b,d){return F(d.createMediaKeys().then(function(d){X=d;U=b;l.debug("eme: set mediakeys");return I(a,d).then(function(){return d})}))}function b(a,b,d){l.debug("eme: generate request",b,d);return F(a.generateRequest(b, d).then(function(){return a}))}function q(a,b){l.debug("eme: load persisted session",b);return F(a.load(b).then(function(){return a}))}function t(a,b){var d=Error(a);b&&(d.reason=b);l.error(a,b);throw d;}function d(a){return w.isPromise(a)?F(a):w.isObservable(a)?a:K(a)}function v(c,f){function h(b,d){var f=d.keySystem,g=d.keySystemAccess;f.persistentLicense&&Z.setStorage(f.licenseStorage);var q=new Uint8Array(b.initData),t=b.initDataType;l.info("eme: encrypted event",b);return a(c,f,g).flatMap(function(a){return v(a, f,t,q).tap(function(a){Z.add(q,a);V.add(a)},function(a){l.error("eme: error during session management handler",a)})}).flatMap(function(a){return u(a,f).tapOnError(function(b){l.error("eme: error in session messages handler",a,b);Z["delete"](q,a);V["delete"](a.sessionId)})})}function v(a,d,c,f){var h=Z.get(f),g=V.get(h);if(g)return l.debug("eme: reuse loaded session",h),K(g);var u=void 0,u=d.persistentLicense?"persistent-license":"temporary";l.debug("eme: create a "+u+" session");g=a.createSession(u); return d.persistentLicense&&h?q(g,h)["catch"](function(d){l.warn("eme: failed to load persisted session, do fallback",h,d);Z["delete"](f,null);return F(V["delete"](h)).flatMap(function(){g=a.createSession(u);return b(g,c,f)})}):b(g,c,f)["catch"](function(d){var h=V.getFirst();if(!h)throw d;l.warn("eme: could not create a new session, retry after closing a currently loaded session",d);return F(h.close()).flatMap(function(){g=a.createSession(u);return b(g,c,f)})})}function u(a,b){var c=void 0,f=Q(a).map(function(a){return t("eme: keyerror event "+ a.errorCode+" / "+a.systemCode,a)}),h=O(a).flatMap(function(f){c=f.sessionId;l.debug("eme: keystatuseschange event",c,a,f);for(var h=a.keyStatuses.values(),g=h.next();!g.done;g=h.next())(g=M[g.value])&&t(g);if(!b.onKeyStatusesChange)return l.warn("eme: keystatuseschange event not handled"),B();h=void 0;try{h=b.onKeyStatusesChange(f,a)}catch(u){h=y["throw"](u)}return d(h)["catch"](function(a){return t("eme: onKeyStatusesChange has failed (reason: "+(a&&a.message||"unknown")+")",a)})}),g=S(a).flatMap(function(f){c= f.sessionId;var h=f.message,g=f.messageType;g||(g="license-request");l.debug("eme: event message type "+g,a,f);f=void 0;try{f=b.getLicense(new Uint8Array(h),g)}catch(u){f=y["throw"](u)}return d(f)["catch"](function(a){return t("eme: getLicense has failed (reason: "+(a&&a.message||"unknown")+")",a)})}),h=E(g,h).concatMap(function(b){l.debug("eme: update session",c,b);return a.update(b,c)["catch"](function(a){return t("eme: error on session update "+c,a)})}).map(function(){return{type:"eme",value:{session:a, name:"session-updated"}}});return E(h,f)}return y.create(function(a){var b=G(L(c),g(f),h).take(1).mergeAll().subscribe(a);return function(){b&&b.dispose();I(c,null)["catch"](function(a){return l.warn(a)})}})}var w=c(1),l=c(4),h=c(6),f=c(2),y=c(3).Observable,G=y.combineLatest,B=y.empty,F=y.fromPromise,E=y.merge,K=y.just;k=c(8);var x=k.requestMediaKeySystemAccess,I=k.setMediaKeys;k=k.emeEvents;var L=k.onEncrypted,S=k.onKeyMessage,Q=k.onKeyError,O=k.onKeyStatusesChange,ca={clearkey:["webkit-org.w3.clearkey", "org.w3.clearkey"],widevine:["com.widevine.alpha"],playready:["com.youtube.playready","com.microsoft.playready"]},M={"output-not-allowed":"eme: the required output protection is not available.",expired:"eme: a required key has expired and the content cannot be decrypted.","internal-error":"eme: an unknown error has occurred in the CDM."};k=function(){function a(){n(this,a);this._hash={}}a.prototype.getFirst=function(){for(var a in this._hash)return this._hash[a]};a.prototype.get=function(a){return this._hash[a]}; a.prototype.add=function(a){var b=this,d=a.sessionId;f(d);this._hash[d]||(l.debug("eme-store: add persisted session in store",d),this._hash[d]=a,a.closed.then(function(){l.debug("eme-store: remove persisted session from store",d);delete b._hash[d]}))};a.prototype["delete"]=function(a){var b=this._hash[a];return b?(delete this._hash[a],b.close()):h.resolve()};a.prototype.dispose=function(){var a=[],b;for(b in this._hash)a.push(this._hash[b].close());this._hash={};return h.all(a)};return a}();var Z= new (function(){function a(b){n(this,a);this.setStorage(b)}a.prototype.setStorage=function(a){if(this._storage!==a){f(a,"eme: no licenseStorage given for keySystem with persistentLicense");f.iface(a,"licenseStorage",{save:"function",load:"function"});this._storage=a;try{this._entries=this._storage.load(),f(Array.isArray(this._entries))}catch(b){l.warn("eme-store: could not get entries from license storage",b),this.dispose()}}};a.prototype.hashInitData=function(a){if("number"==typeof a)return a;for(var b= 0,d=void 0,c=0;c<a.length;c++)d=a[c],b=(b<<5)-b+d,b&=b;return b};a.prototype.get=function(a){a=this.hashInitData(a);var b=w.find(this._entries,function(b){return b.initData===a});if(b)return b.sessionId};a.prototype.add=function(a,b){a=this.hashInitData(a);if(!this.get(a)){var d=b.sessionId;f(d);l.info("eme-store: store new session",d,b);this._entries.push({sessionId:d,initData:a});this._save()}};a.prototype["delete"]=function(a,b){a=this.hashInitData(a);var d=w.find(this._entries,function(b){return b.initData=== a});d&&(l.warn("eme-store: delete session from store",d.sessionId),d=this._entries.indexOf(d),this._entries.splice(d,1),this._save());b&&(l.warn("eme-store: remove session from system",b.sessionId),b.remove())};a.prototype.dispose=function(){this._entries=[];this._save()};a.prototype._save=function(){try{this._storage.save(this._entries)}catch(a){l.warn("eme-store: could not save licenses in localStorage")}};return a}())({load:function(){return[]},save:function(){}}),V=new k,aa={createMediaKeys:function(){return h.resolve(X)}}, X=void 0,U=void 0;v.onEncrypted=L;v.getCurrentKeySystem=function(){return U&&U.type};v.dispose=function(){U=X=null;V.dispose()};r.exports=v},function(r,k,c){function n(a){this.name="OutOfIndexError";this.type=a;this.message="out of range in index "+a}function p(c){switch(c.indexType){case "template":return g;case "timeline":return a;case "list":return b;case "base":return q;default:throw Error("index-handler: unrecognized indexType "+c.indexType);}}c(2);var g=c(30),a=c(17),b=c(29),q=c(28);n.prototype= Error();k=function(){function a(b,c){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.adaptation=b;this.representation=c;this.index=c.index;this.handler=new (p(this.index))(this.index)}a.prototype.getInitSegment=function(){var a=this.index.initialization||{};return{id:"init_"+this.adaptation.id+"_"+this.representation.id,init:!0,media:a.media,range:a.range,indexRange:this.index.indexRange}};a.prototype.normalizeRange=function(a,b,c){var g=this.index.presentationTimeOffset|| 0,h=this.index.timescale||1;b||(b=0);c||(c=0);b=Math.min(b,c);return{time:a*h-g,up:(a+b)*h-g,to:(a+c)*h-g}};a.prototype.getSegments=function(a,b,c){a=this.normalizeRange(a,b,c);b=a.up;c=a.to;if(!this.handler.checkRange(a.time))throw new n(this.index.indexType);return this.handler.getSegments(b,c)};a.prototype.insertNewSegments=function(a,b){for(var c=[],g=0;g<a.length;g++)this.handler.addSegment(a[g],b)&&c.push(a[g]);return c};a.prototype.setTimescale=function(a){var b=this.index;return b.timescale!== a?(b.timescale=a,!0):!1};a.prototype.scale=function(a){return a/this.index.timescale};return a}();r.exports={OutOfIndexError:n,IndexHandler:k,getLiveEdge:function(a){var b=a.adaptations.video[0].representations[0].index;return p(b).getLiveEdge(b,a)}}},function(r,k,c){function n(c){var a=c.ts,b=c.d;c=c.r;return-1===b?a:a+(c+1)*b}var p=c(1);k=function(){function c(a){if(!(this instanceof c))throw new TypeError("Cannot call a class as a function");this.index=a;this.timeline=a.timeline}c.getLiveEdge= function(a,b){var c=n(p.last(a.timeline))/a.timescale-b.suggestedPresentationDelay;return Math.max(a.timeline[0].ts/a.timescale+1,c)};c.prototype.createSegment=function(a,b,c){return{id:a,media:this.index.media,time:a,number:void 0,range:b,duration:c}};c.prototype.calculateRepeat=function(a,b){var c=a.r||0;0>c&&(c=Math.ceil(((b?b.t:Infinity)-a.ts)/a.d)-1);return c};c.prototype.checkRange=function(a){var b=p.last(this.timeline);if(!b)return!0;0>b.d&&(b={ts:b.ts,d:0,r:b.r});return a<=n(b)};c.prototype.getSegmentIndex= function(a){for(var b=this.timeline,c=0,g=b.length;c<g;){var d=c+g>>>1;b[d].ts<a?c=d+1:g=d}return 0<c?c-1:c};c.prototype.getSegmentNumber=function(a,b,c){a=b-a;return 0<a?Math.floor(a/c):0};c.prototype.getSegments=function(a,b){var c=this.index.timeline,g=[],d=c.length,v=this.getSegmentIndex(a)-1,n=c.length&&c[0].d||0;a:for(;!(++v>=d);){var l=c[v],h=l.d,f=l.ts,p=l.range,n=Math.max(n,h);if(0>h){f+n<b&&g.push(this.createSegment(f,p,void 0));break}for(var l=this.calculateRepeat(l,c[v+1]),k=this.getSegmentNumber(f, a,h),B;(B=f+k*h)<b;)if(k++<=l)g.push(this.createSegment(B,p,h));else continue a;break}return g};c.prototype.addSegment=function(a,b){var c=this.timeline,g=c.length,d=c[g-1];if(b&&a.ts===b.ts){var v=a.ts+a.d,p=v-(d.ts+d.d*d.r);if(0>=p)return!1;-1===d.d&&((g=c[g-2])&&g.d===p?(g.r++,c.pop()):d.d=p);c.push({d:-1,ts:v,r:0});return!0}return a.ts>=n(d)?(d.d===a.d?d.r++:c.push({d:a.d,ts:a.ts,r:0}),!0):!1};return c}();r.exports=k},function(r,k,c){function n(a,d,c){a.id=a.id||b.uniqueId();var g=a.adaptations, g=g.concat(c||[]),g=b.map(g,function(a){return p(a,d)}),g=b.filter(g,function(a){return 0>l.indexOf(a.type)?(q.warn("not supported adaptation type",a.type),!1):!0});t(0<g.length);a.adaptations=b.groupBy(g,"type");return a}function p(d,c){t("undefined"!=typeof d.id);b.defaults(d,c);var g=b.pick(d,w),l=b.map(d.representations,function(a){t("undefined"!=typeof a.id);b.defaults(a,g);var d=a.index;t(d);d.timescale||(d.timescale=1);a.bitrate||(a.bitrate=1);"mp4a.40.02"==a.codecs&&(a.codecs="mp4a.40.2"); return a}).sort(function(a,b){return a.bitrate-b.bitrate}),q=d.type,n=d.mimeType;n||(n=l[0].mimeType);t(n);d.mimeType=n;q||(q=d.type=n.split("/")[0]);if("video"==q||"audio"==q)l=b.filter(l,function(b){return v(a(b))});t(0<l.length,"manifest: no compatible representation for this adaptation");d.representations=l;d.bitrates=b.pluck(l,"bitrate");return d}function g(a){b.isArray(a)||(a=[a]);return b.flatten(a,function(a){var d=a.mimeType,c=a.url,h=a.language;a=a.languages;h&&(a=[h]);return b.map(a,function(a){return{id:b.uniqueId(), type:"text",lang:a,mimeType:d,rootURL:c,baseURL:"",representations:[{id:b.uniqueId(),mimeType:d,index:{indexType:"template",duration:Number.MAX_VALUE,timescale:1,startNumber:0}}]}})})}function a(a){return a.mimeType+';codecs="'+a.codecs+'"'}var b=c(1),q=c(4),t=c(2),d=c(11).parseBaseURL,v=c(8).isCodecSupported,w="profiles width height frameRate audioSamplingRate mimeType segmentProfiles codecs maximumSAPPeriod maxPlayoutRate codingDependency index".split(" "),l=["audio","video","text"];r.exports={normalizeManifest:function(a, c,l){t(c.transportType);c.id=c.id||b.uniqueId();c.type=c.type||"static";var q=c.locations;q&&q.length||(c.locations=[a]);c.isLive="dynamic"==c.type;var v={rootURL:d(c.locations[0]),baseURL:c.baseURL,isLive:c.isLive};l&&(l=g(l));a=b.map(c.periods,function(a){return n(a,v,l)});b.extend(c,a[0]);c.periods=null;c.duration||(c.duration=Infinity);c.isLive&&(c.suggestedPresentationDelay=c.suggestedPresentationDelay||15,c.availabilityStartTime=c.availabilityStartTime||0);return c},mergeManifestsIndex:function(a, d){var c=a.adaptations,g=d.adaptations,l;for(l in c){var q=g[l];b.each(c[l],function(a,d){b.simpleMerge(a.index,q[d].index)})}return a},mutateManifestLiveGap:function(a){var b=1>=arguments.length||void 0===arguments[1]?1:arguments[1];a.isLive&&(a.presentationLiveGap+=b)},getCodec:a,getAdaptations:function(d){var c=d.adaptations,g=[];b.each(b.keys(c),function(b){var d=c[b];g.push({type:b,adaptations:d,codec:a(d[0].representations[0])})});return g},getAvailableSubtitles:function(a){return b.pluck(a.adaptations.text, "lang")},getAvailableLanguages:function(a){return b.pluck(a.adaptations.audio,"lang")}}},function(r,k,c){function n(a,b){var c=a.playbackRate,n=a.duration,d=a.currentTime,v=a.readyState,p=new g(a.buffered),l=p.getRange(d),h=p.getGap(d);return{name:b,ts:d,range:l,gap:h,duration:n,playback:c,readyState:v,stalled:null,buffered:p}}var p=c(3).Observable,g=c(9).BufferedRanges;r.exports={timingsSampler:function(a){return p.create(function(b){function c(d){var q=g,l=d&&d.type||"timeupdate";d=n(a,l);var q= q.stalled,h=d.gap;(l="loadedmetadata"==l||q)||(l=(l=d.range)?.5>=d.duration-(h+l.end):!1);d.stalled=l||!(.5>=h||Infinity===h)?q&&Infinity>h&&h>("seeking"==q.name?.5:5)?null:q:{name:d.name,playback:d.playback};g=d;b.onNext(g)}var g=n(a,"init"),d=setInterval(c,1E3);a.addEventListener("play",c);a.addEventListener("progress",c);a.addEventListener("seeking",c);a.addEventListener("seeked",c);a.addEventListener("loadedmetadata",c);b.onNext(g);return function(){clearInterval(d);a.removeEventListener("play", c);a.removeEventListener("progress",c);a.removeEventListener("seeking",c);a.removeEventListener("seeked",c);a.removeEventListener("loadedmetadata",c)}}).shareValue({name:"init",stalled:null})},seekingsSampler:function(a){return a.filter(function(a){return"seeking"==a.name&&(Infinity===a.gap||-2>a.gap)}).skip(1).startWith(!0)},getLiveGap:function(a,b){if(!b.isLive)return Infinity;var c=b.availabilityStartTime,g=b.presentationLiveGap;return Date.now()/1E3-a-(c+g+10)},toWallClockTime:function(a,b){return new Date(1E3* (a+b.availabilityStartTime))},fromWallClockTime:function(a,b){var c=a,g=b.suggestedPresentationDelay,d=b.presentationLiveGap,n=b.timeShiftBufferDepth;"number"!=typeof c&&(c=c.getTime());var p=Date.now(),n=p-1E3*n;return Math.max(Math.min(c,p-1E3*(d+g)),n)/1E3-b.availabilityStartTime}}},function(r,k){function c(c){var p=.3*(2*Math.random()-1);return c*(1+p)}r.exports={getFuzzedDelay:c,getBackedoffDelay:function(n){return c(n*Math.pow(2,(1>=arguments.length||void 0===arguments[1]?1:arguments[1])-1))}}}, function(r,k){r.exports=function(c,n,p){function g(){var a=q-Date.now();if(0<a)b=setTimeout(g,a);else switch(b=null,k.length){case 0:return c();case 1:return c(k[0]);case 2:return c(k[0],k[1]);case 3:return c(k[0],k[1],k[2]);default:return c.apply(null,k)}}function a(){var c=arguments.length,l=0;for(k=Array(c);l<c;l++)k[l]=arguments[l];if(d&&!v)return v=!0,q=Date.now(),g();c=q;q=Date.now()+n;if(!b||q<c)b&&clearTimeout(b),b=setTimeout(g,n);return a}var b=null,q=0,k=[],d=!(!p||!p.leading),v=!1;a.isWaiting= function(){return!!b};a.dispose=function(){b&&(clearTimeout(b),b=null)};return a}},function(r,k){r.exports=function(c){c.webpackPolyfill||(c.deprecate=function(){},c.paths=[],c.children=[],c.webpackPolyfill=1);return c}},function(r,k){function c(c){return function(p,g){return null==p?g:c*g+(1-c)*p}}r.exports=function(n,p){return n.map(function(c){return c.value.response}).filter(function(c){return 2E3<c.size}).map(function(c){return c.size/c.duration*8E3}).scan(c(p.alpha))}},function(r,k,c){function n(a, b){return"number"==typeof a&&0<a?a:b}function p(a,b){var d=2>=arguments.length||void 0===arguments[2]?0:arguments[2];return q.findLast(a,function(a){return a/b<=1-d})||a[0]}function g(a,b){var d=q.find(a,function(a){return a.width>=b});return d?d.bitrate:Infinity}function a(a,b){return b?q.find(a,function(a){return a.lang===b}):null}function b(a,b){return a.filter(function(a){return a.type===b})}var q=c(1),t=c(4);k=c(3);var d=k.BehaviorSubject,v=k.CompositeDisposable,w=k.Observable.combineLatest, l=c(5).only,h=c(23),f={defLanguage:"fra",defSubtitle:"",defBufSize:30,defBufThreshold:.3};r.exports=function(c,k,B){function r(b){return M.changes().map(function(d){return a(b,d)||b[0]})}function E(b){return Z.changes().map(function(d){return a(b,d)})}var K=q.defaults(3>=arguments.length||void 0===arguments[3]?{}:arguments[3],f),x=K.defSubtitle,I=K.defBufSize,L=K.defBufThreshold,S=K.initVideoBitrate,Q=K.initAudioBitrate,O=B.videoWidth,ca=B.inBackground,M=new d(K.defLanguage),Z=new d(x),V={audio:h(b(c, "audio"),{alpha:.6}).publishValue(Q||0),video:h(b(c,"video"),{alpha:.6}).publishValue(S||0)},aa=new v(q.map(q.values(V),function(a){return a.connect()})),X={audio:new d(Infinity),video:new d(Infinity)},U={audio:new d(Infinity),video:new d(Infinity)},R={audio:new d(I),video:new d(I),text:new d(I)};return{setLanguage:function(a){M.onNext(a)},setSubtitle:function(a){Z.onNext(a)},getLanguage:function(){return M.value},getSubtitle:function(){return Z.value},getAverageBitrates:function(){return V},getAudioMaxBitrate:function(){return U.audio.value}, getVideoMaxBitrate:function(){return U.video.value},getAudioBufferSize:function(){return R.audio.value},getVideoBufferSize:function(){return R.video.value},setAudioBitrate:function(a){X.audio.onNext(n(a,Infinity))},setVideoBitrate:function(a){X.video.onNext(n(a,Infinity))},setAudioMaxBitrate:function(a){U.audio.onNext(n(a,Infinity))},setVideoMaxBitrate:function(a){U.video.onNext(n(a,Infinity))},setAudioBufferSize:function(a){R.audio.onNext(n(a,I))},setVideoBufferSize:function(a){R.video.onNext(n(a, I))},getBufferAdapters:function(a){var b=a.type,c=a.bitrates,f=a.representations;a=f[0];if(1<f.length){a=X[b];var h=U[b],n=V[b].map(function(a,b){return p(c,a,0===b?0:L)}).changes().customDebounce(2E3,{leading:!0});"video"==b&&(h=w(h,O,ca,function(a,b,d){if(d)return c[0];b=g(f,b);return b<a?b:a}));a=w(a,h,n,function(a,b,d){return Infinity>a?a:Infinity>b?Math.min(b,d):d}).map(function(a){return q.find(f,function(b){return b.bitrate===p(c,a)})}).changes(function(a){return a.id}).tap(function(a){return t.info("bitrate", b,a.bitrate)})}else a=l(a);return{representations:a,bufferSizes:R[b]||new d(I)}},getAdaptationsChoice:function(a,b){if("audio"==a)return r(b);if("text"==a)return E(b);if(1==b.length)return l(b[0]);throw Error("adaptive: unknown type "+a+" for adaptation chooser");},dispose:function(){aa&&(aa.dispose(),aa=null)}}}},function(r,k,c){var n=c(1),p=c(4);c(2);var g=c(9).BufferedRanges;k=c(3);var a=k.Observable,b=k.Subject,q=a.combineLatest,t=a.defer,d=a.empty,v=a.from,w=a.just,l=a.merge,h=a.timer;k=c(5); var f=k.first,y=k.on,G=c(46).ArraySet;c=c(16);var B=c.IndexHandler,F=c.OutOfIndexError;r.exports=function(a){function c(a){L.appendBuffer(a);return f(la)}function k(a){return t(function(){return L.updating?f(la).flatMap(function(){return c(a)}):c(a)})}function r(a){function b(d){if(t.test(d.id))return!1;if(d.init||null==d.time)return!0;var c=f.scale(d.time);d=f.scale(d.duration);return(c=da.hasRange(c,d))?1.5*c.bitrate<a.bitrate:!0}function c(b,d,g,h){var l=[];h&&(p.debug("add init segment",M),l.push(f.getInitSegment())); if(0===d.readyState)return l;h=d.ts;d=Math.max(0,Math.min(g,d.liveGap,(d.duration||Infinity)-h));b=b.getGap(h);b=b>aa&&Infinity>b?Math.min(b,X):0;(g=da.getRange(h))&&g.bitrate===a.bitrate&&(g=Math.floor(g.end-h),g>b&&(b=g));h=f.getSegments(h,b,d);return l.concat(h)}var f=new B(S,a),t=new G,y=q(ca,R,ta,function(a,b){return{timing:a,bufferSize:b}}).flatMap(function(f,h){var l=f.timing,q=f.bufferSize,k=new g(L.buffered);Z&&!da.equals(k)&&(p.debug("intersect new buffer",M),da.intersect(k));var aa;try{aa= c(k,l,q,0===h),aa=n.filter(aa,b)}catch(y){if(y instanceof F)return V.onNext({type:"out-of-index",value:y}),d();throw y;}return v(n.map(aa,function(b){t.add(b.id);return{adaptation:S,representation:a,segment:b}}))}).concatMap(Q).concatMap(function(a){return k(a.parsed.blob).map(a)}).map(function(b){var d=b.parsed;t.remove(b.segment.id);var c=d.timescale;c&&f.setTimescale(c);c=d.nextSegments;d=d.currentSegment;c=c?f.insertNewSegments(c,d):[];d&&da.insert(a.bitrate,f.scale(d.ts),f.scale(d.ts+d.d));return{type:"segment", value:n.extend({addedSegments:c},b)}});return l(y,V)["catch"](function(b){if(412!==b.code)throw b;return w({type:"precondition-failed",value:b}).concat(h(2E3)).concat(r(a))})}var L=a.sourceBuffer,S=a.adaptation,Q=a.pipeline,O=a.adapters,ca=a.timings;a=a.seekings;var M=S.type,Z="audio"==M||"video"==M,V=new b,aa="video"==M?4:1,X="video"==M?6:1,U=O.representations,R=O.bufferSizes,da=new g,la=l(y(L,"update"),y(L,"error").map(function(a){p.error("buffer: error event",a);throw Error("buffer: error event"); })).share(),ta=la.ignoreElements().startWith(!0);return q(U,a,n.identity).flatMapLatest(r)}},function(r,k){var c=function(){function c(){if(!(this instanceof c))throw new TypeError("Cannot call a class as a function");this.cache={}}c.prototype.add=function(c,g){var a=c.segment;a.init&&(this.cache[a.id]=g)};c.prototype.get=function(c){c=c.segment;return c.init&&(c=this.cache[c.id],null!=c)?c:null};return c}();r.exports={InitializationSegmentCache:c}},function(r,k,c){k=c(3).Observable;var n=k.merge, p=k.interval;c=c(8);var g=c.visibilityChange,a=c.videoSizeChange,b=window.devicePixelRatio||1;r.exports=function(c){var k=g().filter(function(a){return!1===a}),d=g().customDebounce(6E4).filter(function(a){return!0===a}),k=n(k,d).startWith(!1);return{videoWidth:n(p(2E4),a().customDebounce(500)).startWith("init").map(function(){return c.clientWidth*b}).changes(),inBackground:k}}},function(r,k,c){function n(c,g){if("function"!==typeof g&&null!==g)throw new TypeError("Super expression must either be null or a function, not "+ typeof g);c.prototype=Object.create(g&&g.prototype,{constructor:{value:c,enumerable:!1,writable:!0,configurable:!0}});g&&(Object.setPrototypeOf?Object.setPrototypeOf(c,g):c.__proto__=g)}k=function(c){function g(a){if(!(this instanceof g))throw new TypeError("Cannot call a class as a function");c.call(this,a)}n(g,c);g.getLiveEdge=function(){throw Error("not implemented");};g.prototype.addSegment=function(a){this.index.timeline.push(a);return!0};return g}(c(17));r.exports=k},function(r,k){var c=function(){function c(k){if(!(this instanceof c))throw new TypeError("Cannot call a class as a function");this.index=k}c.getLiveEdge=function(){throw Error("not implemented");};c.prototype.checkRange=function(c){var g=this.index,a=g.list;c=Math.floor(c/g.duration);return 0<=c&&c<a.length};c.prototype.createSegment=function(c,g){var a=this.index.list[c];return{id:c,media:a.media,time:g,number:void 0,range:a.range,duration:this.index.duration}};c.prototype.getSegments=function(c,g){for(var a=this.index.duration,b=Math.floor(c/a),k=Math.floor(g/ a),n=[];b<k;)n.push(this.createSegment(b,b*a)),b++;return n};c.prototype.addSegment=function(){return!1};return c}();r.exports=c},function(r,k){var c=function(){function c(k){if(!(this instanceof c))throw new TypeError("Cannot call a class as a function");this.index=k}c.getLiveEdge=function(c,g){return Date.now()/1E3-g.availabilityStartTime-g.suggestedPresentationDelay};c.prototype.checkRange=function(){return!0};c.prototype.createSegment=function(c){var g=this.index,a=g.startNumber,g=g.duration; null==a&&(a=1);c=Math.floor(c/g)+a;return{id:c,media:this.index.media,time:c*g,number:c,range:void 0,duration:this.index.duration}};c.prototype.getSegments=function(c,g){for(var a=this.index.duration,b=[],k=c;k<=g;k+=a)b.push(this.createSegment(k));return b};c.prototype.addSegment=function(){return!1};return c}();r.exports=c},function(r,k,c){function n(d,c,g){function l(a){return f(a).simpleTimeout(r,"timeout").map(function(b){b=p.extend({response:b},a);F.add(a,b);g.onNext({type:d,value:b});return b})} var h=c.resolver,f=c.loader,k=c.parser,n=3>=arguments.length||void 0===arguments[3]?{}:arguments[3];k||(k=q);f||(f=q);h||(h=q);var n=p.defaults(n,{totalRetry:3,timeout:1E4,cache:t}),r=n.timeout,F=n.cache,E={retryDelay:500,totalRetry:n.totalRetry,shouldRetry:function(a){return 500<=a.code||200>a.code||/timeout/.test(a.message)||/request: error event/.test(a.message)}};return function(d){return h(d).flatMap(function(d){var c=a(function(){return l(d)},E),f=F.get(d);return p.isPromise(f)?b(f)["catch"](c): null===f?c():q(f)}).flatMap(function(a){return k(a).map(function(b){return p.extend({parsed:b},a)})})}}var p=c(1);k=c(3);var g=k.Subject;k=k.Observable;var a=c(5).retryWithBackoff,b=k.fromPromise,q=k.just,t={add:function(){},get:function(){return null}};r.exports=function(){var a=new g;return{createPipelines:function(b,c){c=c||{};var g=[],h;for(h in b)g[h]=n(h,b[h],a,c[h]);return g},metrics:a}}},function(r,k,c){function n(a,b){if("function"!==typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+ typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function p(a){B(a.man,"player: no manifest loaded")}function g(a,b){return a.filter(function(a){return a.type==b}).pluck("value")}var a=c(6),b=c(1),q=c(4);k=c(3);var t=k.CompositeDisposable,d=k.BehaviorSubject,v=k.Observable,w=k.Subject,l=v.combineLatest,h=v.defer,f=v.zip,y=c(5).on;k=c(10);var G=c(47),B=c(2),v=c(8), F=v.HTMLVideoElement_,E=v.exitFullscreen,K=v.requestFullscreen,x=v.isFullscreen,I=v.onFullscreenChange,v=c(19),L=v.timingsSampler,S=v.toWallClockTime,Q=v.fromWallClockTime,O=v.getLiveGap,ca=c(26).InitializationSegmentCache,M=c(9).BufferedRanges,Z=c(36).parseTimeFragment,V=c(27),aa=c(18),X=c(40),U=c(31),R=c(24),da=c(34),la=c(15);c=function(c){function u(a){var b=this;if(!(this instanceof u))throw new TypeError("Cannot call a class as a function");var f=a.videoElement,g=a.transport,h=a.transportOptions, l=a.initVideoBitrate;a=a.initAudioBitrate;c.call(this);this.defaultTransport=g;this.defaultTransportOptions=h||{};f||(f=document.createElement("video"));B(f instanceof F,"requires an actual HTMLVideoElement");f.preload="auto";this.version="1.3.0";this.video=f;this.fullscreen=I(f).subscribe(function(){return b.trigger("fullscreenChange",b.isFullscreen())});this.playing=new d;this.stream=new w;var h=U(),g=h.createPipelines,h=h.metrics,k=L(f),f=V(f);this.createPipelines=g;this.metrics=h;this.timings= k;this.adaptive=R(h,k,f,{initVideoBitrate:l,initAudioBitrate:a});this.muted=.1;this._setState("STOPPED");this.resetStates();this.log=q}n(u,c);u.prototype.resetStates=function(){this.man=null;this.reps={video:null,audio:null,text:null};this.adas={video:null,audio:null,text:null};this.evts={};this.frag={start:null,end:null}};u.prototype._clear=function(){this.subscriptions&&(this.subscriptions.dispose(),this.subscriptions=null)};u.prototype.stop=function(){"STOPPED"!==this.state&&(this.resetStates(), this._clear(),this._setState("STOPPED"))};u.prototype.dispose=function(){this.stop();this.metrics.dispose();this.adaptive.dispose();this.fullscreen.dispose();this.stream.dispose();this.video=this.createPipelines=this.timings=this.stream=this.fullscreen=this.adaptive=this.metrics=null};u.prototype.__recordState=function(a,b){this.evts[a]!==b&&(this.evts[a]=b,this.trigger(a+"Change",b))};u.prototype._parseOptions=function(a){var d=b.defaults(b.cloneObject(a),{transport:this.defaultTransport,transportOptions:{}, keySystems:[],timeFragment:{},subtitles:[],autoPlay:!1,directFile:!1}),c=d.transport,f=d.transportOptions,g=d.url,h=d.manifests,l=d.keySystems,u=d.timeFragment,k=d.subtitles,n=d.autoPlay,d=d.directFile,u=Z(u);B(!!h^!!g,"player: you have to pass either a url or a list of manifests");h&&(l=h[0],g=l.url,k=l.subtitles||[],l=b.compact(b.pluck(h,"keySystem")));b.isString(c)&&(c=X[c]);b.isFunction(c)&&(c=c(b.defaults(f,this.defaultTransportOptions)));B(c,"player: transport "+a.transport+" is not supported"); d&&(d={isLive:!1,duration:Infinity});return{url:g,keySystems:l,subtitles:k,timeFragment:u,autoPlay:n,transport:c,directFile:d}};u.prototype.loadVideo=function(){var a=this,d=0>=arguments.length||void 0===arguments[0]?{}:arguments[0],d=this._parseOptions(d);q.info("loadvideo",d);var c=d,u=c.url,k=c.keySystems,n=c.subtitles,v=c.timeFragment,M=c.autoPlay,d=c.transport,L=c.directFile;this.stop();this.frag=v;this.playing.onNext(M);var aa=this.createPipelines(d,{audio:{cache:new ca},video:{cache:new ca}}), p=this.adaptive,d=this.timings,c=this.video,w;try{w=da({url:u,keySystems:k,subtitles:n,timings:d,timeFragment:v,adaptive:p,pipelines:aa,videoElement:c,autoPlay:M,directFile:L})}catch(X){w=h(function(){throw X;})}w=w.publish();var u=g(w,"segment"),k=g(w,"manifest"),n=g(w,"stalled").startWith(null),v=g(w,"loaded").filter(function(a){return!0===a}),L=L?v:f(v,g(u.pluck("adaptation"),"audio"),g(u.pluck("adaptation"),"video"),b.noop),L=L.take(1),n=L.map("LOADED").concat(l(this.playing,n,function(a,b){return b? "seeking"==b.name?"SEEKING":"BUFFERING":a?"PLAYING":"PAUSED"})).changes().startWith("LOADING"),Q=this.subscriptions=new t;w=[y(c,["play","pause"]).each(function(b){return a.playing.onNext("play"==b.type)}),u.each(function(b){var d=b.adaptation.type,c=b.representation,f=b.adaptation;a.reps[d]=c;a.adas[d]=f;"text"==d&&a.__recordState("subtitle",f.lang);"video"==d&&a.__recordState("videoBitrate",c.bitrate);"audio"==d&&(a.__recordState("language",f.lang),a.__recordState("audioBitrate",c.bitrate));a.trigger("progress", b)}),k.each(function(b){a.man=b;a.trigger("manifestChange",b)}),n.each(function(b){return a._setState(b)}),d.each(function(b){a.man&&(a.man.isLive&&0<b.ts&&(b.wallClockTime=S(b.ts,a.man),b.liveGap=O(b.ts,a.man)),a.trigger("currentTimeChange",b))}),w.subscribe(function(){},function(b){a.resetStates();a.trigger("error",b);a._setState("STOPPED");a._clear()},function(){a.resetStates();a._setState("ENDED");a._clear()}),w.subscribe(function(b){return a.stream.onNext(b)},function(b){return a.stream.onNext({type:"error", value:b})}),w.connect()];b.each(w,function(a){return Q.add(a)});this.subscriptions||Q.dispose();return L.toPromise()};u.prototype._setState=function(a){this.state!==a&&(this.state=a,this.trigger("playerStateChange",a))};u.prototype.getManifest=function(){return this.man};u.prototype.getVideoElement=function(){return this.video};u.prototype.getNativeTextTrack=function(){return this.video.textTracks[0]};u.prototype.getPlayerState=function(){return this.state};u.prototype.isLive=function(){p(this);return this.man.isLive}; u.prototype.getUrl=function(){p(this);return this.man.locations[0]};u.prototype.getVideoDuration=function(){return this.video.duration};u.prototype.getVideoLoadedTime=function(){return(new M(this.video.buffered)).getSize(this.video.currentTime)};u.prototype.getVideoPlayedTime=function(){return(new M(this.video.buffered)).getLoaded(this.video.currentTime)};u.prototype.getCurrentTime=function(){if(!this.man)return NaN;var a=this.video.currentTime;return this.man.isLive?S(a,this.man):a};u.prototype.getStartTime= function(){return this.frag.start};u.prototype.getEndTime=function(){return this.frag.end};u.prototype.getPlaybackRate=function(){return this.video.playbackRate};u.prototype.getVolume=function(){return this.video.volume};u.prototype.isFullscreen=function(){return x()};u.prototype.getAvailableLanguages=function(){return this.man&&aa.getAvailableLanguages(this.man)||[]};u.prototype.getAvailableSubtitles=function(){return this.man&&aa.getAvailableSubtitles(this.man)||[]};u.prototype.getLanguage=function(){return this.adaptive.getLanguage()}; u.prototype.getSubtitle=function(){return this.adaptive.getSubtitle()};u.prototype.getAvailableVideoBitrates=function(){var a=this.man&&this.man.adaptations.video[0];return a&&a.bitrates||[]};u.prototype.getAvailableAudioBitrates=function(){var a=this.adas.audio;return a&&a.bitrates||[]};u.prototype.getVideoBitrate=function(){return this.evts.videoBitrate};u.prototype.getAudioBitrate=function(){return this.evts.audioBitrate};u.prototype.getVideoMaxBitrate=function(){return this.adaptive.getVideoMaxBitrate()}; u.prototype.getAudioMaxBitrate=function(){return this.adaptive.getAudioMaxBitrate()};u.prototype.getVideoBufferSize=function(){return this.adaptive.getVideoBufferSize()};u.prototype.getAudioBufferSize=function(){return this.adaptive.getAudioBufferSize()};u.prototype.getAverageBitrates=function(){return this.adaptive.getAverageBitrates()};u.prototype.getMetrics=function(){return this.metrics};u.prototype.getTimings=function(){return this.timings};u.prototype.play=function(){this.video.play()};u.prototype.pause= function(){this.video.pause()};u.prototype.setPlaybackRate=function(b){var d=this;return new a(function(a){return a(d.video.playbackRate=b)})};u.prototype.goToStart=function(){return this.seekTo(this.getStartTime())};u.prototype.seekTo=function(b){var d=this;return new a(function(a){B(d.man);var c=d.video.currentTime;d.man.isLive&&(b=Q(b,d.man));b!==c?(q.info("seek to",b),a(d.video.currentTime=b)):a(c)})};u.prototype.setFullscreen=function(){!1===(0>=arguments.length||void 0===arguments[0]?!0:arguments[0])? E():K(this.video)};u.prototype.setVolume=function(a){a!==this.video.volume&&(this.video.volume=a,this.trigger("volumeChange",a))};u.prototype.mute=function(){this.muted=this.getVolume()||.1;this.setVolume(0)};u.prototype.unMute=function(){0===this.getVolume()&&this.setVolume(this.muted)};u.prototype.setLanguage=function(d){var c=this;return new a(function(a){B(b.contains(c.getAvailableLanguages(),d),"player: unknown language");a(c.adaptive.setLanguage(d))})};u.prototype.setSubtitle=function(d){var c= this;return(new a(function(a){B(!d||b.contains(c.getAvailableSubtitles(),d),"player: unknown subtitle");a(c.adaptive.setSubtitle(d||""))})).then(function(){d||c.__recordState("subtitle",null)})};u.prototype.setVideoBitrate=function(d){var c=this;return new a(function(a){B(0===d||b.contains(c.getAvailableVideoBitrates(),d),"player: video bitrate unavailable");a(c.adaptive.setVideoBitrate(d))})};u.prototype.setAudioBitrate=function(d){var c=this;return new a(function(a){B(0===d||b.contains(c.getAvailableAudioBitrates(), d),"player: audio bitrate unavailable");a(c.adaptive.setAudioBitrate(d))})};u.prototype.setVideoMaxBitrate=function(b){var d=this;return new a(function(a){a(d.adaptive.setVideoMaxBitrate(b))})};u.prototype.setAudioMaxBitrate=function(b){var d=this;return new a(function(a){a(d.adaptive.setAudioMaxBitrate(b))})};u.prototype.setVideoBufferSize=function(b){var d=this;return new a(function(a){return a(d.adaptive.setVideoBufferSize(b))})};u.prototype.setAudioBufferSize=function(b){var d=this;return new a(function(a){return a(d.adaptive.setAudioBufferSize(b))})}; u.prototype.getStreamObservable=function(){return this.stream};u.prototype.getDebug=function(){return G.getDebug(this)};u.prototype.showDebug=function(){G.showDebug(this,this.video)};u.prototype.hideDebug=function(){G.hideDebug()};u.prototype.toggleDebug=function(){G.toggleDebug(this,this.video)};u.prototype.getCurrentKeySystem=function(){return la.getCurrentKeySystem()};return u}(k);r.exports=c},function(r,k,c){function n(a,c){if("function"!==typeof c&&null!==c)throw new TypeError("Super expression must either be null or a function, not "+ typeof c);a.prototype=Object.create(c&&c.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});c&&(Object.setPrototypeOf?Object.setPrototypeOf(a,c):a.__proto__=c)}k=c(10);var p=c(9).BufferedRanges,g=c(6),a=c(2);c=function(b){function c(a){if(!(this instanceof c))throw new TypeError("Cannot call a class as a function");b.call(this);this.codec=a;this.updating=!1;this.readyState="opened";this.buffered=new p}n(c,b);c.prototype.appendBuffer=function(a){var b=this;return this._lock(function(){return b._append(a)})}; c.prototype.remove=function(a,b){var c=this;return this._lock(function(){return c._remove(a,b)})};c.prototype.abort=function(){this.remove(0,Infinity);this.updating=!1;this.readyState="closed";this._abort()};c.prototype._append=function(){};c.prototype._remove=function(){};c.prototype._abort=function(){};c.prototype._lock=function(b){var d=this;a(!this.updating,"text-buffer: cannot remove while updating");this.updating=!0;this.trigger("updatestart");return(new g(function(a){return a(b())})).then(function(){return d._unlock("update")}, function(a){return d._unlock("error",a)})};c.prototype._unlock=function(a,b){this.trigger(a,b);this.updating=!1;this.trigger("updateend")};return c}(k);r.exports=c},function(r,k,c){function n(a,b){return q.create(function(d){b.src=a;d.onNext({url:a});return function(){b.src=""}})}function p(a){return"audio"==a||"video"==a}var g=c(1),a=c(4),b=c(2),q=c(3).Observable;k=c(5);var t=k.first,d=k.on;k=c(19);var v=k.getLiveGap,w=k.seekingsSampler,l=k.fromWallClockTime,h=c(5).retryWithBackoff,f=q.empty,y=q.never, G=q.just,B=q.merge,F=q.zip,E=Math.min;k=c(8);var K=k.MediaSource_,x=k.sourceOpen,I=k.loadedMetadataEvent,L=c(35),S=c(16).getLiveEdge,Q=c(25),O=c(15);c=c(18);var ca=c.normalizeManifest,M=c.mergeManifestsIndex,Z=c.mutateManifestLiveGap,V=c.getAdaptations;r.exports=function(c){function k(b,d,c){var f=c.type;c=c.codec;if(p(f))sa[f]?b=sa[f]:(a.info("add sourcebuffer",c),b=d.addSourceBuffer(c),sa[f]=b);else{if(d=wa[f])try{d.abort()}catch(g){a.warn(g)}finally{delete wa[f]}if("text"==f)a.info("add text sourcebuffer", c),b=new L(b,c);else throw f="stream: unknown buffer type "+f,a.error(f),Error(f);wa[f]=b}return b}function r(b,d,c){b=c.type;var f=p(b);f?(c=sa[b],delete sa[b]):(c=wa[b],delete wa[b]);if(c)try{c.abort(),f&&d.removeSourceBuffer(c)}catch(g){a.warn(g)}}function R(a){var b=Y.map(function(b){var d;Ga?(d=g.cloneObject(b),d.ts=E(b.ts,va),d.duration=E(b.duration,va)):d=b;d.liveGap=v(b.ts,a);return d}),d=w(b);return{timings:b,seekings:d}}function da(b,d,c,g){var h=d.type;return La.getAdaptationsChoice(h, d.adaptations).flatMapLatest(function(l){if(!l)return r(ga,b,d),y();var u=La.getBufferAdapters(l);l=Q({sourceBuffer:k(ga,b,d),pipeline:Ma[h],adaptation:l,timings:c,seekings:g,adapters:u});return p(h)?l:l["catch"](function(b){a.error("buffer",h,"has crashed",b);return f()})})}function la(c){var f=I(ga).tap(function(){var d=c.duration,f=Fa,h=va,u=/^\d*(\.\d+)? ?%$/;g.isString(f)&&u.test(f)&&(f=parseFloat(f)/100*d);g.isString(h)&&u.test(h)&&(va=parseFloat(h)/100*d);if(Infinity===h||"100%"===h)h=d;c.isLive? f=f?l(f,c):S(c):b(f<d&&h<=d,"stream: bad startTime and endTime");a.info("set initial time",f);ga.currentTime=f}),h=d(ga,"canplay").tap(function(){a.info("canplay event");ya&&ga.play();ya=!0});return t(F(f,h,g.noop)).map({type:"loaded",value:!0}).startWith({type:"loaded",value:!1})}function ta(){return Ka&&Ka.length?O(ga,Ka):O.onEncrypted(ga).map(function(){a.error("eme: ciphered media and no keySystem passed");throw Error("eme: ciphered media and no keySystem passed");})}function u(b){var d=1>=arguments.length|| void 0===arguments[1]?!0:arguments[1];return b.distinctUntilChanged(null,function(b,c){var f=c.stalled,h=b.stalled,g;g=h||f?h&&f?h.name==f.name:!1:!0;!g&&d&&(h?(a.warn("resume playback",c.ts,c.name),ga.playbackRate=h.playback):(a.warn("stop playback",c.ts,c.name),ga.playbackRate=0));f&&(f=c.buffered.getNextRangeGap(c.ts),1>f&&(h=c.ts+f+1/60,ga.currentTime=h,a.warn("discontinuity seek",c.ts,f,h)));return g}).map(function(a){return{type:"stalled",value:a.stalled}})}function D(a){return a&&"out-of-index"== a.type}function na(b,d){if(D(d))return a.warn("out of index"),Sa({url:b.locations[0]}).map(function(a){a=a.parsed;return{type:"manifest",value:M(b,ca(a.url,a.manifest,ha))}});d&&"precondition-failed"==d.type&&(Z(b,1),a.warn("precondition failed",b.presentationLiveGap));return G(d)}function ua(a,b,d,c){var f=g.map(V(b),function(b){return da(a,b,d,c)}),f=B(f);return b.isLive?f.distinctUntilChanged(null,function(a,b){return D(b)&&D(a)}).concatMap(function(a){return na(b,a)}):f}function Ea(b,c){var f= R(c),h=f.timings,g=f.seekings,f=G({type:"manifest",value:c}),l=la(c),g=ua(b,c,h,g),k=ta(),h=u(h,!0),n=d(ga,"error").flatMap(function(){var b="stream: video element MEDIA_ERR code "+ga.error.code;a.error(b);throw Error(b);});return B(f,l,k,g,h,n)}function Wa(){var a=R(Ca,{timeInterval:1E3}).timings,b=G({type:"manifest",value:Ca}),d=la(Ca),a=u(a,!1);return B(b,d,a)}var Qa=c.url,Ka=c.keySystems,ha=c.subtitles,Y=c.timings,J=c.timeFragment,La=c.adaptive,Ma=c.pipelines,ga=c.videoElement,ya=c.autoPlay,Ca= c.directFile;b(K,"player: browser is required to support MediaSource");var Fa=J.start,va=J.end,Ga=Infinity>va,Sa=Ma.manifest,sa={},wa={};c=Y.filter(function(a){var b=a.ts;a=a.duration;return 0<a&&.2>E(a,va)-b}).take(1).share();if(Ca)return n(Qa,ga).flatMap(Wa).takeUntil(c);J=h(function(b){var d=b.url,c=b.mediaSource;b=x(c);return Sa({url:d}).zip(b,g.identity).flatMap(function(b){b=b.parsed;b=ca(b.url,b.manifest,ha);c.duration=Infinity===b.duration?Number.MAX_VALUE:b.duration;a.info("set duration", c.duration);return Ea(c,b)})},{retryDelay:500,totalRetry:3,resetDelay:6E4,shouldRetry:function(b,d){if(/MEDIA_ERR/.test(b.message))return!1;a.warn("stream retry",b,d);return!0}});return function(b,d){return q.create(function(c){var f=new K,h=d.src=URL.createObjectURL(f);c.onNext({url:b,mediaSource:f});a.info("create mediasource object",h);return function(){if(f&&"closed"!=f.readyState){var b=f.readyState;g.each(g.cloneArray(f.sourceBuffers),function(d){try{"open"==b&&d.abort(),f.removeSourceBuffer(d)}catch(c){a.warn("error while disposing souceBuffer", c)}})}g.each(g.keys(wa),function(b){b=wa[b];try{b.abort()}catch(d){a.warn("error while disposing souceBuffer",d)}});d.src="";if(h)try{URL.revokeObjectURL(h)}catch(c){a.warn("error while revoking ObjectURL",c)}h=f=wa=sa=null}})}(Qa,ga).flatMap(J).takeUntil(c)}},function(r,k,c){function n(a,c){if("function"!==typeof c&&null!==c)throw new TypeError("Super expression must either be null or a function, not "+typeof c);a.prototype=Object.create(c&&c.prototype,{constructor:{value:a,enumerable:!1,writable:!0, configurable:!0}});c&&(Object.setPrototypeOf?Object.setPrototypeOf(a,c):a.__proto__=c)}var p=c(6),g=c(1);k=c(33);var a=window.VTTCue||window.TextTrackCue;k=function(b){function c(a,d){if(!(this instanceof c))throw new TypeError("Cannot call a class as a function");b.call(this,d);this.video=a;this.codec=d;this.isVTT=/^text\/vtt/.test(d);var g=document.createElement("track"),k=g.track;this.trackElement=g;this.track=k;g.kind="subtitles";k.mode="showing";a.appendChild(g)}n(c,b);c.prototype.createCuesFromArray= function(b){return b.length?g.compact(g.map(b,function(b){var c=b.start,g=b.end;if(b=b.text)return new a(c,g,b)})):[]};c.prototype._append=function(a){var b=this;if(this.isVTT)a=new Blob([a],{type:"text/vtt"}),a=URL.createObjectURL(a),this.trackElement.src=a,this.buffered.insert(0,Infinity);else{var c=this.createCuesFromArray(a);c.length&&(g.each(c,function(a){return b.track.addCue(a)}),a=c[0],c=g.last(c),this.buffered.insert(0,a.startTime,c.endTime))}return p.resolve()};c.prototype._remove=function(a, b){var c=this.track;g.each(g.cloneArray(c.cues),function(g){var l=g.startTime,h=g.endTime;l>=a&&l<=b&&h<=b&&c.removeCue(g)})};c.prototype._abort=function(){var a=this.trackElement,b=this.video;a&&b&&b.hasChildNodes(a)&&b.removeChild(a);this.track.mode="disabled";this.size=0;this.video=this.track=this.trackElement=null};return c}(k);r.exports=k},function(r,k,c){function n(a){if(!a)return!1;a=a.replace(/^npt\:/,"").replace(/\.$/,"");var b,c;a=a.split(":");var g=a.length;switch(g){case 3:b=parseInt(a[0], 10);c=parseInt(a[1],10);a=parseFloat(a[2]);break;case 2:b=0;c=parseInt(a[0],10);a=parseFloat(a[1]);break;case 1:c=b=0;a=parseFloat(a[0]);break;default:return!1}q(23>=b,t);q(59>=c,t);q(1>=g||60>a,t);return 3600*b+60*c+a}function p(a){if(!a)return!1;var b,c,g,h;a=a.split(":");switch(a.length){case 3:b=parseInt(a[0],10);c=parseInt(a[1],10);g=parseInt(a[2],10);h=a=0;break;case 4:b=parseInt(a[0],10);c=parseInt(a[1],10);g=parseInt(a[2],10);-1===a[3].indexOf(".")?(a=parseInt(a[3],10),h=0):(h=a[3].split("."), a=parseInt(h[0],10),h=parseInt(h[1],10));break;default:return!1}q(23>=b,t);q(59>=c,t);q(59>=g,t);return 3600*b+60*c+g+.001*a+1E-6*h}function g(a){return new Date(Date.parse(a))}function a(a){return a?a:!1}var b=c(1),q=c(2),t="Invalid MediaFragment";r.exports={parseTimeFragment:function(c){if(b.isString(c)){var k=c,w=k.split(",");q(2>=w.length,t);c=w[0]?w[0]:"";w=w[1]?w[1]:"";q((c||w)&&(!c||w||-1===k.indexOf(",")),t);c=c.replace(/^smpte(-25|-30|-30-drop)?\:/,"").replace("clock:","");var k=/^((npt\:)?((\d+\:(\d\d)\:(\d\d))|((\d\d)\:(\d\d))|(\d+))(\.\d*)?)?$/, l=/^(\d+\:\d\d\:\d\d(\:\d\d(\.\d\d)?)?)?$/,h=/^((\d{4})(-(\d{2})(-(\d{2})(T(\d{2})\:(\d{2})(\:(\d{2})(\.(\d+))?)?(Z|(([-\+])(\d{2})\:(\d{2})))?)?)?)?)?$/,f=/^(\d*(\.\d+)? ?%)?$/;if(k.test(c)&&k.test(w))k=n;else if(l.test(c)&&l.test(w))k=p;else if(h.test(c)&&h.test(w))k=g;else if(f.test(c)&&f.test(w))k=a;else throw Error(t);c=k(c);w=k(w);q(!1!==c||!1!==w,t);c={start:!1===c?"":c,end:!1===w?"":w}}else c=b.pick(c,["start","end"]);b.isString(c.start)&&b.isString(c.end)?(c.start||(c.start="0%"),c.end|| (c.end="100%")):(c.start||(c.start=0),c.end||(c.end=Infinity));b.isString(c.start)&&b.isString(c.end)?(q(0<=parseFloat(c.start)&&100>=parseFloat(c.start),"player: startTime should be between 0% and 100%"),q(0<=parseFloat(c.end)&&100>=parseFloat(c.end),"player: endTime should be between 0% and 100%")):(q((b.isNumber(c.start)||b.isDate(c.start))&&(b.isNumber(c.end)||b.isDate(c.end)),"player: timeFragment should have interface { start, end } where start and end are numbers or dates"),q(c.start<c.end, "player: startTime should be lower than endTime"),q(0<=c.start,"player: startTime should be greater than 0"));return c}}},function(r,k,c){function n(a){var b=a[0];return(a=a[1])&&Infinity!==a?"bytes="+ +b+"-"+ +a:"bytes="+ +b+"-"}var p=c(1);k=c(3).Observable;var g=k.empty,a=k.merge,b=k.just;c(2);var q=c(13),t=c(11).resolveURL;k=c(38);var d=k.parseSidx,v=k.patchPssh,w=c(39),l=function(a){a.withMetadata=!0;return q(a)};r.exports=function(){var c=(0>=arguments.length||void 0===arguments[0]?{}:arguments[0]).contentProtectionParser; c||(c=p.noop);var f={loader:function(b){var c=b.adaptation,d=b.representation,f=b.segment,h=f.media,k=f.range;b=f.indexRange;if(f.init&&!(h||k||b))return g();k=p.isArray(k)?{Range:n(k)}:null;if(h)var q=f.time,f=f.number,h=-1===h.indexOf("$")?h:h.replace(/\$\$/g,"$").replace(/\$RepresentationID\$/g,d.id).replace(/\$Bandwidth\$/g,d.bitrate).replace(/\$Number\$/g,f).replace(/\$Time\$/g,q);else h="";c=t(c.rootURL,c.baseURL,d.baseURL,h);d=l({url:c,format:"arraybuffer",headers:k});return p.isArray(b)?(b= l({url:c,format:"arraybuffer",headers:{Range:n(b)}}),a(d,b)):d},parser:function(a){var c=a.adaptation,f=a.segment;a=new Uint8Array(a.response.blob);var g=f.init,h=f.indexRange,l,k,n;if(h=d(a,h?h[0]:0))l=h.segments,k=h.timescale;g||(0<=f.time&&0<=f.duration?n={ts:f.time,d:f.duration}:h&&1===h.segments.length&&(n={ts:h.segments[0].ts,d:h.segments[0].d}));g&&c.contentProtection&&(a=v(a,c.contentProtection));return b({blob:a,currentSegment:n,nextSegments:l,timescale:k})}};return{manifest:{loader:function(a){return l({url:a.url, format:"document"})},parser:function(a){a=a.response;return b({manifest:w(a.blob,c),url:a.url})}},audio:f,video:f,text:{loader:function(){}}}}},function(r,k,c){function n(a,b){for(var c=0,d=a.length,k,n;c+8<d&&(n=q(a,c),k=q(a,c+4),g(0<n,"dash: out of range size"),k!==b);)c+=n;if(c>=d)return-1;g(c+n<=d,"dash: atom out of range");return c}function p(b){var c=b.systemId;b=b.privateData;c=c.replace(/-/g,"");g(32===c.length);c=w(4,d(c),a(b.length),b);return w(a(c.length+8),v("pssh"),c)}var g=c(2);k=c(7); var a=k.itobe4,b=k.be8toi,q=k.be4toi,t=k.be2toi,d=k.hexToBytes,v=k.strToBytes,w=k.concat;r.exports={parseSidx:function(a,c){var d=n(a,1936286840);if(-1==d)return null;var g=q(a,d),d=d+4+4,k=a[d],d=d+8,p=q(a,d),d=d+4;if(0===k)k=q(a,d),d+=4,c+=q(a,d)+g,d+=4;else if(1===k)k=b(a,d),d+=8,c+=b(a,d)+g,d+=8;else return null;for(var g=[],d=d+2,v=t(a,d),d=d+2;0<=--v;){var w=q(a,d),d=d+4,r=w&2147483647;if(1==(w&2147483648)>>>31)throw Error("not implemented");w=q(a,d);d+=4;d+=4;g.push({ts:k,d:w,r:0,range:[c, c+r-1]});k+=w;c+=r}return{segments:g,timescale:p}},patchPssh:function(b,c){if(!c||!c.length)return b;var d=n(b,1836019574);if(-1==d)return b;for(var g=q(b,d),k=[b.subarray(d,d+g)],v=0;v<c.length;v++)k.push(p(c[v]));k=w.apply(null,k);k.set(a(k.length),0);return w(b.subarray(0,d),k,b.subarray(d+g))}}},function(r,k,c){function n(a){var b=S.last(a.timeline);return(b.ts+(b.r+1)*b.d)/a.timescale}function p(a,b){var c=V[a.nodeName];Q(c,"parser: no attributes for "+a.nodeName);return S.reduce(c,function(b, c){var d=c.k,f=c.fn,g=c.n,h=c.def;a.hasAttribute(d)?b[g||d]=f(a.getAttribute(d)):null!=h&&(b[g||d]=h);return b},b||{})}function g(a){return a}function a(a){return"true"==a}function b(a){return"true"==a?!0:"false"==a?!1:parseInt(a)}function q(a){return new Date(Date.parse(a))}function t(a){if(!a)return 0;var b=O.exec(a);Q(b,"parser: "+a+" is not a valid ISO8601 duration");return 31536E3*parseFloat(b[2]||0)+2592E3*parseFloat(b[4]||0)+86400*parseFloat(b[6]||0)+3600*parseFloat(b[8]||0)+60*parseFloat(b[10]|| 0)+parseFloat(b[12]||0)}function d(a){var b=M.exec(a);if(!b)return-1;a=parseInt(b[1])||0;b=parseInt(b[2])||0;return 0<b?a/b:a}function v(a){return a}function w(a){return(a=ca.exec(a))?[+a[1],+a[2]]:null}function l(a,b,c){for(a=a.firstElementChild;a;)c=b(c,a.nodeName,a),a=a.nextElementSibling;return c}function h(a){var b=l(a,function(a,b,c){if("Initialization"==b){var d,f;c.hasAttribute("range")&&(d=w(c.getAttribute("range")));c.hasAttribute("sourceURL")&&(f=c.getAttribute("sourceURL"));a.initialization= {range:d,media:f}}return a},p(a));"SegmentBase"==a.nodeName&&(b.indexType="base",b.timeline=[]);return b}function f(a){return l(a,function(a,b,c){"SegmentTimeline"==b&&(a.indexType="timeline",a.timeline=y(c));return a},h(a))}function y(a){return l(a,function(a,b,c){b=a.length;c=p(c);null==c.ts&&(b=0<b&&a[b-1],c.ts=b?b.ts+b.d*(b.r+1):0);null==c.r&&(c.r=0);a.push(c);return a},[])}function G(a){a=f(a);a.indexType||(a.indexType="template");return a}function B(a){var b=f(a);b.list=[];b.indexType="list"; return l(a,function(a,b,c){"SegmentURL"==b&&a.list.push(p(c));return a},b)}function F(a){var b=l(a,function(a,b,c){switch(b){case "BaseURL":a.baseURL=c.textContent;break;case "SegmentBase":a.index=h(c);break;case "SegmentList":a.index=B(c);break;case "SegmentTemplate":a.index=G(c)}return a},{});return p(a,b)}function E(a,b){var c=l(a,function(a,c,d){switch(c){case "ContentProtection":c=b(p(d),d);a.contentProtection=c;break;case "ContentComponent":a.contentComponent=p(d);break;case "BaseURL":a.baseURL= d.textContent;break;case "SegmentBase":a.index=h(d);break;case "SegmentList":a.index=B(d);break;case "SegmentTemplate":a.index=G(d);break;case "Representation":c=F(d),null==c.id&&(c.id=a.representations.length),a.representations.push(c)}return a},{representations:[]});return p(a,c)}function K(a,b){var c=p(a,l(a,function(a,c,d){switch(c){case "BaseURL":a.baseURL=d.textContent;break;case "AdaptationSet":c=E(d,b),null==c.id&&(c.id=a.adaptations.length),a.adaptations.push(c)}return a},{adaptations:[]})); c.baseURL&&S.each(c.adaptations,function(a){return S.defaults(a,{baseURL:c.baseURL})});return c}function x(a,b){var c=a.documentElement;Q.equal(c.nodeName,"MPD","parser: document root should be MPD");var d=l(c,function(a,c,d){switch(c){case "BaseURL":a.baseURL=d.textContent;break;case "Location":a.locations.push(d.textContent);break;case "Period":a.periods.push(K(d,b))}return a},{transportType:"dash",periods:[],locations:[]}),d=p(c,d);/isoff-live/.test(d.profiles)&&(c=(c=S.find(d.periods[0].adaptations, function(a){return"video/mp4"==a.mimeType}))&&c.index,c=c.timeline?n(c):Date.now()/1E3-60,d.availabilityStartTime=d.availabilityStartTime.getTime()/1E3,d.presentationLiveGap=Date.now()/1E3-(c+d.availabilityStartTime));return d}function I(a,b){return x((new DOMParser).parseFromString(a,"application/xml"),b)}function L(a,b){if(S.isString(a))return I(a,b);if(a instanceof window.Document)return x(a,b);throw Error("parser: unsupported type to parse");}var S=c(1),Q=c(2),O=/^P(([\d.]*)Y)?(([\d.]*)M)?(([\d.]*)D)?T?(([\d.]*)H)?(([\d.]*)M)?(([\d.]*)S)?/, ca=/([0-9]+)-([0-9]+)/,M=/([0-9]+)(\/([0-9]+))?/;k=[{k:"profiles",fn:g},{k:"width",fn:parseInt},{k:"height",fn:parseInt},{k:"frameRate",fn:d},{k:"audioSamplingRate",fn:g},{k:"mimeType",fn:g},{k:"segmentProfiles",fn:g},{k:"codecs",fn:g},{k:"maximumSAPPeriod",fn:parseFloat},{k:"maxPlayoutRate",fn:parseFloat},{k:"codingDependency",fn:a}];c=[{k:"timescale",fn:parseInt},{k:"presentationTimeOffset",fn:parseFloat,def:0},{k:"indexRange",fn:w},{k:"indexRangeExact",fn:a},{k:"availabilityTimeOffset",fn:parseFloat}, {k:"availabilityTimeComplete",fn:a}];var Z=c.concat([{k:"duration",fn:parseInt},{k:"startNumber",fn:parseInt}]),V={ContentProtection:[{k:"schemeIdUri",fn:g},{k:"value",fn:g}],SegmentURL:[{k:"media",fn:g},{k:"mediaRange",fn:w},{k:"index",fn:g},{k:"indexRange",fn:w}],S:[{k:"t",fn:parseInt,n:"ts"},{k:"d",fn:parseInt},{k:"r",fn:parseInt}],SegmentTimeline:[],SegmentBase:c,SegmentTemplate:Z.concat([{k:"initialization",fn:function(a){return{media:a,range:void 0}}},{k:"index",fn:g},{k:"media",fn:g},{k:"bitstreamSwitching", fn:g}]),SegmentList:Z,ContentComponent:[{k:"id",fn:g},{k:"lang",fn:g},{k:"contentType",fn:g},{k:"par",fn:v}],Representation:k.concat([{k:"id",fn:g},{k:"bandwidth",fn:parseInt,n:"bitrate"},{k:"qualityRanking",fn:parseInt}]),AdaptationSet:k.concat([{k:"id",fn:g},{k:"group",fn:parseInt},{k:"lang",fn:g},{k:"contentType",fn:g},{k:"par",fn:v},{k:"minBandwidth",fn:parseInt,n:"minBitrate"},{k:"maxBandwidth",fn:parseInt,n:"maxBitrate"},{k:"minWidth",fn:parseInt},{k:"maxWidth",fn:parseInt},{k:"minHeight",fn:parseInt}, {k:"maxHeight",fn:parseInt},{k:"minFrameRate",fn:d},{k:"maxFrameRate",fn:d},{k:"segmentAlignment",fn:b},{k:"subsegmentAlignment",fn:b},{k:"bitstreamSwitching",fn:a}]),Period:[{k:"id",fn:g},{k:"start",fn:t},{k:"duration",fn:t},{k:"bitstreamSwitching",fn:a}],MPD:[{k:"id",fn:g},{k:"profiles",fn:g},{k:"type",fn:g},{k:"availabilityStartTime",fn:q},{k:"availabilityEndTime",fn:q},{k:"publishTime",fn:q},{k:"mediaPresentationDuration",fn:t,n:"duration"},{k:"minimumUpdatePeriod",fn:t},{k:"minBufferTime",fn:t}, {k:"timeShiftBufferDepth",fn:t},{k:"suggestedPresentationDelay",fn:t},{k:"maxSegmentDuration",fn:t},{k:"maxSubsegmentDuration",fn:t}]};L.parseFromString=I;L.parseFromDocument=x;r.exports=L},function(r,k,c){r.exports={smooth:c(41),dash:c(37)}},function(r,k,c){function n(a){return(a=a.match(L))&&a[1]||""}function p(a,b){return b?a.replace(L,"?token="+b):a.replace(L,"")}function g(a,b,c){return d(a.rootURL,a.baseURL,b.baseURL).replace(/\{bitrate\}/g,b.bitrate).replace(/\{start time\}/g,c.time)}k=c(1); var a=c(3).Observable,b=a.empty,q=a.just,t=c(13),d=c(11).resolveURL,v=c(7).bytesToStr,w=c(4),l=c(43),a=c(42),h=a.patchSegment,f=a.createVideoInitSegment,y=a.createAudioInitSegment,G=a.getMdat,B=a.getTraf,F=a.parseTfrf,E=a.parseTfxd,a=c(44).parseSami;c=c(45).parseTTML;var K={"application/x-sami":a,"application/smil":a,"application/ttml+xml":c,"application/ttml+xml+mp4":c,"text/vtt":k.identity},x=/\.(isml?)(\?token=\S+)?$/,I=/\.wsx?(\?token=\S+)?/,L=/\?token=(\S+)/,S=function(a){a.withMetadata=!0;return t(a)}; r.exports=function(){function a(b,c,d){var f,g;c.isLive?(b=B(b))?(f=F(b),g=E(b)):w.warn("smooth: could not find traf atom"):f=null;g||(g={d:d.duration,ts:d.time});return{nextSegments:f,currentSegment:g}}var c=l(0>=arguments.length||void 0===arguments[0]?{}:arguments[0]),d={loader:function(a){var b=a.adaptation,c=a.representation;a=a.segment;if(a.init){var d;a=b.smoothProtection||{};switch(b.type){case "video":d=f(c.index.timescale,c.width,c.height,72,72,4,c.codecPrivateData,a.keyId,a.keySystems); break;case "audio":d=y(c.index.timescale,c.channels,c.bitsPerSample,c.packetSize,c.samplingRate,c.codecPrivateData,a.keyId,a.keySystems)}return q({blob:d,size:d.length,duration:100})}var h;if(d=a.range)h=d[0],h=(d=d[1])&&Infinity!==d?"bytes="+ +h+"-"+ +d:"bytes="+ +h+"-",h={Range:h};b=g(b,c,a);return S({url:b,format:"arraybuffer",headers:h})},parser:function(b){var c=b.adaptation,d=b.response;b=b.segment;if(b.init)return q({blob:d.blob,timings:null});d=new Uint8Array(d.blob);b=a(d,c,b);c=b.nextSegments; b=b.currentSegment;return q({blob:h(d,b.ts),nextSegments:c,currentSegment:b})}};return{manifest:{resolver:function(a){a=a.url;var b=n(a);return(I.test(a)?S({url:p(a,""),format:"document"}).map(function(a){return a.blob.getElementsByTagName("media")[0].getAttribute("src")}):q(a)).map(function(a){var c=a.match(x);a=c?a.replace(c[1],c[1]+"/manifest"):a;return{url:p(a,b)}})},loader:function(a){return S({url:a.url,format:"document"})},parser:function(a){a=a.response;return q({manifest:c(a.blob),url:a.url})}}, audio:d,video:d,text:{loader:function(a){var c=a.adaptation,d=a.representation,f=a.segment;if(f.init)return b();a=d.mimeType;c=g(c,d,f);return 0<=a.indexOf("mp4")?S({url:c,format:"arraybuffer"}):S({url:c,format:"text"})},parser:function(b){var c=b.response,d=b.adaptation,f=b.representation;b=b.segment;var g=d.lang,h=f.mimeType,l=K[h];if(!l)throw Error("smooth: could not find a text-track parser for the type "+h);var k=c.blob;0<=h.indexOf("mp4")?(k=new Uint8Array(k),c=v(G(k))):c=k;h=a(k,d,b);d=h.nextSegments; h=h.currentSegment;return q({blob:l(c,g,b.time/f.index.timescale),currentSegment:h,nextSegments:d})}}}}},function(r,k,c){function n(a,b){return d(G(b.length+8),K(a),b)}function p(a,b,c,d,f){for(var g=0,h=a.length,l;g<h;){l=y(a,g);if(1970628964===y(a,g+4)&&y(a,g+8)===b&&y(a,g+12)===c&&y(a,g+16)===d&&y(a,g+20)===f)return a.subarray(g+24,g+l);g+=l}}function g(a,b){for(var c=0,d=a.length,f,g;c+8<d&&(g=y(a,c),f=y(a,c+4),t(0<g,"dash: out of range size"),f!==b);)c+=g;if(!(c>=d))return a.subarray(c+8,c+g)} function a(a,b,c,d){var f=[a,b,c];q.each(d,function(a){a=x.pssh(a.systemId,a.privateData,a.keyIds);f.push(a)});return f}function b(b,c,f,g,h,l,k){f=x.mult("stbl",[f,n("stts",new Uint8Array(8)),n("stsc",new Uint8Array(8)),n("stsz",new Uint8Array(12)),n("stco",new Uint8Array(8))]);var p=n("url ",new Uint8Array([0,0,0,1])),p=x.dref(p),p=x.mult("dinf",[p]);g=x.mult("minf",[g,p,f]);c=x.hdlr(c);f=x.mdhd(b);c=x.mult("mdia",[f,c,g]);h=x.tkhd(h,l,1);h=x.mult("trak",[h,c]);l=x.trex(1);l=x.mult("mvex",[l]); b=x.mvhd(b,1);k=x.mult("moov",a(b,l,h,k));b=x.ftyp("isom",["isom","iso2","iso6","avc1","dash"]);return d(b,k)}var q=c(1),t=c(2);k=c(7);var d=k.concat,v=k.strToBytes,w=k.hexToBytes,l=k.bytesToHex,h=k.be2toi,f=k.itobe2,y=k.be4toi,G=k.itobe4,B=k.be8toi,F=k.itobe8,E=[96E3,88200,64E3,48E3,44100,32E3,24E3,22050,16E3,12E3,11025,8E3,7350],K=q.memoize(v),x={mult:function(a,b){return n(a,d.apply(null,b))},avc1encv:function(a,b,c,g,h,l,k,p,q,w){return n(a,d(6,f(b),16,f(c),f(g),f(h),2,f(l),6,[0,1,k.length],v(k), 31-k.length,f(p),[255,255],q,"encv"===a?w:[]))},avcc:function(a,b,c){return n("avcC",d([1,a[1],a[2],a[3],252|(2===c?1:4===c?3:0),225],f(a.length),a,[1],f(b.length),b))},dref:function(a){return n("dref",d(7,[1],a))},esds:function(a,b){return n("esds",d(4,[3,25],f(a),[0,4,17,64,21],11,[5,2],w(b),[6,1,2]))},frma:function(a){return n("frma",v(a))},free:function(a){return n("free",new Uint8Array(a-8))},ftyp:function(a,b){return n("ftyp",d.apply(null,[v(a),[0,0,0,1]].concat(b.map(v))))},hdlr:function(a){return n("hdlr", d(8,v("audio"===a?"soun":"vide"),12,v("Media Handler")))},mdhd:function(a){return n("mdhd",d(12,G(a),8))},moof:function(a,b){return x.mult("moof",[a,b])},mp4aenca:function(a,b,c,g,h,l,k,p){return n(a,d(6,f(b),8,f(c),f(g),2,f(h),f(l),2,k,"enca"===a?p:[]))},mvhd:function(a,b){return n("mvhd",d(12,G(a),4,[0,1],2,[1,0],10,[0,1],14,[0,1],14,[64,0,0,0],26,f(b+1)))},pssh:function(a){var b=1>=arguments.length||void 0===arguments[1]?[]:arguments[1],c=2>=arguments.length||void 0===arguments[2]?[]:arguments[2]; a=a.replace(/-/g,"");t(32===a.length,"wrong system id length");var f,g=c.length;0<g?(f=1,c=d.apply(null,[G(g)].concat(c))):(f=0,c=[]);return n("pssh",d([f,0,0,0],w(a),c,G(b.length),b))},saio:function(a,b,c,f){return n("saio",d(4,[0,0,0,1],G(a.length+b.length+c.length+f.length+8+8+8+8)))},saiz:function(a){if(0===a.length)return n("saiz",new Uint8Array);var b=y(a,0),c=y(a,4),d=new Uint8Array(9+c);d.set(G(c),5);for(var c=9,f=8,g,l;f<a.length;)f+=8,2===(b&2)?(l=2,g=h(a,f),f+=2+6*g):l=g=0,d[c]=6*g+8+l, c++;return n("saiz",d)},schm:function(a,b){return n("schm",d(4,v(a),G(b)))},senc:function(a){return n("senc",a)},smhd:function(){return n("smhd",new Uint8Array(8))},stsd:function(a){return n("stsd",d.apply(null,[7,[a.length]].concat(a)))},tkhd:function(a,b,c){return n("tkhd",d(G(7),8,G(c),20,[1,0,0,0],[0,1,0,0],12,[0,1,0,0],12,[64,0,0,0],f(a),2,f(b),2))},trex:function(a){return n("trex",d(4,G(a),[0,0,0,1],12))},tfdt:function(a){return n("tfdt",d([1,0,0,0],F(a)))},tenc:function(a,b,c){return n("tenc", d(6,[a,b],w(c)))},traf:function(a,b,c,d,f){var g=[a,b,c];d&&g.push(x.senc(d),x.saiz(d),x.saio(f,a,b,c));return x.mult("traf",g)},vmhd:function(){var a=new Uint8Array(12);a[3]=1;return n("vmhd",a)}},I={traf:function(a){return(a=g(a,1836019558))?g(a,1953653094):null},senc:function(a){return p(a,2721664850,1520127764,2722393154,2086964724)},tfxd:function(a){return p(a,1830656773,1121273062,2162299933,2952222642)},tfrf:function(a){return p(a,3565190898,3392751253,2387879627,2655430559)},mdat:function(a){return g(a, 1835295092)}};r.exports={getMdat:I.mdat,getTraf:I.traf,parseTfrf:function(a){a=I.tfrf(a);if(!a)return[];for(var b=[],c=a[0],d=a[4],f=0;f<d;f++){var g,h;1==c?(h=B(a,16*f+5),g=B(a,16*f+13)):(h=y(a,8*f+5),g=y(a,8*f+9));b.push({ts:h,d:g})}return b},parseTfxd:function(a){if(a=I.tfxd(a))return{d:B(a,12),ts:B(a,4)}},createVideoInitSegment:function(a,c,d,f,g,h,l,k,n){n||(n=[]);var p=l.split("00000001");l=p[2];p=w(p[1]);l=w(l);h=x.avcc(p,l,h);n.length?(k=x.tenc(1,8,k),k=x.mult("schi",[k]),l=x.schm("cenc", 65536),p=x.frma("avc1"),k=x.mult("sinf",[p,l,k]),f=x.avc1encv("encv",1,c,d,f,g,"AVC Coding",24,h,k)):f=x.avc1encv("avc1",1,c,d,f,g,"AVC Coding",24,h);f=x.stsd([f]);return b(a,"video",f,x.vmhd(),c,d,n)},createAudioInitSegment:function(a,c,d,g,h,k,n,p){p||(p=[]);k||(k=E.indexOf(h),k=((32|k&31)<<4|c&31)<<3,k=l(f(k)));k=x.esds(1,k);if(p.length){n=x.tenc(1,8,n);n=x.mult("schi",[n]);var q=x.schm("cenc",65536),v=x.frma("mp4a");n=x.mult("sinf",[v,q,n]);c=x.mp4aenca("enca",1,c,d,g,h,k,n)}else c=x.mp4aenca("mp4a", 1,c,d,g,h,k);c=x.stsd([c]);return b(a,"audio",c,x.smhd(),0,0,p)},patchSegment:function(a,b){var c=a.subarray(0,y(a,0)),d=x.tfdt(b),f=d.length,g=y(c,8),h=y(c,8+g),l=y(c,8+g+8),k=y(c,8+g+8+l),n=c.subarray(8,8+g),p=c.subarray(8+g+8,8+g+8+h-8),h=p.subarray(0,l),k=p.subarray(l,l+k);h.set([0,0,0,1],12);p=I.senc(p);d=x.traf(h,d,k,p,n);n=x.moof(n,d);f=8+g+8+l+f;l=a.length;g=n.length;d=c.length;c=a.subarray(d,l);l=new Uint8Array(g+(l-d));l.set(n,0);l.set(c,g);l.set(G(n.length+8),f+16);return l}}},function(r, k,c){function n(a){return"boolean"==typeof a?a:"string"==typeof a?"TRUE"===a.toUpperCase():!0}function p(b){var c=a.last(b.timeline);return(c.ts+(c.r+1)*c.d)/b.timescale}function g(a){return[{systemId:"edef8ba9-79d6-4ace-a3c8-27dcd51d21ed",privateData:q.concat([8,1,18,16],a)}]}var a=c(1),b=c(2),q=c(7),t={audio:"audio/mp4",video:"video/mp4",text:"application/ttml+xml"},d={audio:"mp4a.40.2",video:"avc1.4D401E"};k={AACL:"audio/mp4",AVC1:"video/mp4",H264:"video/mp4",TTML:"application/ttml+xml+mp4"};c= {AACL:"mp4a.40.5",AACH:"mp4a.40.5",AVC1:"avc1.4D401E",H264:"avc1.4D401E"};var v={audio:[["Bitrate","bitrate",parseInt],["AudioTag","audiotag",parseInt],["FourCC","mimeType",k],["FourCC","codecs",c],["Channels","channels",parseInt],["SamplingRate","samplingRate",parseInt],["BitsPerSample","bitsPerSample",parseInt],["PacketSize","packetSize",parseInt],["CodecPrivateData","codecPrivateData",String]],video:[["Bitrate","bitrate",parseInt],["FourCC","mimeType",k],["FourCC","codecs",c],["MaxWidth","width", parseInt],["MaxHeight","height",parseInt],["CodecPrivateData","codecPrivateData",String]],text:[["Bitrate","bitrate",parseInt],["FourCC","mimeType",k]]};r.exports=function(){function c(a,b,d){for(a=a.firstElementChild;a;)d=b(d,a.nodeName,a),a=a.nextElementSibling;return d}function l(b,c){return a.reduce(c,function(c,d){var f=d[0],g=d[2];c[d[1]]=a.isFunction(g)?g(b.getAttribute(f)):g[b.getAttribute(f)];return c},{})}function h(f,g){f.hasAttribute("Timescale")&&(g=+f.getAttribute("Timescale"));var h= f.getAttribute("Type"),k=f.getAttribute("Subtype"),n=v[h];b(n,"parser: unrecognized QualityLevel type "+h);var p=0,q=c(f,function(a,b,c){switch(b){case "QualityLevel":c=l(c,n);if("video"!=h||c.bitrate>K)c.id=p++,a.representations.push(c);break;case "c":b=a.index;var d=a.index.timeline,f=d.length,g=0<f?d[f-1]:{d:0,ts:0,r:0},k=+c.getAttribute("d"),q=c.getAttribute("t");(c=+c.getAttribute("r"))&&c--;0<f&&k==g.d&&null==q?g.r+=(c||0)+1:d.push({d:k,ts:null==q?g.ts+g.d*(g.r+1):+q,r:c});b.timeline=d}return a}, {representations:[],index:{timeline:[],indexType:"timeline",timescale:g,initialization:{}}}),r=q.representations,q=q.index;b(r.length,"parser: adaptation should have at least one representation");var y=r[0].codecs;y||(y=d[h],a.each(r,function(a){return a.codecs=y}));var x=r[0].mimeType;x||(x=t[h],a.each(r,function(a){return a.mimeType=x}));return"ADVT"==k?null:{type:h,index:q,representations:r,name:f.getAttribute("Name"),lang:f.getAttribute("Language"),baseURL:f.getAttribute("Url")}}function f(a){return k((new DOMParser).parseFromString(a, "application/xml"))}function k(d){d=d.documentElement;b.equal(d.nodeName,"SmoothStreamingMedia","parser: document root should be SmoothStreamingMedia");b(/^[2]-[0-2]$/.test(d.getAttribute("MajorVersion")+"-"+d.getAttribute("MinorVersion")),"Version should be 2.0, 2.1 or 2.2");var f=+d.getAttribute("Timescale")||1E7,g=0,l=c(d,function(a,c,d){switch(c){case "Protection":d=d.firstElementChild;b.equal(d.nodeName,"ProtectionHeader","parser: Protection should have ProtectionHeader child");c=q.strToBytes(atob(d.textContent)); var l;l=q.le2toi(c,8);l=q.bytesToUTF16Str(c.subarray(10,10+l));l=(new DOMParser).parseFromString(l,"application/xml").querySelector("KID").textContent;l=q.guidToUuid(atob(l)).toLowerCase();var k=q.hexToBytes(l);d=d.getAttribute("SystemID").toLowerCase().replace(/\{|\}/g,"");c={keyId:l,keySystems:[{systemId:d,privateData:c}].concat(x(k))};a.protection=c;break;case "StreamIndex":if(c=h(d,f))c.id=g++,a.adaptations.push(c)}return a},{protection:null,adaptations:[]}),v=l.protection,l=l.adaptations;a.each(l, function(a){return a.smoothProtection=v});var r,t,y,B,G=n(d.getAttribute("IsLive"));if(G){r=F;y=+d.getAttribute("DVRWindowLength")/f;B=E;t=a.find(l,function(a){return"video"==a.type});var K=a.find(l,function(a){return"audio"==a.type});t=Math.min(p(t.index),p(K.index));t=Date.now()/1E3-(t+B)}return{transportType:"smoothstreaming",profiles:"",type:G?"dynamic":"static",suggestedPresentationDelay:r,timeShiftBufferDepth:y,presentationLiveGap:t,availabilityStartTime:B,periods:[{duration:(+d.getAttribute("Duration")|| Infinity)/f,adaptations:l,laFragCount:+d.getAttribute("LookAheadFragmentCount")}]}}function r(b){if(a.isString(b))return f(b);if(b instanceof window.Document)return k(b);throw Error("parser: unsupported type to parse");}var B=0>=arguments.length||void 0===arguments[0]?{}:arguments[0],F=B.suggestedPresentationDelay||20,E=B.referenceDateTime||Date.UTC(1970,0,1,0,0,0,0)/1E3,K=B.minRepresentationBitrate||19E4,x=B.keySystems||g;r.parseFromString=f;r.parseFromDocument=k;return r}},function(r,k,c){function n(c){return c.replace(b, "\n").replace(a,function(a,b){return String.fromCharCode(b)})}var p=c(1),g=c(2),a=/&#([0-9]+);/g,b=/<br>/gi,q=/<style[^>]*>([\s\S]*?)<\/style[^>]*>/i,t=/\s*<p class=([^>]+)>(.*)/i,d=/<sync[^>]+?start="?([0-9]*)"?[^0-9]/i;r.exports={parseSami:function(a,b){var c=/<sync[ >]/ig,h=/<sync[ >]|<\/body>/ig,f=[],k=a.match(q)[1],r,B=h.exec(a),B=/\.(\S+)\s*{([^}]*)}/gi,F;for(r={};F=B.exec(k);){var E=F[1];F=F[2].match(/\s*lang:\s*(\S+);/i)[1];E&&F&&(r[F]=E)}k=r[b];for(g(k,"sami: could not find lang "+b+" in CSS");;){r= c.exec(a);B=h.exec(a);if(!r&&!B)break;if(!r||!B||r.index>=B.index)throw Error("parse error");r=a.slice(r.index,B.index);B=r.match(d);if(!B)throw Error("parse error: sync time attribute");E=+B[1];if(isNaN(E))throw Error("parse error: sync time attribute NaN");B=f;r=r.split("\n");E/=1E3;F=r.length;for(var K=void 0;0<=--F;)if(K=r[F].match(t)){var x=K[2];k===K[1]&&("&nbsp;"===x?p.last(B).end=E:B.push({text:n(x),start:E}))}}return f}}},function(r,k,c){function n(b,c){var d=0;b=b.firstChild;for(var h=[], f;b;){if(1===b.nodeType)switch(b.tagName.toUpperCase()){case "P":f=b;var k=c,q=p(f.getAttribute("begin"),k),r=p(f.getAttribute("end"),k),F=p(f.getAttribute("dur"),0);if(!g.isNumber(q)&&!g.isNumber(r)&&!g.isNumber(F))throw Error("ttml: unsupported timestamp format");0<F?(null==q&&(q=d||k),null==r&&(r=q+F)):null==r&&(r=p(f.getAttribute("duration"),0),r=0<=r?r+q:Number.MAX_VALUE);f={id:f.getAttribute("xml:id")||f.getAttribute("id"),text:decodeURIComponent(t(f.innerHTML.replace(a,"\n"))),start:q,end:r}; d=f.end;h.push(f);break;case "DIV":f=p(b.getAttribute("begin"),0),null==f&&(f=c),h.push.apply(h,n(b,f))}b=b.nextSibling}return h}function p(a,c){if(a){var g;if(g=a.match(b)){var h=g[3],f=g[4],k=g[6];return 3600*parseInt(g[2]||0,10)+60*parseInt(h,10)+parseInt(f,10)+parseFloat("0."+k)}if(g=a.match(q))return h=g[4],parseFloat(g[1])*d[h]+c}}var g=c(1),a=/<br[^>]+>/gm,b=/^(([0-9]+):)?([0-9]+):([0-9]+)(\.([0-9]+))?$/,q=/(([0-9]+)(\.[0-9]+)?)(ms|h|m|s)/,t=window.escape,d={h:3600,m:60,s:1,ms:.001};r.exports= {parseTTML:function(a,b,c){a=g.isString(a)?(new DOMParser).parseFromString(a,"text/xml"):a;if(!(a instanceof window.Document||a instanceof window.HTMLElement))throw Error("ttml: needs a Document to parse");a=a.querySelector("tt");if(!a)throw Error("ttml: could not find <tt> tag");a=n(a.querySelector("body"),0);g.each(a,function(a){a.start+=c;a.end+=c});return a}}},function(r,k){function c(){this.arr=[]}c.prototype.add=function(c){this.arr.push(c)};c.prototype.remove=function(c){c=this.arr.indexOf(c); 0<=c&&this.arr.splice(c,1)};c.prototype.test=function(c){return 0<=this.arr.indexOf(c)};c.prototype.size=function(){return this.arr.length};r.exports={ArraySet:c}},function(r,k,c){function n(a){return null==a?"":String(a).replace(v,function(a){return w[a]})}function p(a){var b=a.getAverageBitrates(),c,d;b.video.subscribe(function(a){return d=a|0}).dispose();b.audio.subscribe(function(a){return c=a|0}).dispose();return{manifest:a.man,version:a.version,timeFragment:a.frag,currentTime:a.getCurrentTime(), state:a.getPlayerState(),buffer:q(a.video.buffered),volume:a.getVolume(),video:{adaptation:a.adas.video,representation:a.reps.video,maxBitrate:a.getVideoMaxBitrate(),bufferSize:a.getVideoBufferSize(),avrBitrate:d},audio:{adaptation:a.adas.audio,representation:a.reps.audio,maxBitrate:a.getAudioMaxBitrate(),bufferSize:a.getAudioBufferSize(),avrBitrate:c}}}function g(a,b){var c=b.parentNode.querySelector("#cp--debug-infos-content");if(c){var d;try{d=p(a)}catch(g){return}var k=d,q=k.video,r=k.audio,k= k.manifest;d="<b>Player v"+d.version+"</b> ("+d.state+")<br>";k&&q&&r&&(d+=["Container: "+n(k.transportType),"Live: "+n(""+k.isLive),"Downloading bitrate (Kbit/s): "+(q.representation.bitrate/1E3).toFixed(3)+"/"+(r.representation.bitrate/1E3).toFixed(3),"Estimated bandwidth (Kbit/s): "+(q.avrBitrate/1E3).toFixed(3)+"/"+(r.avrBitrate/1E3).toFixed(3),"Location: "+k.locations[0]].join("<br>"));c.innerHTML=d}}function a(a,c){var f="<style>\n#cp--debug-infos {\n position: absolute;\n top: "+n(c.offsetTop+ 10)+"px;\n left: "+n(c.offsetLeft+10)+'px;\n width: 500px;\n height: 300px;\n background-color: rgba(10, 10, 10, 0.83);\n overflow: hidden;\n color: white;\n text-align: left;\n padding: 2em;\n box-sizing: border-box;\n}\n#cp--debug-hide-infos {\n float: right;\n cursor: pointer;\n}\n</style>\n<div id="cp--debug-infos">\n <a id="cp--debug-hide-infos">[x]</a>\n <p id="cp--debug-infos-content"></p>\n</div>',k=c.parentNode,p=k.querySelector("#cp--debug-infos-container");p||(p=document.createElement("div"), p.setAttribute("id","cp--debug-infos-container"),k.appendChild(p));p.innerHTML=f;d||(d=k.querySelector("#cp--debug-hide-infos"),d.addEventListener("click",function(){return b(c)}));t&&clearInterval(t);t=setInterval(function(){return g(a,c)},1E3);g(a,c)}function b(a){(a=a.parentNode.querySelector("#cp--debug-infos-container"))&&a.parentNode.removeChild(a);t&&(clearInterval(t),t=null);d&&(d.removeEventListener("click",b),d=null)}var q=c(9).bufferedToArray,t,d,v=/[&<>"']/g,w={"&":"&amp;","<":"&lt;", ">":"&gt;",'"':"&quot;","'":"&#39;"};r.exports={getDebug:p,showDebug:a,hideDebug:b,toggleDebug:function(c,d){d.parentNode.querySelector("#cp--debug-infos-container")?b(d):a(c,d)}}},function(r,k,c){var n;(function(p,g,a){(function(){function b(a){return"function"===typeof a}function q(){return function(){p.nextTick(w)}}function r(){var a=0,b=new aa(w),c=document.createTextNode("");b.observe(c,{characterData:!0});return function(){c.data=a=++a%2}}function d(){var a=new MessageChannel;a.port1.onmessage= w;return function(){a.port2.postMessage(0)}}function v(){return function(){setTimeout(w,1)}}function w(){for(var a=0;a<M;a+=2)(0,X[a])(X[a+1]),X[a]=void 0,X[a+1]=void 0;M=0}function l(){}function h(a,b,c,d){try{a.call(b,c,d)}catch(f){return f}}function f(a,b,c){Z(function(a){var d=!1,f=h(c,b,function(c){d||(d=!0,b!==c?G(a,c):F(a,c))},function(b){d||(d=!0,E(a,b))},"Settle: "+(a._label||" unknown promise"));!d&&f&&(d=!0,E(a,f))},a)}function y(a,b){1===b._state?F(a,b._result):2===a._state?E(a,b._result): K(b,void 0,function(b){G(a,b)},function(b){E(a,b)})}function G(a,c){if(a===c)E(a,new TypeError("You cannot resolve a promise with itself"));else if("function"===typeof c||"object"===typeof c&&null!==c)if(c.constructor===a.constructor)y(a,c);else{var d;try{d=c.then}catch(g){R.error=g,d=R}d===R?E(a,R.error):void 0===d?F(a,c):b(d)?f(a,c,d):F(a,c)}else F(a,c)}function B(a){a._onerror&&a._onerror(a._result);x(a)}function F(a,b){void 0===a._state&&(a._result=b,a._state=1,0!==a._subscribers.length&&Z(x, a))}function E(a,b){void 0===a._state&&(a._state=2,a._result=b,Z(B,a))}function K(a,b,c,d){var f=a._subscribers,g=f.length;a._onerror=null;f[g]=b;f[g+1]=c;f[g+2]=d;0===g&&a._state&&Z(x,a)}function x(a){var b=a._subscribers,c=a._state;if(0!==b.length){for(var d,f,g=a._result,h=0;h<b.length;h+=3)d=b[h],f=b[h+c],d?L(c,d,f,g):f(g);a._subscribers.length=0}}function I(){this.error=null}function L(a,c,d,f){var g=b(d),h,k,l,n;if(g){try{h=d(f)}catch(p){da.error=p,h=da}h===da?(n=!0,k=h.error,h=null):l=!0;if(c=== h){E(c,new TypeError("A promises callback cannot return that same promise."));return}}else h=f,l=!0;void 0===c._state&&(g&&l?G(c,h):n?E(c,k):1===a?F(c,h):2===a&&E(c,h))}function S(a,b){try{b(function(b){G(a,b)},function(b){E(a,b)})}catch(c){E(a,c)}}function Q(a,b,c,d){this._instanceConstructor=a;this.promise=new a(l,d);this._abortOnReject=c;this._validateInput(b)?(this._input=b,this._remaining=this.length=b.length,this._init(),0===this.length?F(this.promise,this._result):(this.length=this.length|| 0,this._enumerate(),0===this._remaining&&F(this.promise,this._result))):E(this.promise,this._validationError())}function O(a){this._id=la++;this._result=this._state=void 0;this._subscribers=[];if(l!==a){if(!b(a))throw new TypeError("You must pass a resolver function as the first argument to the promise constructor");if(!(this instanceof O))throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");S(this,a)}}var ca= Array.isArray?Array.isArray:function(a){return"[object Array]"===Object.prototype.toString.call(a)},M=0,Z=function(a,b){X[M]=a;X[M+1]=b;M+=2;2===M&&U()},V="undefined"!==typeof window?window:{},aa=V.MutationObserver||V.WebKitMutationObserver,V="undefined"!==typeof Uint8ClampedArray&&"undefined"!==typeof importScripts&&"undefined"!==typeof MessageChannel,X=Array(1E3),U;U="undefined"!==typeof p&&"[object process]"==={}.toString.call(p)?q():aa?r():V?d():v();var R=new I,da=new I;Q.prototype._validateInput= function(a){return ca(a)};Q.prototype._validationError=function(){return Error("Array Methods must be provided an Array")};Q.prototype._init=function(){this._result=Array(this.length)};Q.prototype._enumerate=function(){for(var a=this.length,b=this.promise,c=this._input,d=0;void 0===b._state&&d<a;d++)this._eachEntry(c[d],d)};Q.prototype._eachEntry=function(a,b){var c=this._instanceConstructor;"object"===typeof a&&null!==a?a.constructor===c&&void 0!==a._state?(a._onerror=null,this._settledAt(a._state, b,a._result)):this._willSettleAt(c.resolve(a),b):(this._remaining--,this._result[b]=this._makeResult(1,b,a))};Q.prototype._settledAt=function(a,b,c){var d=this.promise;void 0===d._state&&(this._remaining--,this._abortOnReject&&2===a?E(d,c):this._result[b]=this._makeResult(a,b,c));0===this._remaining&&F(d,this._result)};Q.prototype._makeResult=function(a,b,c){return c};Q.prototype._willSettleAt=function(a,b){var c=this;K(a,void 0,function(a){c._settledAt(1,b,a)},function(a){c._settledAt(2,b,a)})}; var la=0;O.all=function(a,b){return(new Q(this,a,!0,b)).promise};O.race=function(a,b){function c(a){G(f,a)}function d(a){E(f,a)}var f=new this(l,b);if(!ca(a))return E(f,new TypeError("You must pass an array to race.")),f;for(var g=a.length,h=0;void 0===f._state&&h<g;h++)K(this.resolve(a[h]),void 0,c,d);return f};O.resolve=function(a,b){if(a&&"object"===typeof a&&a.constructor===this)return a;var c=new this(l,b);G(c,a);return c};O.reject=function(a,b){var c=new this(l,b);E(c,a);return c};O.prototype= {constructor:O,then:function(a,b){var c=this._state;if(1===c&&!a||2===c&&!b)return this;var d=new this.constructor(l),f=this._result;if(c){var g=arguments[c-1];Z(function(){L(c,d,g,f)})}else K(this,d,a,b);return d},"catch":function(a){return this.then(null,a)}};var ta={Promise:O,polyfill:function(){var a;a="undefined"!==typeof g?g:"undefined"!==typeof window&&window.document?window:self;"Promise"in a&&"resolve"in a.Promise&&"reject"in a.Promise&&"all"in a.Promise&&"race"in a.Promise&&function(){var c; new a.Promise(function(a){c=a});return b(c)}()||(a.Promise=O)}};c(49).amd?!(n=function(){return ta}.call(k,c,k,a),void 0!==n&&(a.exports=n)):"undefined"!==typeof a&&a.exports?a.exports=ta:"undefined"!==typeof this&&(this.ES6Promise=ta)}).call(this)}).call(k,c(14),function(){return this}(),c(22)(r))},function(r,k){r.exports=function(){throw Error("define cannot be used indirect");}}])});
IntlMessageFormat.__addLocaleData({"locale":"sl"});
import Stylis from 'stylis/stylis.min'; import _insertRulePlugin from 'stylis-rule-sheet'; import React, { cloneElement, createContext, Component, createElement } from 'react'; import { isElement, isValidElementType, ForwardRef } from 'react-is'; import memoize from 'memoize-one'; import stream from 'stream'; import PropTypes from 'prop-types'; import validAttr from '@emotion/is-prop-valid'; // var interleave = (function (strings, interpolations) { var result = [strings[0]]; for (var i = 0, len = interpolations.length; i < len; i += 1) { result.push(interpolations[i], strings[i + 1]); } return result; }); 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 classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; 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; }; }(); var _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; }; var inherits = function (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 objectWithoutProperties = function (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; }; var possibleConstructorReturn = function (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; }; // var isPlainObject = (function (x) { return (typeof x === 'undefined' ? 'undefined' : _typeof(x)) === 'object' && x.constructor === Object; }); // var EMPTY_ARRAY = Object.freeze([]); var EMPTY_OBJECT = Object.freeze({}); // function isFunction(test) { return typeof test === 'function'; } // function getComponentName(target) { return target.displayName || target.name || 'Component'; } // function isStyledComponent(target) { return target && typeof target.styledComponentId === 'string'; } // var SC_ATTR = typeof process !== 'undefined' && process.env.SC_ATTR || 'data-styled'; var SC_VERSION_ATTR = 'data-styled-version'; var SC_STREAM_ATTR = 'data-styled-streamed'; var IS_BROWSER = typeof window !== 'undefined' && 'HTMLElement' in window; var DISABLE_SPEEDY = process.env.NODE_ENV !== 'production'; // Shared empty execution context when generating static styles var STATIC_EXECUTION_CONTEXT = {}; // /** * Parse errors.md and turn it into a simple hash of code: message */ var ERRORS = process.env.NODE_ENV !== 'production' ? { "1": "Cannot create styled-component for component: %s.\n\n", "2": "Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n", "3": "Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n", "4": "The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n", "5": "The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n", "6": "Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n", "7": "ThemeProvider: Please return an object from your \"theme\" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n", "8": "ThemeProvider: Please make your \"theme\" prop an object.\n\n", "9": "Missing document `<head>`\n\n", "10": "Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n", "11": "_This error was replaced with a dev-time warning, it will be deleted for v4 final._ [createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n" } : {}; /** * super basic version of sprintf */ function format() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var a = args[0]; var b = []; var c = void 0; for (c = 1; c < args.length; c += 1) { b.push(args[c]); } b.forEach(function (d) { a = a.replace(/%[a-z]/, d); }); return a; } /** * Create an error file out of errors.md for development and a simple web link to the full errors * in production mode. */ var StyledComponentsError = function (_Error) { inherits(StyledComponentsError, _Error); function StyledComponentsError(code) { classCallCheck(this, StyledComponentsError); for (var _len2 = arguments.length, interpolations = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { interpolations[_key2 - 1] = arguments[_key2]; } if (process.env.NODE_ENV === 'production') { var _this = possibleConstructorReturn(this, _Error.call(this, 'An error occurred. See https://github.com/styled-components/styled-components/blob/master/src/utils/errors.md#' + code + ' for more information. ' + (interpolations ? 'Additional arguments: ' + interpolations.join(', ') : ''))); } else { var _this = possibleConstructorReturn(this, _Error.call(this, format.apply(undefined, [ERRORS[code]].concat(interpolations)).trim())); } return possibleConstructorReturn(_this); } return StyledComponentsError; }(Error); // var SC_COMPONENT_ID = /^[^\S\n]*?\/\* sc-component-id:\s*(\S+)\s+\*\//gm; var extractComps = (function (maybeCSS) { var css = '' + (maybeCSS || ''); // Definitely a string, and a clone var existingComponents = []; css.replace(SC_COMPONENT_ID, function (match, componentId, matchIndex) { existingComponents.push({ componentId: componentId, matchIndex: matchIndex }); return match; }); return existingComponents.map(function (_ref, i) { var componentId = _ref.componentId, matchIndex = _ref.matchIndex; var nextComp = existingComponents[i + 1]; var cssFromDOM = nextComp ? css.slice(matchIndex, nextComp.matchIndex) : css.slice(matchIndex); return { componentId: componentId, cssFromDOM: cssFromDOM }; }); }); // var COMMENT_REGEX = /^\s*\/\/.*$/gm; var SELF_REFERENTIAL_COMBINATOR = /(&(?! *[+~>])([^&{][^{]+)[^+~>]*)?([+~>] *)&/g; // NOTE: This stylis instance is only used to split rules from SSR'd style tags var stylisSplitter = new Stylis({ global: false, cascade: true, keyframe: false, prefix: false, compress: false, semicolon: true }); var stylis = new Stylis({ global: false, cascade: true, keyframe: false, prefix: true, compress: false, semicolon: false // NOTE: This means "autocomplete missing semicolons" }); // Wrap `insertRulePlugin to build a list of rules, // and then make our own plugin to return the rules. This // makes it easier to hook into the existing SSR architecture var parsingRules = []; // eslint-disable-next-line consistent-return var returnRulesPlugin = function returnRulesPlugin(context) { if (context === -2) { var parsedRules = parsingRules; parsingRules = []; return parsedRules; } }; var parseRulesPlugin = _insertRulePlugin(function (rule) { parsingRules.push(rule); }); stylis.use([parseRulesPlugin, returnRulesPlugin]); stylisSplitter.use([parseRulesPlugin, returnRulesPlugin]); var stringifyRules = function stringifyRules(rules, selector, prefix) { var componentId = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '&'; var flatCSS = rules.join('').replace(COMMENT_REGEX, ''); // replace JS comments var cssStr = (selector && prefix ? prefix + ' ' + selector + ' { ' + flatCSS + ' }' : flatCSS).replace(SELF_REFERENTIAL_COMBINATOR, '$1$3.' + componentId + '$2'); return stylis(prefix || !selector ? '' : selector, cssStr); }; var splitByRules = function splitByRules(css) { return stylisSplitter('', css); }; // /* eslint-disable camelcase, no-undef */ var getNonce = (function () { return typeof __webpack_nonce__ !== 'undefined' ? __webpack_nonce__ : null; }); // // Helper to call a given function, only once var once = (function (cb) { var called = false; return function () { if (!called) { called = true; cb(); } }; }); // /* These are helpers for the StyleTags to keep track of the injected * rule names for each (component) ID that they're keeping track of. * They're crucial for detecting whether a name has already been * injected. * (This excludes rehydrated names) */ /* adds a new ID:name pairing to a names dictionary */ var addNameForId = function addNameForId(names, id, name) { if (name) { // eslint-disable-next-line no-param-reassign var namesForId = names[id] || (names[id] = Object.create(null)); namesForId[name] = true; } }; /* resets an ID entirely by overwriting it in the dictionary */ var resetIdNames = function resetIdNames(names, id) { // eslint-disable-next-line no-param-reassign names[id] = Object.create(null); }; /* factory for a names dictionary checking the existance of an ID:name pairing */ var hasNameForId = function hasNameForId(names) { return function (id, name) { return names[id] !== undefined && names[id][name]; }; }; /* stringifies names for the html/element output */ var stringifyNames = function stringifyNames(names) { var str = ''; // eslint-disable-next-line guard-for-in for (var id in names) { str += Object.keys(names[id]).join(' ') + ' '; } return str.trim(); }; /* clones the nested names dictionary */ var cloneNames = function cloneNames(names) { var clone = Object.create(null); // eslint-disable-next-line guard-for-in for (var id in names) { clone[id] = _extends({}, names[id]); } return clone; }; // /* These are helpers that deal with the insertRule (aka speedy) API * They are used in the StyleTags and specifically the speedy tag */ /* retrieve a sheet for a given style tag */ var sheetForTag = function sheetForTag(tag) { // $FlowFixMe if (tag.sheet) return tag.sheet; /* Firefox quirk requires us to step through all stylesheets to find one owned by the given tag */ var size = document.styleSheets.length; for (var i = 0; i < size; i += 1) { var sheet = document.styleSheets[i]; // $FlowFixMe if (sheet.ownerNode === tag) return sheet; } /* we should always be able to find a tag */ throw new StyledComponentsError(10); }; /* insert a rule safely and return whether it was actually injected */ var safeInsertRule = function safeInsertRule(sheet, cssRule, index) { /* abort early if cssRule string is falsy */ if (!cssRule) return false; var maxIndex = sheet.cssRules.length; try { /* use insertRule and cap passed index with maxIndex (no of cssRules) */ sheet.insertRule(cssRule, index <= maxIndex ? index : maxIndex); } catch (err) { /* any error indicates an invalid rule */ return false; } return true; }; /* deletes `size` rules starting from `removalIndex` */ var deleteRules = function deleteRules(sheet, removalIndex, size) { var lowerBound = removalIndex - size; for (var i = removalIndex; i > lowerBound; i -= 1) { sheet.deleteRule(i); } }; // /* this marker separates component styles and is important for rehydration */ var makeTextMarker = function makeTextMarker(id) { return '\n/* sc-component-id: ' + id + ' */\n'; }; /* add up all numbers in array up until and including the index */ var addUpUntilIndex = function addUpUntilIndex(sizes, index) { var totalUpToIndex = 0; for (var i = 0; i <= index; i += 1) { totalUpToIndex += sizes[i]; } return totalUpToIndex; }; /* create a new style tag after lastEl */ var makeStyleTag = function makeStyleTag(target, tagEl, insertBefore) { var el = document.createElement('style'); el.setAttribute(SC_ATTR, ''); el.setAttribute(SC_VERSION_ATTR, "4.0.0-beta.10-5"); var nonce = getNonce(); if (nonce) { el.setAttribute('nonce', nonce); } /* Work around insertRule quirk in EdgeHTML */ el.appendChild(document.createTextNode('')); if (target && !tagEl) { /* Append to target when no previous element was passed */ target.appendChild(el); } else { if (!tagEl || !target || !tagEl.parentNode) { throw new StyledComponentsError(6); } /* Insert new style tag after the previous one */ tagEl.parentNode.insertBefore(el, insertBefore ? tagEl : tagEl.nextSibling); } return el; }; /* takes a css factory function and outputs an html styled tag factory */ var wrapAsHtmlTag = function wrapAsHtmlTag(css, names) { return function (additionalAttrs) { var nonce = getNonce(); var attrs = [nonce && 'nonce="' + nonce + '"', SC_ATTR + '="' + stringifyNames(names) + '"', SC_VERSION_ATTR + '="' + "4.0.0-beta.10-5" + '"', additionalAttrs]; var htmlAttr = attrs.filter(Boolean).join(' '); return '<style ' + htmlAttr + '>' + css() + '</style>'; }; }; /* takes a css factory function and outputs an element factory */ var wrapAsElement = function wrapAsElement(css, names) { return function () { var _props; var props = (_props = {}, _props[SC_ATTR] = stringifyNames(names), _props[SC_VERSION_ATTR] = "4.0.0-beta.10-5", _props); var nonce = getNonce(); if (nonce) { // $FlowFixMe props.nonce = nonce; } // eslint-disable-next-line react/no-danger return React.createElement('style', _extends({}, props, { dangerouslySetInnerHTML: { __html: css() } })); }; }; var getIdsFromMarkersFactory = function getIdsFromMarkersFactory(markers) { return function () { return Object.keys(markers); }; }; /* speedy tags utilise insertRule */ var makeSpeedyTag = function makeSpeedyTag(el, getImportRuleTag) { var names = Object.create(null); var markers = Object.create(null); var sizes = []; var extractImport = getImportRuleTag !== undefined; /* indicates whther getImportRuleTag was called */ var usedImportRuleTag = false; var insertMarker = function insertMarker(id) { var prev = markers[id]; if (prev !== undefined) { return prev; } markers[id] = sizes.length; sizes.push(0); resetIdNames(names, id); return markers[id]; }; var insertRules = function insertRules(id, cssRules, name) { var marker = insertMarker(id); var sheet = sheetForTag(el); var insertIndex = addUpUntilIndex(sizes, marker); var injectedRules = 0; var importRules = []; var cssRulesSize = cssRules.length; for (var i = 0; i < cssRulesSize; i += 1) { var cssRule = cssRules[i]; var mayHaveImport = extractImport; /* @import rules are reordered to appear first */ if (mayHaveImport && cssRule.indexOf('@import') !== -1) { importRules.push(cssRule); } else if (safeInsertRule(sheet, cssRule, insertIndex + injectedRules)) { mayHaveImport = false; injectedRules += 1; } } if (extractImport && importRules.length > 0) { usedImportRuleTag = true; // $FlowFixMe getImportRuleTag().insertRules(id + '-import', importRules); } sizes[marker] += injectedRules; /* add up no of injected rules */ addNameForId(names, id, name); }; var removeRules = function removeRules(id) { var marker = markers[id]; if (marker === undefined) return; var size = sizes[marker]; var sheet = sheetForTag(el); var removalIndex = addUpUntilIndex(sizes, marker) - 1; deleteRules(sheet, removalIndex, size); sizes[marker] = 0; resetIdNames(names, id); if (extractImport && usedImportRuleTag) { // $FlowFixMe getImportRuleTag().removeRules(id + '-import'); } }; var css = function css() { var _sheetForTag = sheetForTag(el), cssRules = _sheetForTag.cssRules; var str = ''; // eslint-disable-next-line guard-for-in for (var id in markers) { str += makeTextMarker(id); var marker = markers[id]; var end = addUpUntilIndex(sizes, marker); var size = sizes[marker]; for (var i = end - size; i < end; i += 1) { var rule = cssRules[i]; if (rule !== undefined) { str += rule.cssText; } } } return str; }; return { clone: function clone() { throw new StyledComponentsError(5); }, css: css, getIds: getIdsFromMarkersFactory(markers), hasNameForId: hasNameForId(names), insertMarker: insertMarker, insertRules: insertRules, removeRules: removeRules, sealed: false, styleTag: el, toElement: wrapAsElement(css, names), toHTML: wrapAsHtmlTag(css, names) }; }; var makeTextNode = function makeTextNode(id) { return document.createTextNode(makeTextMarker(id)); }; var makeBrowserTag = function makeBrowserTag(el, getImportRuleTag) { var names = Object.create(null); var markers = Object.create(null); var extractImport = getImportRuleTag !== undefined; /* indicates whther getImportRuleTag was called */ var usedImportRuleTag = false; var insertMarker = function insertMarker(id) { var prev = markers[id]; if (prev !== undefined) { return prev; } markers[id] = makeTextNode(id); el.appendChild(markers[id]); names[id] = Object.create(null); return markers[id]; }; var insertRules = function insertRules(id, cssRules, name) { var marker = insertMarker(id); var importRules = []; var cssRulesSize = cssRules.length; for (var i = 0; i < cssRulesSize; i += 1) { var rule = cssRules[i]; var mayHaveImport = extractImport; if (mayHaveImport && rule.indexOf('@import') !== -1) { importRules.push(rule); } else { mayHaveImport = false; var separator = i === cssRulesSize - 1 ? '' : ' '; marker.appendData('' + rule + separator); } } addNameForId(names, id, name); if (extractImport && importRules.length > 0) { usedImportRuleTag = true; // $FlowFixMe getImportRuleTag().insertRules(id + '-import', importRules); } }; var removeRules = function removeRules(id) { var marker = markers[id]; if (marker === undefined) return; /* create new empty text node and replace the current one */ var newMarker = makeTextNode(id); el.replaceChild(newMarker, marker); markers[id] = newMarker; resetIdNames(names, id); if (extractImport && usedImportRuleTag) { // $FlowFixMe getImportRuleTag().removeRules(id + '-import'); } }; var css = function css() { var str = ''; // eslint-disable-next-line guard-for-in for (var id in markers) { str += markers[id].data; } return str; }; return { clone: function clone() { throw new StyledComponentsError(5); }, css: css, getIds: getIdsFromMarkersFactory(markers), hasNameForId: hasNameForId(names), insertMarker: insertMarker, insertRules: insertRules, removeRules: removeRules, sealed: false, styleTag: el, toElement: wrapAsElement(css, names), toHTML: wrapAsHtmlTag(css, names) }; }; var makeServerTag = function makeServerTag(namesArg, markersArg) { var names = namesArg === undefined ? Object.create(null) : namesArg; var markers = markersArg === undefined ? Object.create(null) : markersArg; var insertMarker = function insertMarker(id) { var prev = markers[id]; if (prev !== undefined) { return prev; } return markers[id] = ['']; }; var insertRules = function insertRules(id, cssRules, name) { var marker = insertMarker(id); marker[0] += cssRules.join(' '); addNameForId(names, id, name); }; var removeRules = function removeRules(id) { var marker = markers[id]; if (marker === undefined) return; marker[0] = ''; resetIdNames(names, id); }; var css = function css() { var str = ''; // eslint-disable-next-line guard-for-in for (var id in markers) { var cssForId = markers[id][0]; if (cssForId) { str += makeTextMarker(id) + cssForId; } } return str; }; var clone = function clone() { var namesClone = cloneNames(names); var markersClone = Object.create(null); // eslint-disable-next-line guard-for-in for (var id in markers) { markersClone[id] = [markers[id][0]]; } return makeServerTag(namesClone, markersClone); }; var tag = { clone: clone, css: css, getIds: getIdsFromMarkersFactory(markers), hasNameForId: hasNameForId(names), insertMarker: insertMarker, insertRules: insertRules, removeRules: removeRules, sealed: false, styleTag: null, toElement: wrapAsElement(css, names), toHTML: wrapAsHtmlTag(css, names) }; return tag; }; var makeTag = function makeTag(target, tagEl, forceServer, insertBefore, getImportRuleTag) { if (IS_BROWSER && !forceServer) { var el = makeStyleTag(target, tagEl, insertBefore); if (DISABLE_SPEEDY) { return makeBrowserTag(el, getImportRuleTag); } else { return makeSpeedyTag(el, getImportRuleTag); } } return makeServerTag(); }; /* wraps a given tag so that rehydration is performed once when necessary */ var makeRehydrationTag = function makeRehydrationTag(tag, els, extracted, immediateRehydration) { /* rehydration function that adds all rules to the new tag */ var rehydrate = once(function () { /* add all extracted components to the new tag */ for (var i = 0, len = extracted.length; i < len; i += 1) { var _extracted$i = extracted[i], componentId = _extracted$i.componentId, cssFromDOM = _extracted$i.cssFromDOM; var cssRules = splitByRules(cssFromDOM); tag.insertRules(componentId, cssRules); } /* remove old HTMLStyleElements, since they have been rehydrated */ for (var _i = 0, _len = els.length; _i < _len; _i += 1) { var el = els[_i]; if (el.parentNode) { el.parentNode.removeChild(el); } } }); if (immediateRehydration) rehydrate(); return _extends({}, tag, { /* add rehydration hook to methods */ insertMarker: function insertMarker(id) { rehydrate(); return tag.insertMarker(id); }, insertRules: function insertRules(id, cssRules, name) { rehydrate(); return tag.insertRules(id, cssRules, name); }, removeRules: function removeRules(id) { rehydrate(); return tag.removeRules(id); } }); }; // var SPLIT_REGEX = /\s+/; /* determine the maximum number of components before tags are sharded */ var MAX_SIZE = void 0; if (IS_BROWSER) { /* in speedy mode we can keep a lot more rules in a sheet before a slowdown can be expected */ MAX_SIZE = DISABLE_SPEEDY ? 40 : 1000; } else { /* for servers we do not need to shard at all */ MAX_SIZE = -1; } var sheetRunningId = 0; var master = void 0; var StyleSheet = function () { /* a map from ids to tags */ /* deferred rules for a given id */ /* this is used for not reinjecting rules via hasNameForId() */ /* when rules for an id are removed using remove() we have to ignore rehydratedNames for it */ /* a list of tags belonging to this StyleSheet */ /* a tag for import rules */ /* current capacity until a new tag must be created */ /* children (aka clones) of this StyleSheet inheriting all and future injections */ function StyleSheet() { var _this = this; var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : IS_BROWSER ? document.head : null; var forceServer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; classCallCheck(this, StyleSheet); this.getImportRuleTag = function () { var importRuleTag = _this.importRuleTag; if (importRuleTag !== undefined) { return importRuleTag; } var firstTag = _this.tags[0]; var insertBefore = true; return _this.importRuleTag = makeTag(_this.target, firstTag ? firstTag.styleTag : null, _this.forceServer, insertBefore); }; sheetRunningId += 1; this.id = sheetRunningId; this.forceServer = forceServer; this.target = forceServer ? null : target; this.tagMap = {}; this.deferred = {}; this.rehydratedNames = {}; this.ignoreRehydratedNames = {}; this.tags = []; this.capacity = 1; this.clones = []; } /* rehydrate all SSR'd style tags */ StyleSheet.prototype.rehydrate = function rehydrate() { if (!IS_BROWSER || this.forceServer) { return this; } var els = []; var extracted = []; var isStreamed = false; /* retrieve all of our SSR style elements from the DOM */ var nodes = document.querySelectorAll('style[' + SC_ATTR + '][' + SC_VERSION_ATTR + '="' + "4.0.0-beta.10-5" + '"]'); var nodesSize = nodes.length; /* abort rehydration if no previous style tags were found */ if (nodesSize === 0) { return this; } for (var i = 0; i < nodesSize; i += 1) { // $FlowFixMe: We can trust that all elements in this query are style elements var el = nodes[i]; /* check if style tag is a streamed tag */ if (!isStreamed) isStreamed = !!el.getAttribute(SC_STREAM_ATTR); /* retrieve all component names */ var elNames = (el.getAttribute(SC_ATTR) || '').trim().split(SPLIT_REGEX); var elNamesSize = elNames.length; for (var j = 0; j < elNamesSize; j += 1) { var name = elNames[j]; /* add rehydrated name to sheet to avoid readding styles */ this.rehydratedNames[name] = true; } /* extract all components and their CSS */ extracted.push.apply(extracted, extractComps(el.textContent)); /* store original HTMLStyleElement */ els.push(el); } /* abort rehydration if nothing was extracted */ var extractedSize = extracted.length; if (extractedSize === 0) { return this; } /* create a tag to be used for rehydration */ var tag = this.makeTag(null); var rehydrationTag = makeRehydrationTag(tag, els, extracted, isStreamed); /* reset capacity and adjust MAX_SIZE by the initial size of the rehydration */ this.capacity = Math.max(1, MAX_SIZE - extractedSize); this.tags.push(rehydrationTag); /* retrieve all component ids */ for (var _j = 0; _j < extractedSize; _j += 1) { this.tagMap[extracted[_j].componentId] = rehydrationTag; } return this; }; /* retrieve a "master" instance of StyleSheet which is typically used when no other is available * The master StyleSheet is targeted by createGlobalStyle, keyframes, and components outside of any * StyleSheetManager's context */ /* reset the internal "master" instance */ StyleSheet.reset = function reset() { var forceServer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; master = new StyleSheet(undefined, forceServer).rehydrate(); }; /* adds "children" to the StyleSheet that inherit all of the parents' rules * while their own rules do not affect the parent */ StyleSheet.prototype.clone = function clone() { var sheet = new StyleSheet(this.target, this.forceServer); /* add to clone array */ this.clones.push(sheet); /* clone all tags */ sheet.tags = this.tags.map(function (tag) { var ids = tag.getIds(); var newTag = tag.clone(); /* reconstruct tagMap */ for (var i = 0; i < ids.length; i += 1) { sheet.tagMap[ids[i]] = newTag; } return newTag; }); /* clone other maps */ sheet.rehydratedNames = _extends({}, this.rehydratedNames); sheet.deferred = _extends({}, this.deferred); return sheet; }; /* force StyleSheet to create a new tag on the next injection */ StyleSheet.prototype.sealAllTags = function sealAllTags() { this.capacity = 1; this.tags.forEach(function (tag) { // eslint-disable-next-line no-param-reassign tag.sealed = true; }); }; StyleSheet.prototype.makeTag = function makeTag$$1(tag) { var lastEl = tag ? tag.styleTag : null; var insertBefore = false; return makeTag(this.target, lastEl, this.forceServer, insertBefore, this.getImportRuleTag); }; /* get a tag for a given componentId, assign the componentId to one, or shard */ StyleSheet.prototype.getTagForId = function getTagForId(id) { /* simply return a tag, when the componentId was already assigned one */ var prev = this.tagMap[id]; if (prev !== undefined && !prev.sealed) { return prev; } var tag = this.tags[this.tags.length - 1]; /* shard (create a new tag) if the tag is exhausted (See MAX_SIZE) */ this.capacity -= 1; if (this.capacity === 0) { this.capacity = MAX_SIZE; tag = this.makeTag(tag); this.tags.push(tag); } return this.tagMap[id] = tag; }; /* mainly for createGlobalStyle to check for its id */ StyleSheet.prototype.hasId = function hasId(id) { return this.tagMap[id] !== undefined; }; /* caching layer checking id+name to already have a corresponding tag and injected rules */ StyleSheet.prototype.hasNameForId = function hasNameForId(id, name) { /* exception for rehydrated names which are checked separately */ if (this.ignoreRehydratedNames[id] === undefined && this.rehydratedNames[name]) { return true; } var tag = this.tagMap[id]; return tag !== undefined && tag.hasNameForId(id, name); }; /* registers a componentId and registers it on its tag */ StyleSheet.prototype.deferredInject = function deferredInject(id, cssRules) { /* don't inject when the id is already registered */ if (this.tagMap[id] !== undefined) return; var clones = this.clones; for (var i = 0; i < clones.length; i += 1) { clones[i].deferredInject(id, cssRules); } this.getTagForId(id).insertMarker(id); this.deferred[id] = cssRules; }; /* injects rules for a given id with a name that will need to be cached */ StyleSheet.prototype.inject = function inject(id, cssRules, name) { var clones = this.clones; for (var i = 0; i < clones.length; i += 1) { clones[i].inject(id, cssRules, name); } var tag = this.getTagForId(id); /* add deferred rules for component */ if (this.deferred[id] !== undefined) { // Combine passed cssRules with previously deferred CSS rules // NOTE: We cannot mutate the deferred array itself as all clones // do the same (see clones[i].inject) var rules = this.deferred[id].concat(cssRules); tag.insertRules(id, rules, name); this.deferred[id] = undefined; } else { tag.insertRules(id, cssRules, name); } }; /* removes all rules for a given id, which doesn't remove its marker but resets it */ StyleSheet.prototype.remove = function remove(id) { var tag = this.tagMap[id]; if (tag === undefined) return; var clones = this.clones; for (var i = 0; i < clones.length; i += 1) { clones[i].remove(id); } /* remove all rules from the tag */ tag.removeRules(id); /* ignore possible rehydrated names */ this.ignoreRehydratedNames[id] = true; /* delete possible deferred rules */ this.deferred[id] = undefined; }; StyleSheet.prototype.toHTML = function toHTML() { return this.tags.map(function (tag) { return tag.toHTML(); }).join(''); }; StyleSheet.prototype.toReactElements = function toReactElements() { var id = this.id; return this.tags.map(function (tag, i) { var key = 'sc-' + id + '-' + i; return cloneElement(tag.toElement(), { key: key }); }); }; createClass(StyleSheet, null, [{ key: 'master', get: function get$$1() { return master || (master = new StyleSheet().rehydrate()); } /* NOTE: This is just for backwards-compatibility with jest-styled-components */ }, { key: 'instance', get: function get$$1() { return StyleSheet.master; } }]); return StyleSheet; }(); // var Keyframes = function () { function Keyframes(name, rules) { var _this = this; classCallCheck(this, Keyframes); this.inject = function (styleSheet) { if (!styleSheet.hasNameForId(_this.id, _this.name)) { styleSheet.inject(_this.id, _this.rules, _this.name); } }; this.name = name; this.rules = rules; this.id = 'sc-keyframes-' + name; } Keyframes.prototype.getName = function getName() { return this.name; }; return Keyframes; }(); // /** * inlined version of * https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/hyphenateStyleName.js */ var uppercasePattern = /([A-Z])/g; var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return string.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-'); } // var objToCss = function objToCss(obj, prevKey) { var css = Object.keys(obj).filter(function (key) { var chunk = obj[key]; return chunk !== undefined && chunk !== null && chunk !== false && chunk !== ''; }).map(function (key) { if (isPlainObject(obj[key])) return objToCss(obj[key], key); return hyphenateStyleName(key) + ': ' + obj[key] + ';'; }).join(' '); return prevKey ? prevKey + ' {\n ' + css + '\n}' : css; }; /** * It's falsish not falsy because 0 is allowed. */ var isFalsish = function isFalsish(chunk) { return chunk === undefined || chunk === null || chunk === false || chunk === ''; }; function flatten(chunk, executionContext, styleSheet) { if (Array.isArray(chunk)) { var ruleSet = []; for (var i = 0, len = chunk.length, result; i < len; i += 1) { result = flatten(chunk[i], executionContext, styleSheet); if (result === null) continue;else if (Array.isArray(result)) ruleSet.push.apply(ruleSet, result);else ruleSet.push(result); } return ruleSet; } if (isFalsish(chunk)) { return null; } /* Handle other components */ if (isStyledComponent(chunk)) { return '.' + chunk.styledComponentId; } /* Either execute or defer the function */ if (isFunction(chunk)) { if (executionContext) { if (process.env.NODE_ENV !== 'production') { /* Warn if not referring styled component */ // eslint-disable-next-line new-cap if (isElement(new chunk(executionContext))) { console.warn(getComponentName(chunk) + ' is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.'); } } return flatten(chunk(executionContext), executionContext, styleSheet); } else return chunk; } if (chunk instanceof Keyframes) { if (styleSheet) { chunk.inject(styleSheet); return chunk.getName(); } else return chunk; } /* Handle objects */ return isPlainObject(chunk) ? objToCss(chunk) : chunk.toString(); } // function css(styles) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } if (isFunction(styles) || isPlainObject(styles)) { // $FlowFixMe return flatten(interleave(EMPTY_ARRAY, [styles].concat(interpolations))); } // $FlowFixMe return flatten(interleave(styles, interpolations)); } // function constructWithOptions(componentConstructor, tag) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EMPTY_OBJECT; if (!isValidElementType(tag)) { throw new StyledComponentsError(1, String(tag)); } /* This is callable directly as a template function */ // $FlowFixMe: Not typed to avoid destructuring arguments var templateFunction = function templateFunction() { return componentConstructor(tag, options, css.apply(undefined, arguments)); }; /* If config methods are called, wrap up a new template function and merge options */ templateFunction.withConfig = function (config) { return constructWithOptions(componentConstructor, tag, _extends({}, options, config)); }; templateFunction.attrs = function (attrs) { return constructWithOptions(componentConstructor, tag, _extends({}, options, { attrs: _extends({}, options.attrs || EMPTY_OBJECT, attrs) })); }; return templateFunction; } // // Source: https://github.com/garycourt/murmurhash-js/blob/master/murmurhash2_gc.js function murmurhash(c) { for (var e = c.length | 0, a = e | 0, d = 0, b; e >= 4;) { b = c.charCodeAt(d) & 255 | (c.charCodeAt(++d) & 255) << 8 | (c.charCodeAt(++d) & 255) << 16 | (c.charCodeAt(++d) & 255) << 24, b = 1540483477 * (b & 65535) + ((1540483477 * (b >>> 16) & 65535) << 16), b ^= b >>> 24, b = 1540483477 * (b & 65535) + ((1540483477 * (b >>> 16) & 65535) << 16), a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16) ^ b, e -= 4, ++d; } switch (e) { case 3: a ^= (c.charCodeAt(d + 2) & 255) << 16; case 2: a ^= (c.charCodeAt(d + 1) & 255) << 8; case 1: a ^= c.charCodeAt(d) & 255, a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16); } a ^= a >>> 13; a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16); return (a ^ a >>> 15) >>> 0; } // /* eslint-disable no-bitwise */ /* This is the "capacity" of our alphabet i.e. 2x26 for all letters plus their capitalised * counterparts */ var charsLength = 52; /* start at 75 for 'a' until 'z' (25) and then start at 65 for capitalised letters */ var getAlphabeticChar = function getAlphabeticChar(code) { return String.fromCharCode(code + (code > 25 ? 39 : 97)); }; /* input a number, usually a hash and convert it to base-52 */ function generateAlphabeticName(code) { var name = ''; var x = void 0; /* get a char and divide by alphabet-length */ for (x = code; x > charsLength; x = Math.floor(x / charsLength)) { name = getAlphabeticChar(x % charsLength) + name; } return getAlphabeticChar(x % charsLength) + name; } // function isStaticRules(rules, attrs) { for (var i = 0; i < rules.length; i += 1) { var rule = rules[i]; // recursive case if (Array.isArray(rule) && !isStaticRules(rule)) { return false; } else if (isFunction(rule) && !isStyledComponent(rule)) { // functions are allowed to be static if they're just being // used to get the classname of a nested styled component return false; } } if (attrs !== undefined) { // eslint-disable-next-line guard-for-in, no-restricted-syntax for (var key in attrs) { var value = attrs[key]; if (isFunction(value)) { return false; } } } return true; } // // var isHMREnabled = process.env.NODE_ENV !== 'production' && typeof module !== 'undefined' && module.hot; /* combines hashStr (murmurhash) and nameGenerator for convenience */ var hasher = function hasher(str) { return generateAlphabeticName(murmurhash(str)); }; /* ComponentStyle is all the CSS-specific stuff, not the React-specific stuff. */ var ComponentStyle = function () { function ComponentStyle(rules, attrs, componentId) { classCallCheck(this, ComponentStyle); this.rules = rules; this.isStatic = !isHMREnabled && isStaticRules(rules, attrs); this.componentId = componentId; if (!StyleSheet.master.hasId(componentId)) { var placeholder = process.env.NODE_ENV !== 'production' ? ['.' + componentId + ' {}'] : []; StyleSheet.master.deferredInject(componentId, placeholder); } } /* * Flattens a rule set into valid CSS * Hashes it, wraps the whole chunk in a .hash1234 {} * Returns the hash to be injected on render() * */ ComponentStyle.prototype.generateAndInjectStyles = function generateAndInjectStyles(executionContext, styleSheet) { var isStatic = this.isStatic, componentId = this.componentId, lastClassName = this.lastClassName; if (IS_BROWSER && isStatic && lastClassName !== undefined && styleSheet.hasNameForId(componentId, lastClassName)) { return lastClassName; } var flatCSS = flatten(this.rules, executionContext, styleSheet); var name = hasher(this.componentId + flatCSS.join('')); if (!styleSheet.hasNameForId(componentId, name)) { styleSheet.inject(this.componentId, stringifyRules(flatCSS, '.' + name, undefined, componentId), name); } this.lastClassName = name; return name; }; ComponentStyle.generateName = function generateName(str) { return hasher(str); }; return ComponentStyle; }(); // var LIMIT = 200; var createWarnTooManyClasses = (function (displayName) { var generatedClasses = {}; var warningSeen = false; return function (className) { if (!warningSeen) { generatedClasses[className] = true; if (Object.keys(generatedClasses).length >= LIMIT) { // Unable to find latestRule in test environment. /* eslint-disable no-console, prefer-template */ console.warn('Over ' + LIMIT + ' classes were generated for component ' + displayName + '. \n' + 'Consider using the attrs method, together with a style object for frequently changed styles.\n' + 'Example:\n' + ' const Component = styled.div.attrs({\n' + ' style: ({ background }) => ({\n' + ' background,\n' + ' }),\n' + ' })`width: 100%;`\n\n' + ' <Component />'); warningSeen = true; generatedClasses = {}; } } }; }); // var determineTheme = (function (props, fallbackTheme) { var defaultProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EMPTY_OBJECT; // Props should take precedence over ThemeProvider, which should take precedence over // defaultProps, but React automatically puts defaultProps on props. /* eslint-disable react/prop-types, flowtype-errors/show-errors */ var isDefaultTheme = defaultProps ? props.theme === defaultProps.theme : false; var theme = props.theme && !isDefaultTheme ? props.theme : fallbackTheme || defaultProps.theme; /* eslint-enable */ return theme; }); // var escapeRegex = /[[\].#*$><+~=|^:(),"'`-]+/g; var dashesAtEnds = /(^-|-$)/g; /** * TODO: Explore using CSS.escape when it becomes more available * in evergreen browsers. */ function escape(str) { return str // Replace all possible CSS selectors .replace(escapeRegex, '-') // Remove extraneous hyphens at the start and end .replace(dashesAtEnds, ''); } // function isTag(target) /* : %checks */{ return typeof target === 'string'; } // function generateDisplayName(target) { return isTag(target) ? 'styled.' + target : 'Styled(' + getComponentName(target) + ')'; } var _TYPE_STATICS; var REACT_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDerivedStateFromProps: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, callee: true, arguments: true, arity: true }; var TYPE_STATICS = (_TYPE_STATICS = {}, _TYPE_STATICS[ForwardRef] = { $$typeof: true, render: true }, _TYPE_STATICS); var defineProperty$1 = Object.defineProperty, getOwnPropertyNames = Object.getOwnPropertyNames, _Object$getOwnPropert = Object.getOwnPropertySymbols, getOwnPropertySymbols = _Object$getOwnPropert === undefined ? function () { return []; } : _Object$getOwnPropert, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor, getPrototypeOf = Object.getPrototypeOf, objectPrototype = Object.prototype; var arrayPrototype = Array.prototype; function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components var inheritedComponent = getPrototypeOf(sourceComponent); if (inheritedComponent && inheritedComponent !== objectPrototype) { hoistNonReactStatics(targetComponent, inheritedComponent, blacklist); } var keys = arrayPrototype.concat(getOwnPropertyNames(sourceComponent), // $FlowFixMe getOwnPropertySymbols(sourceComponent)); var targetStatics = TYPE_STATICS[targetComponent.$$typeof] || REACT_STATICS; var sourceStatics = TYPE_STATICS[sourceComponent.$$typeof] || REACT_STATICS; var i = keys.length; var descriptor = void 0; var key = void 0; // eslint-disable-next-line no-plusplus while (i--) { key = keys[i]; if ( // $FlowFixMe !KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && // $FlowFixMe !(targetStatics && targetStatics[key])) { descriptor = getOwnPropertyDescriptor(sourceComponent, key); if (descriptor) { try { // Avoid failures from read-only properties defineProperty$1(targetComponent, key, descriptor); } catch (e) { /* fail silently */ } } } } return targetComponent; } return targetComponent; } // function isDerivedReactComponent(fn) { return !!(fn && fn.prototype && fn.prototype.isReactComponent); } // var ThemeContext = createContext(); var ThemeConsumer = ThemeContext.Consumer; /** * Provide a theme to an entire react component tree via context */ var ThemeProvider = function (_Component) { inherits(ThemeProvider, _Component); function ThemeProvider(props) { classCallCheck(this, ThemeProvider); var _this = possibleConstructorReturn(this, _Component.call(this, props)); _this.getContext = memoize(_this.getContext.bind(_this)); _this.renderInner = _this.renderInner.bind(_this); return _this; } ThemeProvider.prototype.render = function render() { if (!this.props.children) return null; return React.createElement( ThemeContext.Consumer, null, this.renderInner ); }; ThemeProvider.prototype.renderInner = function renderInner(outerTheme) { var context = this.getContext(this.props.theme, outerTheme); return React.createElement( ThemeContext.Provider, { value: context }, React.Children.only(this.props.children) ); }; /** * Get the theme from the props, supporting both (outerTheme) => {} * as well as object notation */ ThemeProvider.prototype.getTheme = function getTheme(theme, outerTheme) { if (isFunction(theme)) { var mergedTheme = theme(outerTheme); if (process.env.NODE_ENV !== 'production' && (mergedTheme === null || Array.isArray(mergedTheme) || (typeof mergedTheme === 'undefined' ? 'undefined' : _typeof(mergedTheme)) !== 'object')) { throw new StyledComponentsError(7); } return mergedTheme; } if (theme === null || Array.isArray(theme) || (typeof theme === 'undefined' ? 'undefined' : _typeof(theme)) !== 'object') { throw new StyledComponentsError(8); } return _extends({}, outerTheme, theme); }; ThemeProvider.prototype.getContext = function getContext(theme, outerTheme) { return this.getTheme(theme, outerTheme); }; return ThemeProvider; }(Component); // var ServerStyleSheet = function () { function ServerStyleSheet() { classCallCheck(this, ServerStyleSheet); /* The master sheet might be reset, so keep a reference here */ this.masterSheet = StyleSheet.master; this.instance = this.masterSheet.clone(); this.sealed = false; } /** * Mark the ServerStyleSheet as being fully emitted and manually GC it from the * StyleSheet singleton. */ ServerStyleSheet.prototype.seal = function seal() { if (!this.sealed) { /* Remove sealed StyleSheets from the master sheet */ var index = this.masterSheet.clones.indexOf(this.instance); this.masterSheet.clones.splice(index, 1); this.sealed = true; } }; ServerStyleSheet.prototype.collectStyles = function collectStyles(children) { if (this.sealed) { throw new StyledComponentsError(2); } return React.createElement( StyleSheetManager, { sheet: this.instance }, children ); }; ServerStyleSheet.prototype.getStyleTags = function getStyleTags() { this.seal(); return this.instance.toHTML(); }; ServerStyleSheet.prototype.getStyleElement = function getStyleElement() { this.seal(); return this.instance.toReactElements(); }; ServerStyleSheet.prototype.interleaveWithNodeStream = function interleaveWithNodeStream(readableStream) { var _this = this; if (IS_BROWSER) { throw new StyledComponentsError(3); } /* the tag index keeps track of which tags have already been emitted */ var instance = this.instance; var instanceTagIndex = 0; var streamAttr = SC_STREAM_ATTR + '="true"'; var transformer = new stream.Transform({ transform: function appendStyleChunks(chunk, /* encoding */_, callback) { var tags = instance.tags; var html = ''; /* retrieve html for each new style tag */ for (; instanceTagIndex < tags.length; instanceTagIndex += 1) { var tag = tags[instanceTagIndex]; html += tag.toHTML(streamAttr); } /* force our StyleSheets to emit entirely new tags */ instance.sealAllTags(); /* prepend style html to chunk */ this.push(html + chunk); callback(); } }); readableStream.on('end', function () { return _this.seal(); }); readableStream.on('error', function (err) { _this.seal(); // forward the error to the transform stream transformer.emit('error', err); }); return readableStream.pipe(transformer); }; return ServerStyleSheet; }(); // var StyleSheetContext = createContext(); var StyleSheetConsumer = StyleSheetContext.Consumer; var StyleSheetManager = function (_Component) { inherits(StyleSheetManager, _Component); function StyleSheetManager(props) { classCallCheck(this, StyleSheetManager); var _this = possibleConstructorReturn(this, _Component.call(this, props)); _this.getContext = memoize(_this.getContext); return _this; } StyleSheetManager.prototype.getContext = function getContext(sheet, target) { if (sheet) { return sheet; } else if (target) { return new StyleSheet(target); } else { throw new StyledComponentsError(4); } }; StyleSheetManager.prototype.render = function render() { var _props = this.props, children = _props.children, sheet = _props.sheet, target = _props.target; var context = this.getContext(sheet, target); return React.createElement( StyleSheetContext.Provider, { value: context }, React.Children.only(children) ); }; return StyleSheetManager; }(Component); process.env.NODE_ENV !== "production" ? StyleSheetManager.propTypes = { sheet: PropTypes.oneOfType([PropTypes.instanceOf(StyleSheet), PropTypes.instanceOf(ServerStyleSheet)]), target: PropTypes.shape({ appendChild: PropTypes.func.isRequired }) } : void 0; // var identifiers = {}; /* We depend on components having unique IDs */ function generateId(_ComponentStyle, _displayName, parentComponentId) { var displayName = typeof _displayName !== 'string' ? 'sc' : escape(_displayName); /** * This ensures uniqueness if two components happen to share * the same displayName. */ var nr = (identifiers[displayName] || 0) + 1; identifiers[displayName] = nr; var componentId = displayName + '-' + _ComponentStyle.generateName(displayName + nr); return parentComponentId ? parentComponentId + '-' + componentId : componentId; } var warnInnerRef = once(function () { return ( // eslint-disable-next-line no-console console.warn('The "innerRef" API has been removed in styled-components v4 in favor of React 16 ref forwarding, use "ref" instead like a typical component.') ); }); // $FlowFixMe var StyledComponent = function (_Component) { inherits(StyledComponent, _Component); function StyledComponent() { classCallCheck(this, StyledComponent); var _this = possibleConstructorReturn(this, _Component.call(this)); _this.attrs = {}; _this.renderOuter = _this.renderOuter.bind(_this); _this.renderInner = _this.renderInner.bind(_this); return _this; } StyledComponent.prototype.render = function render() { return React.createElement( StyleSheetConsumer, null, this.renderOuter ); }; StyledComponent.prototype.renderOuter = function renderOuter(styleSheet) { this.styleSheet = styleSheet; return React.createElement( ThemeConsumer, null, this.renderInner ); }; StyledComponent.prototype.renderInner = function renderInner(theme) { var _props$forwardedClass = this.props.forwardedClass, componentStyle = _props$forwardedClass.componentStyle, defaultProps = _props$forwardedClass.defaultProps, styledComponentId = _props$forwardedClass.styledComponentId, target = _props$forwardedClass.target; var generatedClassName = void 0; if (componentStyle.isStatic) { generatedClassName = this.generateAndInjectStyles(EMPTY_OBJECT, this.props, this.styleSheet); } else if (theme !== undefined) { generatedClassName = this.generateAndInjectStyles(determineTheme(this.props, theme, defaultProps), this.props, this.styleSheet); } else { generatedClassName = this.generateAndInjectStyles(this.props.theme || EMPTY_OBJECT, this.props, this.styleSheet); } var elementToBeCreated = this.props.as || this.attrs.as || target; var isTargetTag = isTag(elementToBeCreated); var propsForElement = _extends({}, this.attrs); var key = void 0; // eslint-disable-next-line guard-for-in for (key in this.props) { if (process.env.NODE_ENV !== 'production' && key === 'innerRef') { warnInnerRef(); } if (key === 'forwardedClass' || key === 'as') continue;else if (key === 'forwardedRef') propsForElement.ref = this.props[key];else if (!isTargetTag || validAttr(key)) { // Don't pass through non HTML tags through to HTML elements propsForElement[key] = key === 'style' && key in this.attrs ? _extends({}, this.attrs[key], this.props[key]) : this.props[key]; } } propsForElement.className = [this.props.className, styledComponentId, this.attrs.className, generatedClassName].filter(Boolean).join(' '); return createElement(elementToBeCreated, propsForElement); }; StyledComponent.prototype.buildExecutionContext = function buildExecutionContext(theme, props, attrs) { var context = _extends({}, props, { theme: theme }); if (attrs === undefined) return context; this.attrs = {}; var attr = void 0; var key = void 0; /* eslint-disable guard-for-in */ for (key in attrs) { attr = attrs[key]; this.attrs[key] = isFunction(attr) && !isDerivedReactComponent(attr) && !isStyledComponent(attr) ? attr(context) : attr; } /* eslint-enable */ return _extends({}, context, this.attrs); }; StyledComponent.prototype.generateAndInjectStyles = function generateAndInjectStyles(theme, props) { var styleSheet = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : StyleSheet.master; var _props$forwardedClass2 = props.forwardedClass, attrs = _props$forwardedClass2.attrs, componentStyle = _props$forwardedClass2.componentStyle, warnTooManyClasses = _props$forwardedClass2.warnTooManyClasses; // statically styled-components don't need to build an execution context object, // and shouldn't be increasing the number of class names if (componentStyle.isStatic && attrs === undefined) { return componentStyle.generateAndInjectStyles(EMPTY_OBJECT, styleSheet); } var className = componentStyle.generateAndInjectStyles(this.buildExecutionContext(theme, props, props.forwardedClass.attrs), styleSheet); if (warnTooManyClasses) { warnTooManyClasses(className); } return className; }; return StyledComponent; }(Component); function createStyledComponent(target, options, rules) { var isTargetStyledComp = isStyledComponent(target); var isClass = !isTag(target); var _options$displayName = options.displayName, displayName = _options$displayName === undefined ? generateDisplayName(target) : _options$displayName, _options$componentId = options.componentId, componentId = _options$componentId === undefined ? generateId(ComponentStyle, options.displayName, options.parentComponentId) : _options$componentId, _options$ParentCompon = options.ParentComponent, ParentComponent = _options$ParentCompon === undefined ? StyledComponent : _options$ParentCompon, attrs = options.attrs; var styledComponentId = options.displayName && options.componentId ? escape(options.displayName) + '-' + options.componentId : options.componentId || componentId; // fold the underlying StyledComponent attrs up (implicit extend) var finalAttrs = // $FlowFixMe isTargetStyledComp && target.attrs ? _extends({}, target.attrs, attrs) : attrs; var componentStyle = new ComponentStyle(isTargetStyledComp ? // fold the underlying StyledComponent rules up (implicit extend) // $FlowFixMe target.componentStyle.rules.concat(rules) : rules, finalAttrs, styledComponentId); /** * forwardRef creates a new interim component, which we'll take advantage of * instead of extending ParentComponent to create _another_ interim class */ var WrappedStyledComponent = React.forwardRef(function (props, ref) { return React.createElement(ParentComponent, _extends({}, props, { forwardedClass: WrappedStyledComponent, forwardedRef: ref })); }); // $FlowFixMe WrappedStyledComponent.attrs = finalAttrs; // $FlowFixMe WrappedStyledComponent.componentStyle = componentStyle; WrappedStyledComponent.displayName = displayName; // $FlowFixMe WrappedStyledComponent.styledComponentId = styledComponentId; // fold the underlying StyledComponent target up since we folded the styles // $FlowFixMe WrappedStyledComponent.target = isTargetStyledComp ? target.target : target; // $FlowFixMe WrappedStyledComponent.withComponent = function withComponent(tag) { var previousComponentId = options.componentId, optionsToCopy = objectWithoutProperties(options, ['componentId']); var newComponentId = previousComponentId && previousComponentId + '-' + (isTag(tag) ? tag : escape(getComponentName(tag))); var newOptions = _extends({}, optionsToCopy, { attrs: finalAttrs, componentId: newComponentId, ParentComponent: ParentComponent }); return createStyledComponent(tag, newOptions, rules); }; if (process.env.NODE_ENV !== 'production') { // $FlowFixMe WrappedStyledComponent.warnTooManyClasses = createWarnTooManyClasses(displayName); } if (isClass) { hoistNonReactStatics(WrappedStyledComponent, target, { // all SC-specific things should not be hoisted attrs: true, componentStyle: true, displayName: true, styledComponentId: true, target: true, warnTooManyClasses: true, withComponent: true }); } return WrappedStyledComponent; } // // Thanks to ReactDOMFactories for this handy list! var domElements = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', // SVG 'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan']; // var styled = function styled(tag) { return constructWithOptions(createStyledComponent, tag); }; // Shorthands for all valid HTML Elements domElements.forEach(function (domElement) { styled[domElement] = styled(domElement); }); // var GlobalStyle = function () { function GlobalStyle(rules, componentId) { classCallCheck(this, GlobalStyle); this.rules = rules; this.componentId = componentId; this.isStatic = isStaticRules(rules); if (!StyleSheet.master.hasId(componentId)) { StyleSheet.master.deferredInject(componentId, []); } } GlobalStyle.prototype.createStyles = function createStyles(executionContext, styleSheet) { var flatCSS = flatten(this.rules, executionContext, styleSheet); var css = stringifyRules(flatCSS, ''); styleSheet.inject(this.componentId, css); }; GlobalStyle.prototype.removeStyles = function removeStyles(styleSheet) { var componentId = this.componentId; if (styleSheet.hasId(componentId)) { styleSheet.remove(componentId); } }; // TODO: overwrite in-place instead of remove+create? GlobalStyle.prototype.renderStyles = function renderStyles(executionContext, styleSheet) { this.removeStyles(styleSheet); this.createStyles(executionContext, styleSheet); }; return GlobalStyle; }(); function getHMR() { return module.hot; } // function createGlobalStyle(strings) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(undefined, [strings].concat(interpolations)); var id = 'sc-global-' + murmurhash(JSON.stringify(rules)); var style = new GlobalStyle(rules, id); var count = 0; var GlobalStyleComponent = function (_React$Component) { inherits(GlobalStyleComponent, _React$Component); function GlobalStyleComponent() { classCallCheck(this, GlobalStyleComponent); var _this = possibleConstructorReturn(this, _React$Component.call(this)); count += 1; /** * This fixes HMR compatiblility. Don't ask me why, but this combination of * caching the closure variables via statics and then persisting the statics in * state works across HMR where no other combination did. ¯\_(ツ)_/¯ */ _this.state = { globalStyle: _this.constructor.globalStyle, styledComponentId: _this.constructor.styledComponentId }; return _this; } GlobalStyleComponent.prototype.componentDidMount = function componentDidMount() { if (process.env.NODE_ENV !== 'production' && IS_BROWSER && count > 1) { console.warn('The global style component ' + this.state.styledComponentId + ' was composed and rendered multiple times in your React component tree. Only the last-rendered copy will have its styles remain in <head> (or your StyleSheetManager target.)'); } }; GlobalStyleComponent.prototype.componentWillUnmount = function componentWillUnmount() { count -= 1; /** * Depending on the order "render" is called this can cause the styles to be lost * until the next render pass of the remaining instance, which may * not be immediate. */ if (count === 0) this.state.globalStyle.removeStyles(this.styleSheet); }; GlobalStyleComponent.prototype.render = function render() { var _this2 = this; if (process.env.NODE_ENV !== 'production' && React.Children.count(this.props.children)) { console.warn('The global style component ' + this.state.styledComponentId + ' was given child JSX. createGlobalStyle does not render children.'); } return React.createElement( StyleSheetConsumer, null, function (styleSheet) { _this2.styleSheet = styleSheet || StyleSheet.master; var globalStyle = _this2.state.globalStyle; if (globalStyle.isStatic) { globalStyle.renderStyles(STATIC_EXECUTION_CONTEXT, _this2.styleSheet); return null; } else { return React.createElement( ThemeConsumer, null, function (theme) { var defaultProps = _this2.constructor.defaultProps; var context = _extends({}, _this2.props); if (typeof theme !== 'undefined') { context.theme = determineTheme(_this2.props, theme, defaultProps); } globalStyle.renderStyles(context, _this2.styleSheet); return null; } ); } } ); }; return GlobalStyleComponent; }(React.Component); GlobalStyleComponent.globalStyle = style; GlobalStyleComponent.styledComponentId = id; if (process.env.NODE_ENV !== 'production' && getHMR()) getHMR().dispose(function () { return style.removeStyles(StyleSheet.master); }); return GlobalStyleComponent; } // var replaceWhitespace = function replaceWhitespace(str) { return str.replace(/\s|\\n/g, ''); }; function keyframes(strings) { /* Warning if you've used keyframes on React Native */ if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { console.warn('`keyframes` cannot be used on ReactNative, only on the web. To do animation in ReactNative please use Animated.'); } for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(undefined, [strings].concat(interpolations)); var name = generateAlphabeticName(murmurhash(replaceWhitespace(JSON.stringify(rules)))); return new Keyframes(name, stringifyRules(rules, name, '@keyframes')); } // var withTheme = (function (Component$$1) { var WithTheme = React.forwardRef(function (props, ref) { return React.createElement( ThemeConsumer, null, function (theme) { // $FlowFixMe var defaultProps = Component$$1.defaultProps; var themeProp = determineTheme(props, theme, defaultProps); if (process.env.NODE_ENV !== 'production' && themeProp === undefined) { // eslint-disable-next-line no-console console.warn('[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class ' + getComponentName(Component$$1)); } return React.createElement(Component$$1, _extends({}, props, { theme: themeProp, ref: ref })); } ); }); hoistNonReactStatics(WithTheme, Component$$1); WithTheme.displayName = 'WithTheme(' + getComponentName(Component$$1) + ')'; return WithTheme; }); // /* eslint-disable */ var __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS = { StyleSheet: StyleSheet }; // /* Warning if you've imported this file on React Native */ if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { // eslint-disable-next-line no-console console.warn("It looks like you've imported 'styled-components' on React Native.\n" + "Perhaps you're looking to import 'styled-components/native'?\n" + 'Read more about this at https://www.styled-components.com/docs/basics#react-native'); } /* Warning if there are several instances of styled-components */ if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test' && typeof window !== 'undefined' && typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Node.js') === -1 && navigator.userAgent.indexOf('jsdom') === -1) { window['__styled-components-init__'] = window['__styled-components-init__'] || 0; if (window['__styled-components-init__'] === 1) { // eslint-disable-next-line no-console console.warn("It looks like there are several instances of 'styled-components' initialized in this application. " + 'This may cause dynamic styles not rendering properly, errors happening during rehydration process ' + 'and makes your application bigger without a good reason.\n\n' + 'See https://s-c.sh/2BAXzed for more info.'); } window['__styled-components-init__'] += 1; } // export default styled; export { css, keyframes, createGlobalStyle, isStyledComponent, ThemeConsumer, ThemeProvider, withTheme, ServerStyleSheet, StyleSheetManager, __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS }; //# sourceMappingURL=styled-components.esm.js.map
import { __decorate, __metadata } from 'tslib'; import { ɵɵdefineInjectable, ɵɵinject, Injectable } from '@angular/core'; import { Angulartics2 } from 'angulartics2'; var facebookEventList = [ 'ViewContent', 'Search', 'AddToCart', 'AddToWishlist', 'InitiateCheckout', 'AddPaymentInfo', 'Purchase', 'Lead', 'CompleteRegistration', ]; var Angulartics2Facebook = /** @class */ (function () { function Angulartics2Facebook(angulartics2) { this.angulartics2 = angulartics2; } Angulartics2Facebook.prototype.startTracking = function () { var _this = this; this.angulartics2.eventTrack .pipe(this.angulartics2.filterDeveloperMode()) .subscribe(function (x) { return _this.eventTrack(x.action, x.properties); }); }; /** * Send interactions to the Pixel, i.e. for event tracking in Pixel * * @param action action associated with the event */ Angulartics2Facebook.prototype.eventTrack = function (action, properties) { if (properties === void 0) { properties = {}; } if (typeof fbq === 'undefined') { return; } if (facebookEventList.indexOf(action) === -1) { return fbq('trackCustom', action, properties); } return fbq('track', action, properties); }; Angulartics2Facebook.ngInjectableDef = ɵɵdefineInjectable({ factory: function Angulartics2Facebook_Factory() { return new Angulartics2Facebook(ɵɵinject(Angulartics2)); }, token: Angulartics2Facebook, providedIn: "root" }); Angulartics2Facebook = __decorate([ Injectable({ providedIn: 'root' }), __metadata("design:paramtypes", [Angulartics2]) ], Angulartics2Facebook); return Angulartics2Facebook; }()); export { Angulartics2Facebook }; //# sourceMappingURL=angulartics2-facebook.js.map
require('../../modules/es.string.fontsize'); module.exports = require('../../internals/entry-unbind')('String', 'fontsize');
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; import { Injectable } from 'angular2/angular2'; import { global } from 'angular2/src/facade/lang'; let _nextRequestId = 0; export const JSONP_HOME = '__ng_jsonp__'; var _jsonpConnections = null; function _getJsonpConnections() { if (_jsonpConnections === null) { _jsonpConnections = global[JSONP_HOME] = {}; } return _jsonpConnections; } // Make sure not to evaluate this in a non-browser environment! export let BrowserJsonp = class { // Construct a <script> element with the specified URL build(url) { let node = document.createElement('script'); node.src = url; return node; } nextRequestID() { return `__req${_nextRequestId++}`; } requestCallback(id) { return `${JSONP_HOME}.${id}.finished`; } exposeConnection(id, connection) { let connections = _getJsonpConnections(); connections[id] = connection; } removeConnection(id) { var connections = _getJsonpConnections(); connections[id] = null; } // Attach the <script> element to the DOM send(node) { document.body.appendChild((node)); } // Remove <script> element from the DOM cleanup(node) { if (node.parentNode) { node.parentNode.removeChild((node)); } } }; BrowserJsonp = __decorate([ Injectable(), __metadata('design:paramtypes', []) ], BrowserJsonp); //# sourceMappingURL=browser_jsonp.js.map
this.primereact = this.primereact || {}; this.primereact.steps = (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 _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 _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } 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 _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 Steps = /*#__PURE__*/function (_Component) { _inherits(Steps, _Component); var _super = _createSuper(Steps); function Steps() { _classCallCheck(this, Steps); return _super.apply(this, arguments); } _createClass(Steps, [{ key: "itemClick", value: function itemClick(event, item, index) { if (this.props.readOnly || item.disabled) { event.preventDefault(); return; } if (this.props.onSelect) { this.props.onSelect({ originalEvent: event, item: item, index: index }); } if (!item.url) { event.preventDefault(); } if (item.command) { item.command({ originalEvent: event, item: item, index: index }); } } }, { key: "renderItem", value: function renderItem(item, index) { var _this = this; var active = index === this.props.activeIndex; var disabled = item.disabled || index !== this.props.activeIndex && this.props.readOnly; var className = core.classNames('p-steps-item', item.className, { 'p-highlight p-steps-current': active, 'p-disabled': disabled }); var label = item.label && /*#__PURE__*/React__default['default'].createElement("span", { className: "p-steps-title" }, item.label); var tabIndex = disabled ? -1 : ''; var content = /*#__PURE__*/React__default['default'].createElement("a", { href: item.url || '#', className: "p-menuitem-link", role: "presentation", target: item.target, onClick: function onClick(event) { return _this.itemClick(event, item, index); }, tabIndex: tabIndex, "aria-disabled": disabled }, /*#__PURE__*/React__default['default'].createElement("span", { className: "p-steps-number" }, index + 1), label); if (item.template) { var defaultContentOptions = { onClick: function onClick(event) { return _this.itemClick(event, item, index); }, className: 'p-menuitem-link', labelClassName: 'p-steps-title', numberClassName: 'p-steps-number', element: content, props: this.props, tabIndex: tabIndex, active: active, disabled: disabled }; content = core.ObjectUtils.getJSXElement(item.template, item, defaultContentOptions); } return /*#__PURE__*/React__default['default'].createElement("li", { key: item.label + '_' + index, className: className, style: item.style, role: "tab", "aria-selected": active, "aria-expanded": active }, content); } }, { key: "renderItems", value: function renderItems() { var _this2 = this; if (this.props.model) { var items = this.props.model.map(function (item, index) { return _this2.renderItem(item, index); }); return /*#__PURE__*/React__default['default'].createElement("ul", { role: "tablist" }, items); } return null; } }, { key: "render", value: function render() { var className = core.classNames('p-steps p-component', this.props.className, { 'p-readonly': this.props.readOnly }); var items = this.renderItems(); return /*#__PURE__*/React__default['default'].createElement("div", { id: this.props.id, className: className, style: this.props.style }, items); } }]); return Steps; }(React.Component); _defineProperty(Steps, "defaultProps", { id: null, model: null, activeIndex: 0, readOnly: true, style: null, className: null, onSelect: null }); exports.Steps = Steps; Object.defineProperty(exports, '__esModule', { value: true }); return exports; }({}, React, primereact.core));
define(['exports', 'module'], function (exports, module) { 'use strict'; module.exports = deprecationWarning; function deprecationWarning(oldname, newname, link) { if (process.env.NODE_ENV !== 'production') { if (!window.console && typeof console.warn !== 'function') { return; } var message = '' + oldname + ' is deprecated. Use ' + newname + ' instead.'; console.warn(message); if (link) { console.warn('You can read more about it here ' + link); } } } });
/** * Interaction manages all aspects of user interaction - mouse move, * click, hover, drag events, touch gestures. * * [[InteractionObject]] elements that want to use certain events, must attach event * listeners to Interaction instance. * * Interaction itself will not modify [[InteractionObject]] elements, it will be up to * those elements to handle interaction information received via event triggers. */ import { __extends } from "tslib"; /** * ============================================================================ * IMPORTS * ============================================================================ * @hidden */ import { BaseObjectEvents } from "../Base"; import { List } from "../utils/List"; import { Animation } from "../utils/Animation"; import { MultiDisposer } from "../utils/Disposer"; import { InteractionObject } from "./InteractionObject"; import { InteractionKeyboardObject } from "./InteractionKeyboardObject"; import { Dictionary } from "../utils/Dictionary"; import { Inertia } from "./Inertia"; import { addEventListener } from "../utils/DOM"; import { keyboard } from "../utils/Keyboard"; import { system } from "./../System"; import { options } from "./../Options"; import * as $ease from "../utils/Ease"; import * as $math from "../utils/Math"; import * as $array from "../utils/Array"; import * as $dom from "../utils/DOM"; import * as $iter from "../utils/Iterator"; import * as $type from "../utils/Type"; import * as $time from "../utils/Time"; /** * ============================================================================ * MAIN CLASS * ============================================================================ * @hidden */ /** * Interaction manages all aspects of user interaction - mouse move, * click, hover, drag events, touch gestures. * * [[InteractionObject]] elements that want to use certain events, must attach event * listeners to Interaction instance. * * Interaction itself will not modify [[InteractionObject]] elements, it will be up to * those elements to handle interaction information received via event triggers. * * @see {@link IInteractionEvents} for a list of available events */ var Interaction = /** @class */ (function (_super) { __extends(Interaction, _super); /** * Constructor. Sets up universal document-wide move events to handle stuff * outside particular chart container. */ function Interaction() { var _this = // Call super _super.call(this) || this; /** * An indicator of global events were already initialized. */ _this._globalEventsAdded = false; /** * Holds which mouse event listeners to use. */ _this._pointerEvents = { "pointerdown": "mousedown", "pointerup": "mouseup", "pointermove": "mousemove", "pointercancel": "mouseup", "pointerover": "mouseover", "pointerout": "mouseout", "wheel": "wheel" }; /** * Indicates if Interaction should use only "pointer" type events, like * "pointermove", available in all modern browsers, ignoring "legacy" * events, like "touchmove". */ _this._usePointerEventsOnly = false; /** * Use only touch events (for touch only devices such as tablets and phones) */ _this._useTouchEventsOnly = false; /** * Add special hover events. Normally, touch device tap will also simulate * hover event. On some devices (ahem iOS) we want to prevent that so that * over/out events are not duplicated. */ _this._addHoverEvents = true; /** * Indicates if passive mode options is supported by this browser. */ _this._passiveSupported = false; /** * Holds list of delayed events */ _this._delayedEvents = { out: [] }; /** * List of objects that current have a pointer hovered over them. */ _this.overObjects = new List(); /** * List of objects that currently has a pressed pointer. */ _this.downObjects = new List(); /** * List of objects that need mouse position to be reported to them. */ _this.trackedObjects = new List(); /** * List of objects that are currently being dragged. */ _this.transformedObjects = new List(); /** * Holds all known pointers. */ _this.pointers = new Dictionary(); /** * Inertia options that need to be applied to after element drag, if it's * `inert = true`. * * This is just a default, which can and probably will be overridden by * actual elements. */ _this.inertiaOptions = new Dictionary(); /** * Default options for click events. These can be overridden in * [[InteractionObject]]. */ _this.hitOptions = { //"holdTime": 1000, "doubleHitTime": 300, //"delayFirstHit": false, "hitTolerance": 10, "noFocus": true }; /** * Default options for hover events. These can be overridden in * [[InteractionObject]]. */ _this.hoverOptions = { "touchOutBehavior": "leave", "touchOutDelay": 1000 }; /** * Default options for detecting a swipe gesture. These can be overridden in * [[InteractionObject]]. */ _this.swipeOptions = { "time": 500, "verticalThreshold": 75, "horizontalThreshold": 30 }; /** * Default options for keyboard operations. These can be overridden in * [[InteractionObject]]. */ _this.keyboardOptions = { "speed": 0.1, "accelleration": 1.2, "accellerationDelay": 2000 }; /** * Default options for keyboard operations. These can be overridden in * [[InteractionObject]]. * * @since 4.5.14 */ _this.mouseOptions = { "sensitivity": 1 }; // Set class name _this.className = "Interaction"; // Create InteractionObject for <body> _this.body = _this.getInteraction(document.body); _this._disposers.push(_this.body); // Detect browser capabilities and determine what event listeners to use if (window.hasOwnProperty("PointerEvent")) { // IE10+/Edge without touch controls enabled _this._pointerEvents.pointerdown = "pointerdown"; _this._pointerEvents.pointerup = "pointerup"; _this._pointerEvents.pointermove = "pointermove"; _this._pointerEvents.pointercancel = "pointercancel"; _this._pointerEvents.pointerover = "pointerover"; _this._pointerEvents.pointerout = "pointerout"; //this._usePointerEventsOnly = true; } else if (window.hasOwnProperty("MSPointerEvent")) { // IE9 _this._pointerEvents.pointerdown = "MSPointerDown"; _this._pointerEvents.pointerup = "MSPointerUp"; _this._pointerEvents.pointermove = "MSPointerMove"; _this._pointerEvents.pointercancel = "MSPointerUp"; _this._pointerEvents.pointerover = "MSPointerOver"; _this._pointerEvents.pointerout = "MSPointerOut"; //this._usePointerEventsOnly = true; } else if ((typeof matchMedia !== "undefined") && matchMedia('(pointer:fine)').matches) { // This is only for Safari as it does not support PointerEvent // Do nothing and let it use regular `mouse*` events // Hi Apple ;) // Additionally disable hover events for iOS devices if ('ontouchstart' in window) { _this._addHoverEvents = false; _this._useTouchEventsOnly = true; } } else if (window.navigator.userAgent.match(/MSIE /)) { // Oh looky, an MSIE that does not support PointerEvent. Hi granpa IE9! _this._usePointerEventsOnly = true; } else if (_this.fullFF()) { // Old FF, let's use regular events. // (Newer FFs would be detected by the PointerEvent availability check) _this._usePointerEventsOnly = true; } else { // Uses defaults for normal browsers // We also assume that this must be a touch device that does not have // any pointer events _this._useTouchEventsOnly = true; } // Detect if device has a mouse // This is turning out to be not reliable // @todo remove /*if (!window.navigator.msPointerEnabled && (typeof matchMedia !== "undefined") && !matchMedia('(pointer:fine)').matches && !this.fullFF()) { this._useTouchEventsOnly = true; }*/ // Detect proper mouse wheel events if ("onwheel" in document.createElement("div")) { // Modern browsers _this._pointerEvents.wheel = "wheel"; } else if ($type.hasValue(document.onmousewheel)) { // Webkit and IE support at least "mousewheel" _this._pointerEvents.wheel = "mousewheel"; } // Set up default inertia options _this.inertiaOptions.setKey("move", { "time": 100, "duration": 500, "factor": 1, "easing": $ease.polyOut3 }); _this.inertiaOptions.setKey("resize", { "time": 100, "duration": 500, "factor": 1, "easing": $ease.polyOut3 }); // Set the passive mode support _this._passiveSupported = Interaction.passiveSupported; // Apply theme _this.applyTheme(); return _this; } /** * This is a nasty detection for Firefox. The reason why we have is that * Firefox ESR version does not support matchMedia correctly. * * On iOS, Firefox uses different userAgent, so we don't have to detect iOS. * * @return Full Firefox? */ Interaction.prototype.fullFF = function () { return (window.navigator.userAgent.match(/Firefox/)) && !(window.navigator.userAgent.match(/Android/)); }; Interaction.prototype.debug = function () { }; /** * ========================================================================== * Processing * ========================================================================== * @hidden */ /** * Sets up global events. * * We need this so that we can track drag movement beyond chart's container. * * @ignore Exclude from docs */ Interaction.prototype.addGlobalEvents = function () { var _this = this; if (!this._globalEventsAdded) { if (!this._useTouchEventsOnly) { this._disposers.push(addEventListener(document, this._pointerEvents.pointerdown, function (ev) { _this.handleGlobalPointerDown(ev); })); this._disposers.push(addEventListener(document, this._pointerEvents.pointermove, function (ev) { _this.handleGlobalPointerMove(ev); })); this._disposers.push(addEventListener(document, this._pointerEvents.pointerup, function (ev) { _this.handleGlobalPointerUp(ev); })); this._disposers.push(addEventListener(document, this._pointerEvents.pointercancel, function (ev) { _this.handleGlobalPointerUp(ev, true); })); this._disposers.push(addEventListener(document, "mouseenter", function (ev) { if (!$type.hasValue(ev.relatedTarget) && (ev.buttons == 0 || ev.which == 0)) { _this.handleDocumentLeave(ev); } })); } // No need to duplicate events for hubrid systems that support both // pointer events and touch events. Touch events are need only for // some touch-only systems, like Mobile Safari. if (!this._usePointerEventsOnly) { this._disposers.push(addEventListener(document, "touchstart", function (ev) { _this.handleGlobalTouchStart(ev); })); this._disposers.push(addEventListener(document, "touchmove", function (ev) { _this.handleGlobalTouchMove(ev); })); this._disposers.push(addEventListener(document, "touchend", function (ev) { _this.handleGlobalTouchEnd(ev); })); } this._disposers.push(addEventListener(document, "keydown", function (ev) { _this.handleGlobalKeyDown(ev); })); this._disposers.push(addEventListener(document, "keyup", function (ev) { _this.handleGlobalKeyUp(ev); })); this._globalEventsAdded = true; } }; /** * Sets if [[InteractionObject]] is clickable. * * @ignore Exclude from docs * @param io [[InteractionObject]] instance */ Interaction.prototype.processClickable = function (io) { // Add or remove touch events this.processTouchable(io); }; /** * Sets if [[InteractionObject]] will display context menu when right-clicked. * * @ignore Exclude from docs * @param io [[InteractionObject]] instance */ Interaction.prototype.processContextMenu = function (io) { if (io.contextMenuDisabled) { if (!io.eventDisposers.hasKey("contextMenuDisabled")) { io.eventDisposers.setKey("contextMenuDisabled", addEventListener(io.element, "contextmenu", function (e) { e.preventDefault(); })); } } else { if (io.eventDisposers.hasKey("contextMenuDisabled")) { io.eventDisposers.getKey("contextMenuDisabled").dispose(); } } }; /** * Sets if [[InteractionObject]] is hoverable. * * @ignore Exclude from docs * @param io [[InteractionObject]] instance */ Interaction.prototype.processHoverable = function (io) { var _this = this; if (io.hoverable || io.trackable) { // Add global events this.addGlobalEvents(); // Add hover styles this.applyCursorOverStyle(io); // Add local events if (!io.eventDisposers.hasKey("hoverable") && this._addHoverEvents) { io.eventDisposers.setKey("hoverable", new MultiDisposer([ addEventListener(io.element, this._pointerEvents.pointerout, function (e) { return _this.handlePointerOut(io, e); }), addEventListener(io.element, this._pointerEvents.pointerover, function (e) { return _this.handlePointerOver(io, e); }) ])); } if (io.trackable) { //sprite.addEventListener("touchmove", this.handleTouchMove, false, this); } } else { var disposer = io.eventDisposers.getKey("hoverable"); if (disposer != null) { disposer.dispose(); io.eventDisposers.removeKey("hoverable"); } } // Add or remove touch events this.processTouchable(io); }; /** * Sets up [[InteractionObject]] as movable. Movable can be any * transformation, e.g. drag, swipe, resize, track. * * @ignore Exclude from docs * @param io Element */ Interaction.prototype.processMovable = function (io) { // Add unified events if (io.draggable || io.swipeable || io.trackable || io.resizable) { // Prep the element if (!this.isGlobalElement(io) && !io.isTouchProtected) { this.prepElement(io); } // Add hover styles this.applyCursorOverStyle(io); } // Add or remove touch events this.processTouchable(io); }; /** * Checks if [[InteractionObject]] is trackable and sets relative events. * * @ignore Exclude from docs * @param io Element */ Interaction.prototype.processTrackable = function (io) { this.processHoverable(io); this.processMovable(io); if (io.trackable) { this.trackedObjects.moveValue(io); } else { this.trackedObjects.removeValue(io); } }; /** * Checks if [[InteractionObject]] is draggable. * * @ignore Exclude from docs * @param io Element */ Interaction.prototype.processDraggable = function (io) { this.processMovable(io); }; /** * Checks if [[InteractionObject]] is swipeable and sets relative events. * * A swipe event is triggered when a horizontal drag of 75px or more (and * less than 30px vertically) occurs within 700 milliseconds. This can be * overridden in sprites [[swipeOptions]]. * * @ignore Exclude from docs * @param io Element */ Interaction.prototype.processSwipeable = function (io) { this.processMovable(io); }; /** * Checks if [[InteractionObject]] is resizable and attaches required events * to it. * * @ignore Exclude from docs * @param io Element */ Interaction.prototype.processResizable = function (io) { this.processMovable(io); }; /** * Checks if [[InteractionObject]] is supposed to capture mouse wheel events * and prepares it to catch those events. * * @ignore Exclude from docs * @param io Element */ Interaction.prototype.processWheelable = function (io) { var _this = this; if (io.wheelable) { //io.hoverable = true; if (!io.eventDisposers.hasKey("wheelable")) { io.eventDisposers.setKey("wheelable", new MultiDisposer([ addEventListener(io.element, this._pointerEvents.wheel, function (e) { return _this.handleMouseWheel(io, e); }, this._passiveSupported ? { passive: false } : false), io.events.on("out", function (e) { if (io.wheelable) { _this.unlockWheel(); } }), io.events.on("over", function (e) { if (io.wheelable) { _this.lockWheel(); } }) ])); } } else { var disposer = io.eventDisposers.getKey("wheelable"); if (disposer != null) { disposer.dispose(); io.eventDisposers.removeKey("wheelable"); } } }; /** * Checks if [[InteractionObject]] is focusable. A focusable element is an * element that will be highlighted when users presses TAB key. If the * element is focusable, this function will attach relative focus/blur * events to it. * * @ignore Exclude from docs * @param io Element */ Interaction.prototype.processFocusable = function (io) { var _this = this; if (io.focusable === true && (io.tabindex > -1) && !this._useTouchEventsOnly) { if (!io.eventDisposers.hasKey("focusable")) { io.eventDisposers.setKey("focusable", new MultiDisposer([ addEventListener(io.element, "focus", function (e) { return _this.handleFocus(io, e); }), addEventListener(io.element, "blur", function (e) { return _this.handleBlur(io, e); }), addEventListener(io.element, this._pointerEvents.pointerdown, function (e) { return _this.handleFocusBlur(io, e); }), addEventListener(io.element, "touchstart", function (e) { return _this.handleFocusBlur(io, e); }, this._passiveSupported ? { passive: false } : false) ])); } } else { var disposer = io.eventDisposers.getKey("focusable"); if (disposer != null) { disposer.dispose(); io.eventDisposers.removeKey("focusable"); } } }; /** * Checks if [[InteractionObject]] is "touchable". It means any interaction * whatsoever: mouse click, touch screen tap, swipe, drag, resize, etc. * * @ignore Exclude from docs * @param io Element */ Interaction.prototype.processTouchable = function (io) { var _this = this; // Add unified events if (io.clickable || io.hoverable || io.trackable || io.draggable || io.swipeable || io.resizable) { // Add global events this.addGlobalEvents(); // Add local events if (!io.eventDisposers.hasKey("touchable")) { if (!this._useTouchEventsOnly && !this._usePointerEventsOnly) { io.eventDisposers.setKey("touchable", new MultiDisposer([ addEventListener(io.element, this._pointerEvents.pointerdown, function (e) { return _this.handlePointerDown(io, e); }), addEventListener(io.element, "touchstart", function (e) { return _this.handleTouchDown(io, e); }, this._passiveSupported ? { passive: false } : false) ])); } else if (!this._useTouchEventsOnly) { io.eventDisposers.setKey("touchable", addEventListener(io.element, this._pointerEvents.pointerdown, function (e) { return _this.handlePointerDown(io, e); })); } else if (!this._usePointerEventsOnly) { io.eventDisposers.setKey("touchable", addEventListener(io.element, "touchstart", function (e) { return _this.handleTouchDown(io, e); }, this._passiveSupported ? { passive: false } : false)); } } } else { var disposer = io.eventDisposers.getKey("touchable"); if (disposer != null) { disposer.dispose(); io.eventDisposers.removeKey("touchable"); } } }; /** * ========================================================================== * Non-pointer events * ========================================================================== * @hidden */ /** * Dispatches "focus" event when element gains focus. * * @ignore Exclude from docs * @param io Element * @param ev Original event */ Interaction.prototype.handleFocus = function (io, ev) { if (!io.focusable) { ev.preventDefault(); return; } io.isFocused = true; if (io.events.isEnabled("focus") && !system.isPaused) { var imev = { type: "focus", target: io, event: ev }; io.events.dispatchImmediately("focus", imev); } }; /** * Used by regular click events to prevent focus if "noFocus" is set. * * This should not be called by "focus" handlers. * * @param io Element * @param ev Original event */ Interaction.prototype.handleFocusBlur = function (io, ev) { if (io.focusable !== false && this.getHitOption(io, "noFocus")) { io.events.once("focus", function () { io.events.disableType("blur"); $dom.blur(); if (io.sprite) { io.sprite.handleBlur(); } io.events.enableType("blur"); }); } }; /** * Dispatches "blur" event when element loses focus. * * @ignore Exclude from docs * @param io Element * @param ev Original event */ Interaction.prototype.handleBlur = function (io, ev) { if (!io.focusable) { ev.preventDefault(); return; } io.isFocused = false; if (io.events.isEnabled("blur") && !system.isPaused) { var imev = { type: "blur", target: io, event: ev }; io.events.dispatchImmediately("blur", imev); } }; /** * ========================================================================== * Global keyboard-related even handlers * ========================================================================== * @hidden */ /** * Checks if there is an item that has currently focus and that they key is * one of the directional keys. If both of the conditions are true, it * creates an object to simulate movement of dragable element with keyboard. * * @ignore Exclude from docs * @param ev An original keyboard event */ Interaction.prototype.handleGlobalKeyDown = function (ev) { if (this.focusedObject) { if (keyboard.isKey(ev, "esc")) { // ESC removes focus $dom.blur(); } else if (this.focusedObject.draggable && keyboard.isKey(ev, ["up", "down", "left", "right"])) { // Prevent scrolling of the document ev.preventDefault(); // Get focused object var io = this.focusedObject; // Get particular key var disposerKey = "interactionKeyboardObject"; // If such disposer already exists we know the event is going on so we // just move on if (io.eventDisposers.hasKey(disposerKey)) { return; } // Create a keyboard mover var ko = new InteractionKeyboardObject(io, ev); io.eventDisposers.setKey(disposerKey, ko); switch (keyboard.getEventKey(ev)) { case "up": ko.directionY = -1; break; case "down": ko.directionY = 1; break; case "left": ko.directionX = -1; break; case "right": ko.directionX = 1; break; } } } }; /** * Dispatches related events when the keyboard key is realeasd. * * @ignore Exclude from docs * @param ev An original keyboard event */ Interaction.prototype.handleGlobalKeyUp = function (ev) { var disposerKey = "interactionKeyboardObject"; if (this.focusedObject) { var disposer = this.focusedObject.eventDisposers.getKey(disposerKey); if (disposer != null) { // Prevent scrolling of the document ev.preventDefault(); // Dispose stuff disposer.dispose(); this.focusedObject.eventDisposers.removeKey(disposerKey); } // Does focused object have "hit" event? if (keyboard.isKey(ev, "enter") && this.focusedObject.sprite && this.focusedObject.sprite.events.isEnabled("hit") && !this.focusedObject.sprite.events.isEnabled("toggled")) { this.focusedObject.dispatchImmediately("hit"); } } }; /** * ========================================================================== * Global pointer-related even handlers * ========================================================================== * @hidden */ /** * Handler for a global "pointermove" event. * * @ignore Exclude from docs * @param ev Event object */ Interaction.prototype.handleGlobalPointerMove = function (ev) { // Get pointer var pointer = this.getPointer(ev); // Update current point position pointer.point = this.getPointerPoint(ev); // Prepare and fire global event if (this.events.isEnabled("track") && !system.isPaused) { var imev = { type: "track", target: this, event: ev, pointer: pointer, touch: pointer.touch }; this.events.dispatchImmediately("track", imev); } // Track this.addBreadCrumb(pointer, pointer.point); // Process further this.handleGlobalMove(pointer, ev); }; /** * Handler for a global "pointerdown" event. * * @ignore Exclude from docs * @param ev Event object */ Interaction.prototype.handleGlobalPointerDown = function (ev) { // Remove delayed hovers this.processDelayed(); // Get pointer var pointer = this.getPointer(ev); // Prepare and fire global event if (this.events.isEnabled("down") && !system.isPaused) { var imev = { type: "down", target: this, event: ev, pointer: pointer, touch: pointer.touch }; this.events.dispatchImmediately("down", imev); } }; /** * Prevents touch action from firing. * * @ignore Exclude from docs * @param ev Event */ Interaction.prototype.preventTouchAction = function (ev) { if (!ev.defaultPrevented) { ev.preventDefault(); } }; /** * Handler for a global "pointerup" event. * * @ignore Exclude from docs * @param ev Event object */ Interaction.prototype.handleGlobalPointerUp = function (ev, cancelled) { if (cancelled === void 0) { cancelled = false; } // Get pointer var pointer = this.getPointer(ev); // Prepare and fire global event if (this.events.isEnabled("up") && !system.isPaused) { var imev = { type: "up", target: this, event: ev, pointer: pointer, touch: pointer.touch }; this.events.dispatchImmediately("up", imev); } // Process further this.handleGlobalUp(pointer, ev, cancelled); }; /** * ========================================================================== * Global touch-related even handlers * ========================================================================== */ /** * Handler for a global "touchmove" event. * * @ignore Exclude from docs * @param ev Event object */ Interaction.prototype.handleGlobalTouchMove = function (ev) { // Process each changed touch point for (var i = 0; i < ev.changedTouches.length; i++) { // Get pointer var pointer = this.getPointer(ev.changedTouches[i]); // Update current point position pointer.point = this.getPointerPoint(ev.changedTouches[i]); // Prepare and fire global event if (this.events.isEnabled("track") && !system.isPaused) { var imev = { type: "track", target: this, event: ev, pointer: pointer, touch: pointer.touch }; this.events.dispatchImmediately("track", imev); } // Track this.addBreadCrumb(pointer, pointer.point); // Process further this.handleGlobalMove(pointer, ev); } }; /** * Handler for a global "touchstart" event. * * @ignore Exclude from docs * @param ev Event object */ Interaction.prototype.handleGlobalTouchStart = function (ev) { // Remove delayed hovers this.processDelayed(); // Process each changed touch point for (var i = 0; i < ev.changedTouches.length; i++) { // Get pointer var pointer = this.getPointer(ev.changedTouches[i]); // Prepare and fire global event if (!this._usePointerEventsOnly && this.events.isEnabled("down") && !system.isPaused) { var imev = { type: "down", target: this, event: ev, pointer: pointer, touch: pointer.touch }; this.events.dispatchImmediately("down", imev); } } }; /** * Handler for a global "touchend" event. * * @ignore Exclude from docs * @param ev Event object */ Interaction.prototype.handleGlobalTouchEnd = function (ev) { // Process each changed touch point for (var i = 0; i < ev.changedTouches.length; i++) { // Get pointer var pointer = this.getPointer(ev.changedTouches[i]); // Prepare and fire global event if (this.events.isEnabled("up") && !system.isPaused) { var imev = { type: "up", target: this, event: ev, pointer: pointer, touch: pointer.touch }; this.events.dispatchImmediately("up", imev); } // Handle element-related events this.handleGlobalUp(pointer, ev); } }; /** * ========================================================================== * Element-specific pointer-related even handlers * ========================================================================== * @hidden */ /** * Handles event when pointer is over [[InteractionObject]] and button is * pressed. * * @ignore Exclude from docs * @param io Element * @param ev Original event */ Interaction.prototype.handlePointerDown = function (io, ev) { // Stop further propagation so we don't get multiple triggers on hybrid // devices (both mouse and touch capabilities) //ev.preventDefault(); //ev.stopPropagation(); //if (ev.defaultPrevented) { //} // Get pointer var pointer = this.getPointer(ev); // Ignore if it's anything but mouse's primary button if (!pointer.touch && ev.which != 1 && ev.which != 3) { return; } // Set mouse button pointer.button = ev.which; // Reset pointer this.resetPointer(pointer, ev); // Process down this.handleDown(io, pointer, ev); }; /** * Handles event when [[InteractionObject]] is hovered by a mouse pointer. * * @ignore Exclude from docs * @param io Element * @param ev Original event */ Interaction.prototype.handlePointerOver = function (io, ev) { // Get pointer var pointer = this.getPointer(ev); // Process down this.handleOver(io, pointer, ev); }; /** * Handles event when [[InteractionObject]] loses hover from a mouse pointer. * * @ignore Exclude from docs * @param io Element * @param ev Original event */ Interaction.prototype.handlePointerOut = function (io, ev) { // Get pointer var pointer = this.getPointer(ev); // Process down this.handleOut(io, pointer, ev); }; /** * Handles event when mouse wheel is crolled over the [[InteractionObject]]. * * @ignore Exclude from docs * @param io Element * @param ev Original event * @todo Investigate more-cross browser stuff https://developer.mozilla.org/en-US/docs/Web/Events/wheel */ Interaction.prototype.handleMouseWheel = function (io, ev) { // Get pointer var pointer = this.getPointer(ev); // Update current point position pointer.point = this.getPointerPoint(ev); // Init delta values var deltaX = 0, deltaY = 0; // Set up modifier // This is needed because FireFox reports wheel deltas in "lines" instead // of pixels so we have to approximate pixel value var mod = 1; if (ev.deltaMode == 1) { mod = 50; } // Adjust configurable sensitivity mod *= this.getMouseOption(io, "sensitivity"); // Calculate deltas if (ev instanceof WheelEvent) { deltaX = Math.round((-1 * ev.wheelDeltaX) || ev.deltaX) * mod; deltaY = Math.round((-1 * ev.wheelDeltaY) || ev.deltaY) * mod; } else { throw new Error("Invalid event type"); } // Handle the event this.handleWheel(io, pointer, deltaX, deltaY, ev); }; /** * ========================================================================== * Element-specific touch-related even handlers * ========================================================================== * @hidden */ /** * Handles an event when an [[InteractionObject]] is touched on a touch * device. * * @ignore Exclude from docs * @param io Element * @param ev Original event */ Interaction.prototype.handleTouchDown = function (io, ev) { // Stop further propagation so we don't get multiple triggers on hybrid // devices (both mouse and touch capabilities) //this.maybePreventDefault(io, ev); //return; // Process each changed touch point for (var i = 0; i < ev.changedTouches.length; i++) { // Get pointer var pointer = this.getPointer(ev.changedTouches[i]); this.maybePreventDefault(io, ev, pointer); // Reset pointer this.resetPointer(pointer, ev.changedTouches[i]); // Process down this.handleDown(io, pointer, ev); } }; /** * ========================================================================== * Universal handlers * ========================================================================== * @hidden */ /** * Handles click/tap. Checks for doublehit. * * @ignore Exclude from docs * @param io Interaction object * @param pointer Pointer * @param ev Original event */ Interaction.prototype.handleHit = function (io, pointer, ev) { // Check if this is a double-hit var now = $time.getTime(); if (io.lastHit && (io.lastHit >= (now - this.getHitOption(io, "doubleHitTime")))) { // Yup - it's a double-hit // Cancel the hit //clearTimeout(io.lastHitPointer.hitTimeout); // If it happened too fast it probably means that hybrid device just // generated two events for the same tap if ((now - io.lastHit) < 100) { // Ignore return; } // Clear last hit io.lastHit = undefined; io.lastHitPointer = undefined; // Dispatch event if (io.events.isEnabled("doublehit") && !system.isPaused) { var imev = { type: "doublehit", target: io, point: pointer.point, event: ev, touch: pointer.touch }; io.events.dispatchImmediately("doublehit", imev); } } else { // Log last hit io.lastHit = now; io.lastHitPointer = pointer; if (pointer.button === 3) { // Execute HIT now if (io.events.isEnabled("rightclick") && !system.isPaused) { var imev = { type: "rightclick", target: io, event: ev }; io.events.dispatchImmediately("rightclick", imev); } } else { if (io.events.isEnabled("hit") && !system.isPaused) { var imev = { type: "hit", target: io, event: ev, point: pointer.point, touch: pointer.touch }; io.events.dispatchImmediately("hit", imev); } } } }; /** * Handles pointer hovering over [[InteractionObject]]. * * @ignore Exclude from docs * @param io Interaction object * @param pointer Pointer * @param ev Original event * @param soft Invoked by helper function */ Interaction.prototype.handleOver = function (io, pointer, ev, soft) { if (soft === void 0) { soft = false; } if (!io.hoverable) { return; } var hoversPaused = false; if (this.shouldCancelHovers(pointer) && this.areTransformed() && this.moved(pointer, this.getHitOption(io, "hitTolerance"))) { hoversPaused = true; this.cancelAllHovers(ev); } // Remove any delayed outs this.processDelayed(); // Add pointer io.overPointers.moveValue(pointer); // Check if object is not yet hovered if (!io.isRealHover) { // Set element as hovered if (!hoversPaused) { io.isHover = true; io.isRealHover = true; this.overObjects.moveValue(io); } // Generate body track event. This is needed so that if element loads // under unmoved mouse cursor, we still need all the actions that are // required to happen to kick in. this.handleTrack(this.body, pointer, ev, true); // Event if (io.events.isEnabled("over") && !system.isPaused && !hoversPaused) { var imev = { type: "over", target: io, event: ev, pointer: pointer, touch: pointer.touch }; io.events.dispatchImmediately("over", imev); } } }; /** * Handles when [[InteractionObject]] is no longer hovered. * * If `soft = true`, this means that method is being invoked by some other * code, not hard "out" function, like `handleUp` which implies we need to * run additional checks before unhovering the object. * * @ignore Exclude from docs * @param io Interaction object * @param pointer Pointer * @param ev Original event * @param soft Invoked by helper function * @param force Force imediate out */ Interaction.prototype.handleOut = function (io, pointer, ev, soft, force) { var _this = this; if (soft === void 0) { soft = false; } if (force === void 0) { force = false; } if (!io.hoverable) { return; } // Remove pointer io.overPointers.removeValue(pointer); // Check if element is still hovered if (io.isHover && (!io.hasDelayedOut || force)) { // Should we run additional checks? if (soft && io.overPointers.length) { // There are still pointers hovering - don't do anything else and // wait until either no over pointers are there or we get a hard out // event. return; } // Should we delay "out" if this is happening on a touch device? if (pointer.touch && !force && !this.old(pointer)) { // This is a touch pointer, and it hasn't moved, let's pretend // the object is still hovered, and act as per "behavior" setting var behavior = this.getHoverOption(io, "touchOutBehavior"); if (behavior == "leave") { // Set to "leave", so we do not execute any "out" event. // It will be handled by any other interaction that happens // afterwards. this._delayedEvents.out.push({ type: "out", io: io, pointer: pointer, event: ev, keepUntil: $time.getTime() + 500 }); io.hasDelayedOut = true; return; } else if (behavior == "delay" && this.getHoverOption(io, "touchOutDelay")) { this._delayedEvents.out.push({ type: "out", io: io, pointer: pointer, event: ev, keepUntil: $time.getTime() + 500, timeout: this.setTimeout(function () { _this.handleOut(io, pointer, ev, true); }, this.getHoverOption(io, "touchOutDelay")) }); return; } else { // Nothing for "remove" - that's how it works "out-of-the-box" } } // Set element as not hovered io.isHover = false; this.overObjects.removeValue(io); // Invoke event if (io.events.isEnabled("out") && !system.isPaused) { var imev = { type: "out", target: io, event: ev, pointer: pointer, touch: pointer.touch }; io.events.dispatchImmediately("out", imev); } // Reset object from lefover delayed outs, pointers io.overPointers.clear(); io.hasDelayedOut = false; // @todo (clean delayed) } }; /** * Processes dalyed events, such as "out" event that was initiated for * elements by touch. */ Interaction.prototype.processDelayed = function () { var delayedEvent; while (true) { delayedEvent = this._delayedEvents.out.pop(); if (!delayedEvent) { break; } if (delayedEvent.timeout) { delayedEvent.timeout.dispose(); } this.handleOut(delayedEvent.io, delayedEvent.pointer, delayedEvent.event, false, true); } }; /** * Performs tasks on pointer down. * * @ignore Exclude from docs * @param io Element * @param pointer Pointer * @param ev Original event */ Interaction.prototype.handleDown = function (io, pointer, ev) { // Need to prevent default event from happening on transformable objects this.maybePreventDefault(io, ev, pointer); // Stop inertia animations if they're currently being played out if (io.inert) { this.stopInertia(io); } // Trigger hover because some touch devices won't trigger over events // on their own this.handleOver(io, pointer, ev, true); // Add pointer to list io.downPointers.moveValue(pointer); // Apply styles if necessary this.applyCursorDownStyle(io, pointer); // Check if object is already down if (!io.isDown) { // Lose focus if needed if (io.focusable !== false && this.getHitOption(io, "noFocus") && this.focusedObject) { $dom.blur(); } // Set object as hovered io.isDown = true; this.downObjects.moveValue(io); // Prep object for dragging and/or resizing if (io.draggable) { this.processDragStart(io, pointer, ev); } if (io.resizable) { this.processResizeStart(io, pointer, ev); } } // Dispatch "down" event if (io.events.isEnabled("down") && !system.isPaused) { var imev = { type: "down", target: io, event: ev, pointer: pointer, touch: pointer.touch }; io.events.dispatchImmediately("down", imev); } }; /** * Performs tasks on pointer up. * * @ignore Exclude from docs * @param pointer Pointer * @param ev Original event */ Interaction.prototype.handleGlobalUp = function (pointer, ev, cancelled) { var _this = this; if (cancelled === void 0) { cancelled = false; } var sorted = this.downObjects.values.slice(); sorted.sort(function (x, y) { if (x && y) { var pos = x.element.compareDocumentPosition(y.element); if (pos & Node.DOCUMENT_POSITION_CONTAINED_BY) { return 1; } else if (pos & Node.DOCUMENT_POSITION_CONTAINS) { return -1; } else { return 0; } } else { return 0; } }); // Process all down objects $array.each(sorted, function (io) { // Check if this particular pointer is pressing down // on object if (io && io.downPointers.contains(pointer)) { _this.handleUp(io, pointer, ev, cancelled); } }); }; /** * Simulates all pointers being up once mouse leaves document area. * * @ignore Exclude from docs * @param ev Original event */ Interaction.prototype.handleDocumentLeave = function (ev) { var _this = this; // Process all down objects $iter.each(this.downObjects.backwards().iterator(), function (io) { io.downPointers.each(function (pointer) { _this.handleUp(io, pointer, ev); }); }); }; /** * Handles when [[InteractionObject]] is no longer hovered. * * @ignore Exclude from docs * @param io Interaction object * @param pointer Pointer * @param ev Original event */ Interaction.prototype.handleUp = function (io, pointer, ev, cancelled) { if (cancelled === void 0) { cancelled = false; } // Restore cursor style this.restoreCursorDownStyle(io, pointer); // Remove pointer from the list io.downPointers.removeValue(pointer); // Trigger out because some touch devices won't trigger out events // on their own if (pointer.touch || this._useTouchEventsOnly) { this.handleOut(io, pointer, ev, true); } // Check if object still down if (io.isDown) { // Check if there are no other pointers hovering this element if (io.downPointers.length == 0) { // Set element as no longer down io.isDown = false; this.downObjects.removeValue(io); } // Dispatch "up" event if (io.events.isEnabled("up") && !system.isPaused) { var imev = { type: "up", target: io, event: ev, pointer: pointer, touch: pointer.touch }; io.events.dispatchImmediately("up", imev); } // Check if this was not a cancelled event. // If event was canelled (which might happen if gesture resulted in // navigation or page scroll) there's no point in triggering hit and // other actions. if (!cancelled) { // Handle swiping-related stuff if (io.swipeable && this.swiped(io, pointer)) { // Swiped - nothing else should happen this.handleSwipe(io, pointer, ev); } else { // Check if it maybe a click if (io.clickable && !this.moved(pointer, this.getHitOption(io, "hitTolerance"))) { this.handleHit(io, pointer, ev); } // Handle inertia if (io.inert && this.moved(pointer, this.getHitOption(io, "hitTolerance"))) { this.handleInertia(io, pointer); } else if (io.draggable) { this.processDragStop(io, pointer, ev); } if (io.resizable) { this.processResizeStop(io, pointer, ev); } } } } }; /** * Checks if event needs to be prevented on draggable and such items, so that * touch gestures like navigation and scroll do not kick in. * * @param io Object * @param ev Event */ Interaction.prototype.maybePreventDefault = function (io, ev, pointer) { if ($type.hasValue(ev) && (io.draggable || io.swipeable || io.trackable || io.resizable) && !this.isGlobalElement(io) && ev.cancelable !== false && (!io.isTouchProtected || !pointer || !pointer.touch)) { ev.preventDefault(); } }; /** * Cancels all hovers on all currently hovered objects. * * @param pointer Pointer * @param ev Event */ Interaction.prototype.cancelAllHovers = function (ev) { var _this = this; //this.overObjects.each((io) => { $iter.each(this.overObjects.backwards().iterator(), function (io) { if (io) { var pointer = io.overPointers.getIndex(0); _this.handleOut(io, pointer, ev, true, true); } }); }; /** * Checks if hovers should be cancelled on transform as per global options. * @param pointer Pointer * @return Cancel? */ Interaction.prototype.shouldCancelHovers = function (pointer) { return options.disableHoverOnTransform == "always" || (options.disableHoverOnTransform == "touch" && pointer.touch); }; /** * Handles pointer move. * * @ignore Exclude from docs * @param pointer Pointer * @param ev Original event */ Interaction.prototype.handleGlobalMove = function (pointer, ev) { var _this = this; // Process hovered elements // We check if the element became unhovered without reporting the mouseout // event. (it happens in some cases) if (!pointer.touch) { var target_1 = $dom.eventTarget(pointer.lastEvent); $iter.each(this.overObjects.backwards().iterator(), function (io) { // Is this pointer relevant to element? if (io && io.overPointers.contains(pointer) && io.hoverable) { // Check if the element is still hovered var reset = false; if (io.element && pointer.lastEvent) { if (!$dom.contains(io.element, target_1)) { reset = true; } } else { reset = true; } if (reset) { _this.handleOut(io, pointer, ev, true); } } }); } // Process down elements $iter.each(this.transformedObjects.backwards().iterator(), function (io) { // Is this pointer relevant to element? if (io.downPointers.contains(pointer) && // Swipe still happening? !(io.swipeable && _this.swiping(io, pointer)) && (io.draggable || io.resizable)) { _this.handleTransform(io, ev); } }); // Process tracked elements $iter.each(this.trackedObjects.backwards().iterator(), function (io) { // Is this pointer relevant to element? if (!io.overPointers.contains(pointer)) { _this.handleTrack(io, pointer, ev); } }); }; /** * Handles reporting of pointer movement. * * @ignore Exclude from docs * @param io Element * @param pointer Pointer * @param ev Original event * @param skipCheck Sould we skip check if cursor actually moved */ Interaction.prototype.handleTrack = function (io, pointer, ev, skipCheck) { if (skipCheck === void 0) { skipCheck = false; } // Do nothing if the cursor did not actually move if (!skipCheck && !this.moved(pointer, 0)) { return; } // Initiate TRACK event if (io.events.isEnabled("track") && !system.isPaused) { var imev = { type: "track", target: io, event: ev, point: pointer.point, pointer: pointer, touch: pointer.touch }; io.events.dispatchImmediately("track", imev); } }; /** * Handles swipe action. * * @ignore Exclude from docs * @param io Element * @param pointer Pointer * @param ev Original event */ Interaction.prototype.handleSwipe = function (io, pointer, ev) { // We pass in InteractionEvent with shift in mouse coordinates // between when the drag started and ended if (io.events.isEnabled("swipe") && !system.isPaused) { var imev = { type: "swipe", target: io, event: ev, touch: pointer.touch }; io.events.dispatchImmediately("swipe", imev); } if (pointer.startPoint.x < pointer.point.x) { if (io.events.isEnabled("swiperight") && !system.isPaused) { var imev = { type: "swiperight", target: io, event: ev, touch: pointer.touch }; io.events.dispatchImmediately("swiperight", imev); } } else { if (io.events.isEnabled("swipeleft") && !system.isPaused) { var imev = { type: "swipeleft", target: io, event: ev, touch: pointer.touch }; io.events.dispatchImmediately("swipeleft", imev); } } }; /** * Handles event triggering for wheel rotation. * * @ignore Exclude from docs * @param io Element * @param pointer Pointer * @param deltaX Horizontal shift * @param deltaY Vertical shift * @param ev Original event */ Interaction.prototype.handleWheel = function (io, pointer, deltaX, deltaY, ev) { var shift = { x: deltaX, y: deltaY }; // Trigger generic WHEEL event if (io.events.isEnabled("wheel") && !system.isPaused) { io.events.dispatchImmediately("wheel", { type: "wheel", target: io, event: ev, point: pointer.point, shift: shift }); } // Trigger direction-specific events // Horizontal if (deltaX < 0) { if (io.events.isEnabled("wheelleft") && !system.isPaused) { io.events.dispatchImmediately("wheelleft", { type: "wheelleft", target: io, event: ev, point: pointer.point, shift: shift }); } } else if (deltaX > 0) { if (io.events.isEnabled("swiperight") && !system.isPaused) { io.events.dispatchImmediately("wheelright", { type: "wheelright", target: io, event: ev, point: pointer.point, shift: shift }); } // Vertical } else if (deltaY < 0) { if (io.events.isEnabled("wheelup") && !system.isPaused) { io.events.dispatchImmediately("wheelup", { type: "wheelup", target: io, event: ev, point: pointer.point, shift: shift }); } } else if (deltaY > 0) { if (io.events.isEnabled("wheeldown") && !system.isPaused) { io.events.dispatchImmediately("wheeldown", { type: "wheeldown", target: io, event: ev, point: pointer.point, shift: shift }); } } }; /** * Initiates inertia checking sub-routines for different movement types: * drag, resize. * * @ignore Exclude from docs * @param sprite * @param pointer */ Interaction.prototype.handleInertia = function (io, pointer) { if (io.draggable && io.downPointers.length === 0) { this.handleMoveInertia(io, pointer); } if (io.resizable && io.downPointers.length > 1) { this.handleResizeInertia(io, pointer); } }; /** * Continues moving the element to simulate the effect of inertia. Happens * when `inert` and `draggable` object is dragged and then released. * * @ignore Exclude from docs * @param io Element * @param pointer Pointer */ Interaction.prototype.handleMoveInertia = function (io, pointer) { var interaction = io; var type = "move"; var point = { "x": pointer.point.x, "y": pointer.point.y }; var startPoint = { "x": pointer.startPoint.x, "y": pointer.startPoint.y }; // Init inertia object var inertia = new Inertia(interaction, type, point, startPoint); // Get inertia data var ref = this.getTrailPoint(pointer, $time.getTime() - this.getInertiaOption(io, "move", "time")); if (typeof ref === "undefined") { this.processDragStop(io, pointer, pointer.lastUpEvent); return; } // Init animation options var factor = this.getInertiaOption(io, "move", "factor"); var animationOptions = [{ "to": pointer.point.x + (pointer.point.x - ref.point.x) * factor, "property": "x" }, { "to": pointer.point.y + (pointer.point.y - ref.point.y) * factor, "property": "y" }]; // Start animation var animation = new Animation(inertia, animationOptions, this.getInertiaOption(io, "move", "duration"), this.getInertiaOption(io, "move", "easing")).start(); this._disposers.push(animation.events.on("animationended", function (ev) { inertia.done(); })); // Add inertia object io.inertias.setKey("move", inertia); }; /** * Continues resizing of a `resizable` element after it is resized and * released. * * **NOTE:** this is is just a placeholder function. No actual fucntionality * is implemented, yet. * * @ignore Exclude from docs * @param io Element * @param pointer Pointer */ Interaction.prototype.handleResizeInertia = function (io, pointer) { // Some day, folks. Some day... }; /** * Recalculates element's position and size based on position of * all its related pointers. * * @ignore Exclude from docs * @param io Element * @param ev Original event */ Interaction.prototype.handleTransform = function (io, ev) { // Get primary pointer and its respective points var pointer1 = io.downPointers.getIndex(0); var point1 = null; var startPoint1 = null; if (pointer1) { point1 = pointer1.point; startPoint1 = pointer1.startPoint; } // Init secondary pointer var pointer2; var point2; var startPoint2; // Use center of the sprite to simulate "second" point of touch point2 = { "x": io.originalPosition.x, "y": io.originalPosition.y }; startPoint2 = point2; // Determine if it's a sinngle pointer or multi var singlePoint = true; for (var i = 1; i < io.downPointers.length; i++) { // Get pointer var nextPointer = io.downPointers.getIndex(i); // Doublecheck if it's not the same pointer by comparing original position if (startPoint1.x != nextPointer.startPoint.x && startPoint1.y != nextPointer.startPoint.y) { // Several pointers down singlePoint = false; // Get second pointer pointer2 = nextPointer; point2 = pointer2.point; startPoint2 = pointer2.startPoint; // Stop looking break; } } // Primary touch point moved? var pointer1Moved = pointer1 && this.moved(pointer1, 0); // Report DRAG_START if necessary if (io.draggable && pointer1 && pointer1.dragStartEvents && pointer1.dragStartEvents.length && pointer1Moved) { if (io.events.isEnabled("dragstart") && !system.isPaused) { io.events.dispatchImmediately("dragstart", pointer1.dragStartEvents.shift()); } //delete pointer1.dragStartEvents; } // Determine what we do in order of superiority if (singlePoint && io.draggable) { // We have only one pointer and the Sprite is draggable // There's nothing else to be done - just move it this.handleTransformMove(io, point1, startPoint1, ev, pointer1Moved, pointer1.touch); if (this.shouldCancelHovers(pointer1) && this.moved(pointer1, this.getHitOption(io, "hitTolerance"))) { this.cancelAllHovers(ev); } } else { // Check if second touch point moved var pointer2Moved = pointer2 && this.moved(pointer2, 0); if ((this.shouldCancelHovers(pointer1) && this.moved(pointer1, this.getHitOption(io, "hitTolerance"))) || (this.shouldCancelHovers(pointer2) && this.moved(pointer2, this.getHitOption(io, "hitTolerance")))) { this.cancelAllHovers(ev); } if (io.draggable && io.resizable) { //this.handleTransformAll(io, point1, startPoint1, point2, startPoint2, ev, pointer1Moved && pointer2Moved); this.handleTransformMove(io, point1, startPoint1, ev, pointer1Moved && pointer2Moved, pointer1.touch); this.handleTransformResize(io, point1, startPoint1, point2, startPoint2, ev, pointer1Moved && pointer2Moved, pointer1.touch); } else { if (io.draggable) { this.handleTransformMove(io, point1, startPoint1, ev, pointer1Moved, pointer1.touch); } if (io.resizable && (!singlePoint || ev.ctrlKey)) { this.handleTransformResize(io, point1, startPoint1, point2, startPoint2, ev, pointer1Moved && pointer2Moved, pointer1.touch); } } } }; /** * Handles movement of the dragged element. * * @ignore Exclude from docs * @param io Element * @param point Current point of the pointer * @param startPoint Starting point of the pointer * @param ev Original event * @param pointerMoved Did pointer move? */ Interaction.prototype.handleTransformMove = function (io, point, startPoint, ev, pointerMoved, touch) { if (pointerMoved) { if (io.events.isEnabled("drag") && !system.isPaused && (!io.isTouchProtected || !touch)) { var imev = { type: "drag", target: io, event: ev, shift: { "x": point.x - startPoint.x, "y": point.y - startPoint.y }, startPoint: startPoint, point: point, touch: touch }; io.events.dispatchImmediately("drag", imev); } } }; /** * Handles resizing of the element. * * @ignore Exclude from docs * @param io Element * @param point1 Current position of reference point #1 * @param startPoint1 Original position of reference point #1 * @param point2 Current position of reference point #2 * @param startPoint2 Original position of reference point #2 * @param ev Original event * @param pointerMoved Did pointer move? */ Interaction.prototype.handleTransformResize = function (io, point1, startPoint1, point2, startPoint2, ev, pointerMoved, touch) { if (io.events.isEnabled("resize") && !system.isPaused && (!io.isTouchProtected || !touch)) { var imev = { type: "resize", target: io, event: ev, scale: $math.getScale(point1, startPoint1, point2, startPoint2), startPoint1: startPoint1, point1: point1, startPoint2: startPoint2, point2: point2, touch: touch }; io.events.dispatchImmediately("resize", imev); } }; /** * Handles all the preparations of the element when it starts to be dragged. * * @ignore Exclude from docs * @param io Element * @param pointer Pointer * @param ev Original event */ Interaction.prototype.processDragStart = function (io, pointer, ev) { // Add to draggedObjects this.transformedObjects.moveValue(io); if (this.shouldCancelHovers(pointer)) { this.cancelAllHovers(ev); } // Report "dragstart" var imev = { type: "dragstart", target: io, event: ev, touch: pointer ? pointer.touch : false }; // Log object that we are starting to drag, so we can check against and // avoid hovers on other objects that might be in the path of movement. if (pointer) { pointer.dragTarget = io; //pointer.startPoint = pointer.point; } /** * If pointer is set we will not fire the event until the pointer has * actually moved. If it's not set we don't have to wait for anything, so we * just fire off the event right away. */ if (pointer && pointer.dragStartEvents) { pointer.dragStartEvents.push(imev); } else { if (!system.isPaused) { io.dispatchImmediately("dragstart", imev); } } }; /** * Finishes up element drag operation. * * @ignore Exclude from docs * @param io Element * @param pointer Pointer * @param ev Original event */ Interaction.prototype.processDragStop = function (io, pointer, ev) { // Pointer set? if (!pointer) { pointer = this.getDragPointer(io); } // Unset drag object if (pointer) { pointer.dragTarget = undefined; } // Removed from transformedObjects this.transformedObjects.removeValue(io); // Unlock document //this.unlockDocument(); // Report dragstop if (!pointer || this.moved(pointer, 0)) { if (io.events.isEnabled("dragstop") && !system.isPaused) { var imev = { type: "dragstop", target: io, touch: pointer ? pointer.touch : false }; io.events.dispatchImmediately("dragstop", imev); } } }; /** * Handles all the preparations of the element when it starts to be resized. * * @ignore Exclude from docs * @param io Element * @param pointer Pointer * @param ev Original event */ Interaction.prototype.processResizeStart = function (io, pointer, ev) { // Add to draggedObjects this.transformedObjects.moveValue(io); }; /** * Finishes up element drag operation. * * @ignore Exclude from docs * @param io Element * @param pointer Pointer * @param ev Original event */ Interaction.prototype.processResizeStop = function (io, pointer, ev) { // Removed from transformedObjects this.transformedObjects.removeValue(io); }; /** * ========================================================================== * Controls for InteractionObjects initiating directly * ========================================================================== * @hidden */ /** * Manually triggers drag start on the element. Could be useful in cases * where tracking or dragging one element can also influence dragging another * element. * * Passing in `pointer` reference is advisable. If not passed in it will try * to determine which pointer to attach to. However, it's better to specify * it explicitly. * * @param io Element * @param pointer Pointer */ Interaction.prototype.dragStart = function (io, pointer) { if (!pointer) { pointer = this.getDragPointer(io); } if (pointer) { this.handleDown(io, pointer, pointer.lastDownEvent); } }; /** * Manually ends drag on the element. * * @param io Element * @param pointer Pointer */ Interaction.prototype.dragStop = function (io, pointer, cancelled) { if (!pointer) { pointer = this.getDragPointer(io); } if (pointer && !cancelled) { this.handleGlobalUp(pointer, pointer.lastUpEvent, cancelled); } }; /** * This method uses a fuzzy logic to find the pointer to be used for dragging. * Beware that this is not a rock-solid solution. If there are a few objects * being dragged at the same time, you may get unexepected results. * * @param io InteractionObject to get pointers from * @return Pointer currently being used for dragging */ Interaction.prototype.getDragPointer = function (io) { if (io) { // InteractionObject is supplied // Use it's first down pointer return io.downPointers.getIndex(0); } else if (this.transformedObjects.length) { // Use first dragged object return this.getDragPointer(this.transformedObjects.getIndex(0)); } else { return undefined; } }; /** * ========================================================================== * Utils * ========================================================================== * @hidden */ /** * Returns pointer id for the given event object. * * @param ev Event * @return Pointer ID */ Interaction.prototype.getPointerId = function (ev) { var id = ""; if ($type.hasValue(ev.identifier)) { id = "" + ev.identifier; } else if ($type.hasValue(ev.pointerId)) { id = "" + ev.pointerId; } else { id = "m"; } return id.replace("-", ""); }; /** * Returns a cursor position of the event. * * @param ev Original event * @return Event point */ Interaction.prototype.getPointerPoint = function (ev) { return { "x": ev.clientX, "y": ev.clientY }; }; /** * Returns [[Pointer]] object that is associated with the Event. * * If no such [[Pointer]] object exists, it is created. * * @param ev Event * @return Pointer */ Interaction.prototype.getPointer = function (ev) { // Get pointer id var id = this.getPointerId(ev); // Get current coordinates var point = this.getPointerPoint(ev); // Look for the pointer in the Dictionary if it maybe already exists var pointer; if (this.pointers.hasKey(id)) { // We already have such pointer pointer = this.pointers.getKey(id); // We need this, because Edge reuses pointer ids across touch and mouse pointer.touch = this.isPointerTouch(ev); // Reset pointer //pointer.point = point; } else { // Init pointer pointer = { "id": id, //"touch": !(ev instanceof MouseEvent) || ((<any>ev).pointerType && (<any>ev).pointerType != "pointer"), //"touch": !(ev instanceof MouseEvent) || ((<any>ev).pointerType && (<any>ev).pointerType != "mouse"), "touch": this.isPointerTouch(ev), "startPoint": point, "startTime": $time.getTime(), "point": point, "track": [], "swipeCanceled": false, "dragStartEvents": [] }; // Add first breadcrumb this.addBreadCrumb(pointer, point); // Add for re-use later this.pointers.setKey(id, pointer); } // Log last event pointer.lastEvent = ev; this.lastPointer = pointer; return pointer; }; /** * Determines if pointer event originated from a touch pointer or mouse. * * @param ev Original event * @return Touch pointer? */ Interaction.prototype.isPointerTouch = function (ev) { if (typeof Touch !== "undefined" && ev instanceof Touch) { return true; } else if (typeof PointerEvent !== "undefined" && ev instanceof PointerEvent && $type.hasValue(ev.pointerType)) { switch (ev.pointerType) { case "touch": case "pen": case 2: return true; case "mouse": case 4: return false; default: return !(ev instanceof MouseEvent); } } else if ($type.hasValue(ev.type)) { if (ev.type.match(/^mouse/)) { return false; } } return true; }; /** * Resets the poiner to original state, i.e. cleans movement information, * starting point, etc. * * @param pointer Pointer */ Interaction.prototype.resetPointer = function (pointer, ev) { // Get current coordinates var point = this.getPointerPoint(ev); ; pointer.startTime = $time.getTime(); pointer.startPoint = { x: point.x, y: point.y }; pointer.point = { x: point.x, y: point.y }; pointer.track = []; pointer.swipeCanceled = false; //clearTimeout(pointer.swipeTimeout); //clearTimeout(pointer.holdTimeout); }; /** * Adds a "breadcrumb" point to the [[Pointer]] to log its movement path. * * @param pointer Pointer * @param point Point coordinates */ Interaction.prototype.addBreadCrumb = function (pointer, point) { pointer.track.push({ "timestamp": $time.getTime(), "point": point }); }; /** * Prepares the document for various touch-related operations. * * @ignore Exclude from docs */ Interaction.prototype.lockDocument = function () { this.prepElement(this.body); }; /** * Restores document functionality. * * @ignore Exclude from docs */ Interaction.prototype.unlockDocument = function () { if (this.transformedObjects.length == 0) { this.restoreAllStyles(this.body); } }; /** * Lock element (disable all touch) * * @ignore Exclude from docs */ Interaction.prototype.lockElement = function (io) { this.prepElement(io); }; /** * Restores element's functionality. * * @ignore Exclude from docs */ Interaction.prototype.unlockElement = function (io) { this.restoreAllStyles(io); }; /** * Locks document's wheel scroll. * * @ignore Exclude from docs */ Interaction.prototype.lockWheel = function () { window.addEventListener(this._pointerEvents.wheel, this.wheelLockEvent, this._passiveSupported ? { passive: false } : false); }; /** * Unlocks document's wheel scroll. * * @ignore Exclude from docs */ Interaction.prototype.unlockWheel = function () { window.removeEventListener(this._pointerEvents.wheel, this.wheelLockEvent); }; /** * Checks if top element at pointer's position belongs to the SVG. * * @ignore Exlude from docs * @param pointer Pointer * @param svg The <svg> element * @param id A unique identifier of the object that is checking for locality * @return Belongs to SVG */ Interaction.prototype.isLocalElement = function (pointer, svg, id) { var cached = this.getCache("local_pointer_" + pointer.id); if ($type.hasValue(cached)) { return cached; } var doc = ($dom.getRoot(svg) || document); if (doc.elementFromPoint) { var target = doc.elementFromPoint(pointer.point.x, pointer.point.y); var local = target && $dom.contains(svg, target); this.setCache("local_pointer_" + pointer.id + "_" + id, local, 100); return local; } return false; }; /** * A function that cancels mouse wheel scroll. * * @ignore Exclude from docs * @param ev Event object * @return Returns `false` to cancel */ Interaction.prototype.wheelLockEvent = function (ev) { ev.preventDefault(); return false; }; /** * Applies a set of styles to an element. Stores the original styles so they * can be restored later. * * @ignore * @param io Element */ Interaction.prototype.prepElement = function (io) { var el = io.element; if (el) { // Define possible props var props = [ "touchAction", "webkitTouchAction", "MozTouchAction", "MSTouchAction", "msTouchAction", "oTouchAction", "userSelect", "webkitUserSelect", "MozUserSelect", "MSUserSelect", "msUserSelect", "oUserSelect", "touchSelect", "webkitTouchSelect", "MozTouchSelect", "MSTouchSelect", "msTouchSelect", "oTouchSelect", "touchCallout", "webkitTouchCallout", "MozTouchCallout", "MSTouchCallout", "msTouchCallout", "oTouchCallout", "contentZooming", "webkitContentZooming", "MozContentZooming", "MSContentZooming", "msContentZooming", "oContentZooming", "userDrag", "webkitUserDrag", "MozUserDrag", "MSUserDrag", "msUserDrag", "oUserDrag" ]; for (var i = 0; i < props.length; i++) { if (props[i] in el.style) { this.setTemporaryStyle(io, props[i], "none"); } } // Remove iOS-specific selection; this.setTemporaryStyle(io, "tapHighlightColor", "rgba(0, 0, 0, 0)"); //this.setTemporaryStyle(io, "webkitOverflowScrolling", "none"); } }; /** * Restores replaced styles * * @ignore * @param io Element */ Interaction.prototype.unprepElement = function (io) { var el = io.element; if (el) { // Define possible props var props = [ "touchAction", "webkitTouchAction", "MozTouchAction", "MSTouchAction", "msTouchAction", "oTouchAction", "userSelect", "webkitUserSelect", "MozUserSelect", "MSUserSelect", "msUserSelect", "oUserSelect", "touchSelect", "webkitTouchSelect", "MozTouchSelect", "MSTouchSelect", "msTouchSelect", "oTouchSelect", "touchCallout", "webkitTouchCallout", "MozTouchCallout", "MSTouchCallout", "msTouchCallout", "oTouchCallout", "contentZooming", "webkitContentZooming", "MozContentZooming", "MSContentZooming", "msContentZooming", "oContentZooming", "userDrag", "webkitUserDrag", "MozUserDrag", "MSUserDrag", "msUserDrag", "oUserDrag" ]; for (var i = 0; i < props.length; i++) { if (props[i] in el.style) { this.restoreStyle(io, props[i]); } } // Remove iOS-specific selection; this.restoreStyle(io, "tapHighlightColor"); //this.restoreStyle(io, "webkitOverflowScrolling"); } }; /** * Returns an option associated with hit events. * * @ignore Exclude from docs * @param io Element * @param option Option key * @return Option value */ Interaction.prototype.getHitOption = function (io, option) { var res = io.hitOptions[option]; if (typeof res === "undefined") { res = this.hitOptions[option]; } return res; }; /** * Returns an option associated with hover events. * * @ignore Exclude from docs * @param io Element * @param option Option key * @return Option value */ Interaction.prototype.getHoverOption = function (io, option) { var res = io.hoverOptions[option]; if (typeof res === "undefined") { res = this.hoverOptions[option]; } return res; }; /** * Returns an option associated with swipe events. * * @ignore Exclude from docs * @param io Element * @param option Option key * @return Option value */ Interaction.prototype.getSwipeOption = function (io, option) { var res = io.swipeOptions[option]; if (typeof res === "undefined") { res = this.swipeOptions[option]; } return res; }; /** * Returns an option for keyboard. * * @ignore Exclude from docs * @param io Element * @param option Option key * @return Option value */ Interaction.prototype.getKeyboardOption = function (io, option) { var res = io.keyboardOptions[option]; if (typeof res === "undefined") { res = this.keyboardOptions[option]; } return res; }; /** * Returns an option for mouse. * * @ignore Exclude from docs * @param io Element * @param option Option key * @return Option value */ Interaction.prototype.getMouseOption = function (io, option) { var res = io.mouseOptions[option]; if (typeof res === "undefined") { res = this.mouseOptions[option]; } return res; }; /** * Returns an option associated with inertia. * * @ignore Exclude from docs * @param io Element * @param type Inertia type * @param option Option key * @return Option value */ Interaction.prototype.getInertiaOption = function (io, type, option) { var options = io.inertiaOptions.getKey(type); var res; if (options && $type.hasValue(options[option])) { res = options[option]; } else { res = this.inertiaOptions.getKey(type)[option]; } return res; }; /** * Stops currently going on inertia. Useful if inertia is currently being * animated and the object is being interacted with. * * @param io Element */ Interaction.prototype.stopInertia = function (io) { var x; var inertias = ["move", "resize"]; for (var i = 0; i < inertias.length; i++) { x = inertias[i]; if (io.inertias.hasKey(x)) { var inertia = io.inertias.getKey(x); if (inertia) { inertia.dispose(); //io.inertiaAnimations.removeKey(x); //this.processDragStop(io); continue; } } } }; /** * Check if swiping is currently being performed on an object. * * @param io Element * @param pointer Pointer to check * @return `true` if swiping */ Interaction.prototype.swiping = function (io, pointer) { var now = $time.getTime(); if (pointer.swipeCanceled || !io.swipeable) { return false; } else if ((Math.abs(pointer.startPoint.y - pointer.point.y) < this.getSwipeOption(io, "verticalThreshold")) && (pointer.startTime > (now - this.getSwipeOption(io, "time")))) { return true; } else { return false; } }; /** * Returns `true` if a successfull swipe action was performed on an element. * * @param io Element * @param pointer Pointer * @return Swiped? */ Interaction.prototype.swiped = function (io, pointer) { var now = $time.getTime(); if (pointer.swipeCanceled) { return false; } else if ((Math.abs(pointer.startPoint.x - pointer.point.x) > this.getSwipeOption(io, "horizontalThreshold")) && (Math.abs(pointer.startPoint.y - pointer.point.y) < this.getSwipeOption(io, "verticalThreshold")) && (pointer.startTime > (now - this.getSwipeOption(io, "time")))) { return true; } else { return false; } }; /** * Applies style to mouse cursor based on its stage in relation to * [[InteractionObject]]. * * @ignore Exclude from docs * @param Element */ Interaction.prototype.applyCursorOverStyle = function (io) { // Get sprite's cursor ooptions var options = io.cursorOptions; if (!$type.hasValue(options.overStyle)) { return; } // Apply cursor down styles for (var i = 0; i < options.overStyle.length; i++) { $dom.setStyle(io.element, options.overStyle[i].property, options.overStyle[i].value); } }; /** * Applies style to mouse cursor based on its stage in relation to * [[InteractionObject]]. * * @ignore Exclude from docs * @param io Element * @param pointer Pointer */ Interaction.prototype.applyCursorDownStyle = function (io, pointer) { // Not applicable for touch pointers since they don't display a cursor if (pointer.touch) { return; } var downStyle = io.cursorOptions.downStyle; // Is down? if (io.downPointers.contains(pointer) && $type.hasValue(downStyle)) { // Apply cursor down styles for (var i = 0; i < downStyle.length; i++) { this.setTemporaryStyle(this.body, downStyle[i].property, downStyle[i].value); this.setTemporaryStyle(io, downStyle[i].property, downStyle[i].value); } } }; /** * Restores original cursor style for the element. * * @ignore Exclude from docs * @param io Element * @param pointer Pointer */ Interaction.prototype.restoreCursorDownStyle = function (io, pointer) { // Not applicable for touch pointers since they don't display a cursor if (pointer.touch) { return; } var downStyle = io.cursorOptions.downStyle; // Is down? if (io.downPointers.contains(pointer) && $type.hasValue(downStyle)) { // Apply cursor down styles for (var i = 0; i < downStyle.length; i++) { this.restoreStyle(this.body, downStyle[i].property); this.restoreStyle(io, downStyle[i].property); } } }; /** * Sets style on the body of the document. * * @ignore Exclude from docs * @param style Style definitions */ Interaction.prototype.setGlobalStyle = function (style) { var body = getInteraction().body; var styles = ($type.isArray(style) ? style : [style]); for (var i = 0; i < styles.length; i++) { this.setTemporaryStyle(body, styles[i].property, styles[i].value); } }; /** * Restores style on the body of the document. * * @ignore Exclude from docs * @param style Style definitions */ Interaction.prototype.restoreGlobalStyle = function (style) { var body = getInteraction().body; var styles = ($type.isArray(style) ? style : [style]); for (var i = 0; i < styles.length; i++) { this.restoreStyle(body, styles[i].property); } }; /** * Checks if element is a non-cahrt element. * * @param io InteractionObject * @return Global element? */ Interaction.prototype.isGlobalElement = function (io) { return document.body === io.element; }; /** * Checks if pointer has moved since it was created. * * @param pointer Pointer * @param tolerance Tolerance in pixels * @param minTime Minimum time required for the pointer to be down to be considered moved * @return `true` if the pointer has moved */ Interaction.prototype.moved = function (pointer, tolerance, minTime) { /*// If there was more time, we don't care if cursor actually moved let duration = $time.getTime() - pointer.startTime; if ($type.hasValue(minTime) && (minTime > duration)) { return false; }*/ if (minTime === void 0) { minTime = 300; } // That was quick measure shift var shift = this.getShift(pointer); return (Math.abs(shift.x) > tolerance) || (Math.abs(shift.y) > tolerance); }; /** * Returns if pointer is "old", meaning it has been pressing for more than * X milliseconds. * * @ignore * @param pointer Pointer * @param minTime Minimum time to consider pointer old * @return {boolean} */ Interaction.prototype.old = function (pointer, minTime) { if (minTime === void 0) { minTime = 300; } return $time.getTime() - pointer.startTime > minTime; }; /** * Returns total a shift in pointers coordinates between its original * position and now. * * @param pointer Pointer * @return Shift in coordinates (x/y) */ Interaction.prototype.getShift = function (pointer) { return { "x": pointer.startPoint.x - pointer.point.x, "y": pointer.startPoint.y - pointer.point.y }; }; /** * Returns a point from [[Pointer]]'s move history at a certain timetamp. * * @param pointer Pointer * @param timestamp Timestamp * @return Point */ Interaction.prototype.getTrailPoint = function (pointer, timestamp) { var res; for (var i = 0; i < pointer.track.length; i++) { if (pointer.track[i].timestamp >= timestamp) { res = pointer.track[i]; break; } } return res; }; /** * Checks if same pointer already exists in the list. * * @param list List to check agains * @param pointer Pointer * @return Exists? */ Interaction.prototype.pointerExists = function (list, pointer) { var exists = false; list.each(function (item) { if (item == pointer) { return; } exists = item.point.x == pointer.point.x && item.point.y == pointer.point.y; }); return exists; }; /** * Returns an [[InteractionObject]] representation of a DOM element. * * You can use this on any HTML or SVG element, to add interactive features * to it. * * @param element Element * @return InteractionObject */ Interaction.prototype.getInteraction = function (element) { return new InteractionObject(element); }; /** * Sets a style property on an element. Stores original value to be restored * later with [[restoreStyle]]. * * @see {@link restoreStyle} * @param io Element * @param property Property * @param value Value */ Interaction.prototype.setTemporaryStyle = function (io, property, value) { // Get element //let el = io.element.tagName == "g" ? <SVGSVGElement>io.element.parentNode : io.element; var el = io.element; // Save original property if it is set and hasn't been saved before already if ($type.hasValue(el.style[property]) && !io.replacedStyles.hasKey(property)) { io.replacedStyles.setKey(property, el.style[property]); } // Replace with the new one $dom.setStyle(el, property, value); }; /** * Restores specific style on an element. * * @param io Element * @param property Style property */ Interaction.prototype.restoreStyle = function (io, property) { // Reset style if (io.replacedStyles.hasKey(property)) { io.element.style[property] = io.replacedStyles.getKey(property); io.replacedStyles.removeKey(property); } else { delete io.element.style[property]; } }; /** * Restore temporarily reset styles on an element. * * @param io Element */ Interaction.prototype.restoreAllStyles = function (io) { $iter.each(io.replacedStyles.iterator(), function (a) { var key = a[0]; var value = a[1]; io.element.style[key] = value; io.replacedStyles.removeKey(key); }); }; /** * Disposes this object and cleans up after itself. */ Interaction.prototype.dispose = function () { if (!this.isDisposed()) { _super.prototype.dispose.call(this); this.restoreAllStyles(this.body); this.unlockWheel(); } }; // @ts-ignore Used for debugging Interaction.prototype.log = function (text, ev, io) { var show = true; if (show) { // Touchlist? if (ev.changedTouches) { for (var i = 0; i < ev.changedTouches.length; i++) { this.logTouch(text, ev.type, ev.changedTouches[i]); } return; } // Get type var type = ""; if (ev.pointerType) { switch (ev.pointerType) { case 2: type = "touch"; break; case 4: type = "mouse"; break; default: type = ev.pointerType; break; } } else if (typeof TouchEvent != "undefined" && ev instanceof TouchEvent) { type = "touch"; } else if (ev.type.match(/^mouse/)) { type = "mouse"; } else { type = "???"; } // Get ID var id = ""; if ($type.hasValue(ev.identifier)) { id = ev.identifier; } else if ($type.hasValue(ev.pointerId)) { id = ev.pointerId; } else { id = "???"; } if (io) { console.log(text + " (" + io.uid + ") " + ev.type + " " + type + " " + id); } else { console.log(text + " " + ev.type + " " + type + " " + id); } } }; /** * Checks whether there are currently any objects being transformed (dragged * or resized). * * If `except` is set, that object will be ignored. * * @since 4.9.3 * @param except Ignore this object(s) * @return Objects are being transformed */ Interaction.prototype.areTransformed = function (except) { var count = this.transformedObjects.length; if (except) { var ex = $type.isArray(except) ? except : [except]; for (var i = 0; i < ex.length; i++) { if (this.transformedObjects.contains(ex[i])) { count--; } } } return count > 0; }; /** * Log. */ Interaction.prototype.logTouch = function (text, type, ev) { console.log(text + " " + type + " " + "touch" + " " + ev.identifier); }; Object.defineProperty(Interaction, "passiveSupported", { /** * Indicates if passive mode options is supported by this browser. */ get: function () { var _this = this; if (this._passiveSupported == null) { // Check for passive mode support try { var options_1 = Object.defineProperty({}, "passive", { get: function () { _this._passiveSupported = true; } }); window.addEventListener("test", options_1, options_1); window.removeEventListener("test", options_1, options_1); } catch (err) { this._passiveSupported = false; } } return this._passiveSupported; }, enumerable: true, configurable: true }); return Interaction; }(BaseObjectEvents)); export { Interaction }; var interaction = null; /** * Returns a single unified global instance of [[Interaction]]. * * All code should use this function, rather than create their own instances * of [[Interaction]]. */ export function getInteraction() { if (interaction == null) { interaction = new Interaction(); } return interaction; } //# sourceMappingURL=Interaction.js.map
/*global define*/ define(['jquery', 'underscore', 'backbone', 'templates', 'bootstrap-switch'], function($, _, Backbone, JST) { 'use strict'; var FilterLabelView = Backbone.Marionette.ItemView.extend({ tagName: 'div', ui: { 'toggle': '.make-switch' }, getSwitch: function() { return this.$('.make-switch'); }, initialize: function() { this.listenTo(this.model, 'change:enabled', this.enabled); this.listenTo(this.model, 'change:visible', this.visible); this.listenTo(this.model, 'change:count', this.updateCount); this.listenTo(this, 'render', this.postRender); this.listenTo(this.options.vent, 'disable', this.switchDisabled); this.listenTo(this.options.vent, 'enable', this.switchEnabled); _.bindAll(this, 'switchDisabled', 'switchEnabled'); }, updateCount: function(model) { var count = '-'; if (model) { count = model.get('count'); if (count === 0) { count = '-'; } } this.getSwitch().find('label').text(count); }, isEnabled: function(model) { return model.get('enabled'); }, isVisible: function(model) { return model.get('visible'); }, enabled: function() { var enabled = this.isEnabled(this.model); this.getSwitch().bootstrapSwitch('setState', enabled, true /* skip emit change event */ ); }, visible: function() { if (this.isVisible(this.model)) { this.$el.show(); } else { this.$el.hide(); } }, switchDisabled: function() { this.getSwitch().bootstrapSwitch('setActive', false); }, switchEnabled: function() { this.getSwitch().bootstrapSwitch('setActive', true); }, stateColorMap: { 'up/out': ['success', 'warning'], 'down/in': ['success', 'warning'], 'creating': ['success', 'warning'], 'replaying': ['success', 'warning'], 'splitting': ['success', 'warning'], 'scrubbing': ['success', 'warning'], 'degraded': ['success', 'warning'], 'repair': ['success', 'warning'], 'recovering': ['success', 'warning'], 'backfill': ['success', 'warning'], 'wait-backfill': ['success', 'warning'], 'remapped': ['success', 'warning'], 'inconsistent': ['danger', 'default'], 'down': ['danger', 'default'], 'peering': ['danger', 'default'], 'incomplete': ['danger', 'default'], 'stale': ['danger', 'default'] }, postRender: function() { var colors = this.stateColorMap[this.model.get('label')] || ['primary', 'info']; var $switch = this.getSwitch().attr({ 'data-on': colors[0], 'data-off': colors[1] }); var self = this; $switch.bootstrapSwitch('destroy'); $switch.bootstrapSwitch().on('switch-change', function() { var d = $.Deferred(); self.options.vent.trigger('disable'); self.model.set('enabled', !self.model.get('enabled')); self.options.vent.trigger('filter', d); d.done(function() { self.options.vent.trigger('enable'); }); }).on('click', function(evt) { evt.stopPropagation(); evt.preventDefault(); }); this.visible(); this.enabled(); this.updateCount(); }, template: JST['app/scripts/templates/filter-label.ejs'] }); return FilterLabelView; });
jQuery(function($) { $('#simple-colorpicker-1').ace_colorpicker({pull_right:true}).on('change', function(){ var color_class = $(this).find('option:selected').data('class'); var new_class = 'widget-box'; if(color_class != 'default') new_class += ' widget-color-'+color_class; $(this).closest('.widget-box').attr('class', new_class); }); // scrollables $('.scrollable').each(function () { var $this = $(this); $(this).ace_scroll({ size: $this.attr('data-size') || 100, //styleClass: 'scroll-left scroll-margin scroll-thin scroll-dark scroll-light no-track scroll-visible' }); }); $('.scrollable-horizontal').each(function () { var $this = $(this); $(this).ace_scroll( { horizontal: true, styleClass: 'scroll-top',//show the scrollbars on top(default is bottom) size: $this.attr('data-size') || 500, mouseWheelLock: true } ).css({'padding-top': 12}); }); $(window).on('resize.scroll_reset', function() { $('.scrollable-horizontal').ace_scroll('reset'); }); $('#id-checkbox-vertical').prop('checked', false).on('click', function() { $('#widget-toolbox-1').toggleClass('toolbox-vertical') .find('.btn-group').toggleClass('btn-group-vertical') .filter(':first').toggleClass('hidden') .parent().toggleClass('btn-toolbar') }); /** //or use slimScroll plugin $('.slim-scrollable').each(function () { var $this = $(this); $this.slimScroll({ height: $this.data('height') || 100, railVisible:true }); }); */ /**$('.widget-box').on('setting.ace.widget' , function(e) { e.preventDefault(); });*/ /** $('.widget-box').on('show.ace.widget', function(e) { //e.preventDefault(); //this = the widget-box }); $('.widget-box').on('reload.ace.widget', function(e) { //this = the widget-box }); */ //$('#my-widget-box').widget_box('hide'); // widget boxes // widget box drag & drop example $('.widget-container-col').sortable({ connectWith: '.widget-container-col', items:'> .widget-box', handle: ace.vars['touch'] ? '.widget-header' : false, cancel: '.fullscreen', opacity:0.8, revert:true, forceHelperSize:true, placeholder: 'widget-placeholder', forcePlaceholderSize:true, tolerance:'pointer', start: function(event, ui) { //when an element is moved, it's parent becomes empty with almost zero height. //we set a min-height for it to be large enough so that later we can easily drop elements back onto it ui.item.parent().css({'min-height':ui.item.height()}) //ui.sender.css({'min-height':ui.item.height() , 'background-color' : '#F5F5F5'}) }, update: function(event, ui) { ui.item.parent({'min-height':''}) //p.style.removeProperty('background-color'); } }); });
'use strict'; var filter = require('through2-filter'); function filterSince(date) { var isValid = typeof date === 'number' || date instanceof Number || date instanceof Date; if (!isValid) { throw new Error('expected since option to be a date or timestamp'); } return filter.obj(function(file) { return file.stat && file.stat.mtime > date; }); }; module.exports = filterSince;
async %%PARAM%% => %%BODY%%;
module.exports = { entry: './app.tsx', output: { filename: 'bundle.js' }, resolve: { extensions: ['', '.tsx', '.ts', '.js'] }, externals: { react: true, }, module: { loaders: [ { test: /\.ts(x?)$/, loader: 'ts-loader' } ] } } // for test harness purposes only, you would not need this in a normal project module.exports.resolveLoader = { alias: { 'ts-loader': require('path').join(__dirname, "../../index.js") } }
import React, { Component } from 'react' import { Button, Dimmer, Header, Image, Segment } from 'semantic-ui-react' export default class DimmerExampleDimmer extends Component { state = {} handleShow = () => this.setState({ active: true }) handleHide = () => this.setState({ active: false }) render() { const { active } = this.state return ( <div> <Dimmer.Dimmable as={Segment} dimmed={active}> <Dimmer active={active} onClickOutside={this.handleHide} /> <Header as='h3'>Overlayable Section</Header> <Image.Group size='small' className='ui small images'> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Image.Group> <Image size='medium' src='http://semantic-ui.com/images/wireframe/media-paragraph.png' /> </Dimmer.Dimmable> <Button.Group> <Button icon='plus' onClick={this.handleShow} /> <Button icon='minus' onClick={this.handleHide} /> </Button.Group> </div> ) } }
(function () { 'use strict'; angular.module('flexget.services') .run(serverConfig); function serverConfig(toolBar, server, $mdDialog) { var reload = function () { var reloadController = function ($mdDialog) { var vm = this; vm.title = 'Reload Config'; vm.showCircular = true; vm.content = null; vm.buttons = []; vm.ok = null; vm.hide = function () { $mdDialog.hide(); }; var done = function (text) { vm.showCircular = false; vm.content = text; vm.ok = 'Close'; }; server.reload() .success(function () { done('Reload Success'); }) . error(function (data, status, headers, config) { done('Reload failed: ' + data.error); }); }; $mdDialog.show({ templateUrl: 'services/modal/modal.dialog.circular.tmpl.html', parent: angular.element(document.body), controllerAs: 'vm', controller: reloadController }); }; var doShutdown = function () { window.stop(); // Kill any http connection var shutdownController = function ($mdDialog) { var vm = this; vm.title = 'Shutting Down'; vm.showCircular = true; vm.content = null; vm.buttons = []; vm.ok = null; vm.hide = function () { $mdDialog.hide(); }; var done = function (text) { vm.title = 'Shutdown'; vm.showCircular = false; vm.content = text; vm.ok = 'Close'; }; server.shutdown(). success(function () { done('Flexget has been shutdown'); }). error(function (error) { done('Flexget failed to shutdown failed: ' + error.message); }); }; $mdDialog.show({ templateUrl: 'services/modal/modal.dialog.circular.tmpl.html', parent: angular.element(document.body), controllerAs: 'vm', controller: shutdownController }); }; var shutdown = function () { $mdDialog.show( $mdDialog.confirm() .parent(angular.element(document.body)) .title('Shutdown') .content('Are you sure you want to shutdown Flexget?') .ok('Shutdown') .cancel('Cancel') ).then(function () { doShutdown(); }); }; toolBar.registerMenuItem('Manage', 'Reload', 'fa fa-refresh', reload); toolBar.registerMenuItem('Manage', 'Shutdown', 'fa fa-power-off', shutdown); } })();
var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; import { NgModule, Component, HostBinding, ChangeDetectionStrategy, Input, ElementRef, NgZone, Renderer, Directive } from '@angular/core'; import { CompatibilityModule } from '../core'; // TODO(josephperrott): Benchpress tests. /** A single degree in radians. */ var DEGREE_IN_RADIANS = Math.PI / 180; /** Duration of the indeterminate animation. */ var DURATION_INDETERMINATE = 667; /** Duration of the indeterminate animation. */ var DURATION_DETERMINATE = 225; /** Start animation value of the indeterminate animation */ var startIndeterminate = 3; /** End animation value of the indeterminate animation */ var endIndeterminate = 80; /* Maximum angle for the arc. The angle can't be exactly 360, because the arc becomes hidden. */ var MAX_ANGLE = 359.99 / 100; /** * Directive whose purpose is to add the mat- CSS styling to this selector. */ export var MdProgressSpinnerCssMatStyler = (function () { function MdProgressSpinnerCssMatStyler() { } MdProgressSpinnerCssMatStyler = __decorate([ Directive({ selector: 'md-progress-spinner, mat-progress-spinner', host: { '[class.mat-progress-spinner]': 'true' } }), __metadata('design:paramtypes', []) ], MdProgressSpinnerCssMatStyler); return MdProgressSpinnerCssMatStyler; }()); /** * Directive whose purpose is to add the mat- CSS styling to this selector. */ export var MdProgressCircleCssMatStyler = (function () { function MdProgressCircleCssMatStyler() { } MdProgressCircleCssMatStyler = __decorate([ Directive({ selector: 'md-progress-circle, mat-progress-circle', host: { '[class.mat-progress-circle]': 'true' } }), __metadata('design:paramtypes', []) ], MdProgressCircleCssMatStyler); return MdProgressCircleCssMatStyler; }()); /** * <md-progress-spinner> component. */ export var MdProgressSpinner = (function () { function MdProgressSpinner(_ngZone, _elementRef, _renderer) { this._ngZone = _ngZone; this._elementRef = _elementRef; this._renderer = _renderer; /** The id of the last requested animation. */ this._lastAnimationId = 0; this._mode = 'determinate'; this._color = 'primary'; } Object.defineProperty(MdProgressSpinner.prototype, "_ariaValueMin", { /** * Values for aria max and min are only defined as numbers when in a determinate mode. We do this * because voiceover does not report the progress indicator as indeterminate if the aria min * and/or max value are number values. */ get: function () { return this.mode == 'determinate' ? 0 : null; }, enumerable: true, configurable: true }); Object.defineProperty(MdProgressSpinner.prototype, "_ariaValueMax", { get: function () { return this.mode == 'determinate' ? 100 : null; }, enumerable: true, configurable: true }); Object.defineProperty(MdProgressSpinner.prototype, "interdeterminateInterval", { /** @docs-private */ get: function () { return this._interdeterminateInterval; }, /** @docs-private */ set: function (interval) { clearInterval(this._interdeterminateInterval); this._interdeterminateInterval = interval; }, enumerable: true, configurable: true }); /** * Clean up any animations that were running. */ MdProgressSpinner.prototype.ngOnDestroy = function () { this._cleanupIndeterminateAnimation(); }; Object.defineProperty(MdProgressSpinner.prototype, "color", { /** The color of the progress-spinner. Can be primary, accent, or warn. */ get: function () { return this._color; }, set: function (value) { this._updateColor(value); }, enumerable: true, configurable: true }); Object.defineProperty(MdProgressSpinner.prototype, "value", { /** Value of the progress circle. It is bound to the host as the attribute aria-valuenow. */ get: function () { if (this.mode == 'determinate') { return this._value; } }, set: function (v) { if (v != null && this.mode == 'determinate') { var newValue = clamp(v); this._animateCircle((this.value || 0), newValue, linearEase, DURATION_DETERMINATE, 0); this._value = newValue; } }, enumerable: true, configurable: true }); Object.defineProperty(MdProgressSpinner.prototype, "mode", { /** * Mode of the progress circle * * Input must be one of the values from ProgressMode, defaults to 'determinate'. * mode is bound to the host as the attribute host. */ get: function () { return this._mode; }, set: function (m) { if (m == 'indeterminate') { this._startIndeterminateAnimation(); } else { this._cleanupIndeterminateAnimation(); } this._mode = m; }, enumerable: true, configurable: true }); /** * Animates the circle from one percentage value to another. * * @param animateFrom The percentage of the circle filled starting the animation. * @param animateTo The percentage of the circle filled ending the animation. * @param ease The easing function to manage the pace of change in the animation. * @param duration The length of time to show the animation, in milliseconds. * @param rotation The starting angle of the circle fill, with 0° represented at the top center * of the circle. */ MdProgressSpinner.prototype._animateCircle = function (animateFrom, animateTo, ease, duration, rotation) { var _this = this; var id = ++this._lastAnimationId; var startTime = Date.now(); var changeInValue = animateTo - animateFrom; // No need to animate it if the values are the same if (animateTo === animateFrom) { this._renderArc(animateTo, rotation); } else { var animation_1 = function () { var elapsedTime = Math.max(0, Math.min(Date.now() - startTime, duration)); _this._renderArc(ease(elapsedTime, animateFrom, changeInValue, duration), rotation); // Prevent overlapping animations by checking if a new animation has been called for and // if the animation has lasted longer than the animation duration. if (id === _this._lastAnimationId && elapsedTime < duration) { requestAnimationFrame(animation_1); } }; // Run the animation outside of Angular's zone, in order to avoid // hitting ZoneJS and change detection on each frame. this._ngZone.runOutsideAngular(animation_1); } }; /** * Starts the indeterminate animation interval, if it is not already running. */ MdProgressSpinner.prototype._startIndeterminateAnimation = function () { var _this = this; var rotationStartPoint = 0; var start = startIndeterminate; var end = endIndeterminate; var duration = DURATION_INDETERMINATE; var animate = function () { _this._animateCircle(start, end, materialEase, duration, rotationStartPoint); // Prevent rotation from reaching Number.MAX_SAFE_INTEGER. rotationStartPoint = (rotationStartPoint + end) % 100; var temp = start; start = -end; end = -temp; }; if (!this.interdeterminateInterval) { this._ngZone.runOutsideAngular(function () { _this.interdeterminateInterval = setInterval(animate, duration + 50, 0, false); animate(); }); } }; /** * Removes interval, ending the animation. */ MdProgressSpinner.prototype._cleanupIndeterminateAnimation = function () { this.interdeterminateInterval = null; }; /** * Renders the arc onto the SVG element. Proxies `getArc` while setting the proper * DOM attribute on the `<path>`. */ MdProgressSpinner.prototype._renderArc = function (currentValue, rotation) { // Caches the path reference so it doesn't have to be looked up every time. var path = this._path = this._path || this._elementRef.nativeElement.querySelector('path'); // Ensure that the path was found. This may not be the case if the // animation function fires too early. if (path) { path.setAttribute('d', getSvgArc(currentValue, rotation)); } }; /** * Updates the color of the progress-spinner by adding the new palette class to the element * and removing the old one. */ MdProgressSpinner.prototype._updateColor = function (newColor) { this._setElementColor(this._color, false); this._setElementColor(newColor, true); this._color = newColor; }; /** Sets the given palette class on the component element. */ MdProgressSpinner.prototype._setElementColor = function (color, isAdd) { if (color != null && color != '') { this._renderer.setElementClass(this._elementRef.nativeElement, "mat-" + color, isAdd); } }; __decorate([ Input(), __metadata('design:type', String) ], MdProgressSpinner.prototype, "color", null); __decorate([ Input(), HostBinding('attr.aria-valuenow'), __metadata('design:type', Object) ], MdProgressSpinner.prototype, "value", null); __decorate([ HostBinding('attr.mode'), Input(), __metadata('design:type', Object) ], MdProgressSpinner.prototype, "mode", null); MdProgressSpinner = __decorate([ Component({selector: 'md-progress-spinner, mat-progress-spinner, md-progress-circle, mat-progress-circle', host: { 'role': 'progressbar', '[attr.aria-valuemin]': '_ariaValueMin', '[attr.aria-valuemax]': '_ariaValueMax' }, template: "<svg viewBox=\"0 0 100 100\" preserveAspectRatio=\"xMidYMid meet\"><path></path></svg>", styles: [":host{display:block;height:100px;width:100px;overflow:hidden}:host svg{height:100%;width:100%;transform-origin:center}:host path{fill:transparent;stroke-width:10px}:host[mode=indeterminate] svg{animation-duration:5.25s,2.887s;animation-name:mat-progress-spinner-sporadic-rotate,mat-progress-spinner-linear-rotate;animation-timing-function:cubic-bezier(.35,0,.25,1),linear;animation-iteration-count:infinite;transition:none}@keyframes mat-progress-spinner-linear-rotate{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}@keyframes mat-progress-spinner-sporadic-rotate{12.5%{transform:rotate(135deg)}25%{transform:rotate(270deg)}37.5%{transform:rotate(405deg)}50%{transform:rotate(540deg)}62.5%{transform:rotate(675deg)}75%{transform:rotate(810deg)}87.5%{transform:rotate(945deg)}100%{transform:rotate(1080deg)}}"], changeDetection: ChangeDetectionStrategy.OnPush, }), __metadata('design:paramtypes', [NgZone, ElementRef, Renderer]) ], MdProgressSpinner); return MdProgressSpinner; }()); /** * <md-spinner> component. * * This is a component definition to be used as a convenience reference to create an * indeterminate <md-progress-spinner> instance. */ export var MdSpinner = (function (_super) { __extends(MdSpinner, _super); function MdSpinner(elementRef, ngZone, renderer) { _super.call(this, ngZone, elementRef, renderer); this.mode = 'indeterminate'; } MdSpinner.prototype.ngOnDestroy = function () { // The `ngOnDestroy` from `MdProgressSpinner` should be called explicitly, because // in certain cases Angular won't call it (e.g. when using AoT and in unit tests). _super.prototype.ngOnDestroy.call(this); }; MdSpinner = __decorate([ Component({selector: 'md-spinner, mat-spinner', host: { 'role': 'progressbar', 'mode': 'indeterminate', '[class.mat-spinner]': 'true', }, template: "<svg viewBox=\"0 0 100 100\" preserveAspectRatio=\"xMidYMid meet\"><path></path></svg>", styles: [":host{display:block;height:100px;width:100px;overflow:hidden}:host svg{height:100%;width:100%;transform-origin:center}:host path{fill:transparent;stroke-width:10px}:host[mode=indeterminate] svg{animation-duration:5.25s,2.887s;animation-name:mat-progress-spinner-sporadic-rotate,mat-progress-spinner-linear-rotate;animation-timing-function:cubic-bezier(.35,0,.25,1),linear;animation-iteration-count:infinite;transition:none}@keyframes mat-progress-spinner-linear-rotate{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}@keyframes mat-progress-spinner-sporadic-rotate{12.5%{transform:rotate(135deg)}25%{transform:rotate(270deg)}37.5%{transform:rotate(405deg)}50%{transform:rotate(540deg)}62.5%{transform:rotate(675deg)}75%{transform:rotate(810deg)}87.5%{transform:rotate(945deg)}100%{transform:rotate(1080deg)}}"], }), __metadata('design:paramtypes', [ElementRef, NgZone, Renderer]) ], MdSpinner); return MdSpinner; }(MdProgressSpinner)); /** * Module functions. */ /** Clamps a value to be between 0 and 100. */ function clamp(v) { return Math.max(0, Math.min(100, v)); } /** * Converts Polar coordinates to Cartesian. */ function polarToCartesian(radius, pathRadius, angleInDegrees) { var angleInRadians = (angleInDegrees - 90) * DEGREE_IN_RADIANS; return (radius + (pathRadius * Math.cos(angleInRadians))) + ',' + (radius + (pathRadius * Math.sin(angleInRadians))); } /** * Easing function for linear animation. */ function linearEase(currentTime, startValue, changeInValue, duration) { return changeInValue * currentTime / duration + startValue; } /** * Easing function to match material design indeterminate animation. */ function materialEase(currentTime, startValue, changeInValue, duration) { var time = currentTime / duration; var timeCubed = Math.pow(time, 3); var timeQuad = Math.pow(time, 4); var timeQuint = Math.pow(time, 5); return startValue + changeInValue * ((6 * timeQuint) + (-15 * timeQuad) + (10 * timeCubed)); } /** * Determines the path value to define the arc. Converting percentage values to to polar * coordinates on the circle, and then to cartesian coordinates in the viewport. * * @param currentValue The current percentage value of the progress circle, the percentage of the * circle to fill. * @param rotation The starting point of the circle with 0 being the 0 degree point. * @return A string for an SVG path representing a circle filled from the starting point to the * percentage value provided. */ function getSvgArc(currentValue, rotation) { var startPoint = rotation || 0; var radius = 50; var pathRadius = 40; var startAngle = startPoint * MAX_ANGLE; var endAngle = currentValue * MAX_ANGLE; var start = polarToCartesian(radius, pathRadius, startAngle); var end = polarToCartesian(radius, pathRadius, endAngle + startAngle); var arcSweep = endAngle < 0 ? 0 : 1; var largeArcFlag; if (endAngle < 0) { largeArcFlag = endAngle >= -180 ? 0 : 1; } else { largeArcFlag = endAngle <= 180 ? 0 : 1; } return "M" + start + "A" + pathRadius + "," + pathRadius + " 0 " + largeArcFlag + "," + arcSweep + " " + end; } export var MdProgressSpinnerModule = (function () { function MdProgressSpinnerModule() { } /** @deprecated */ MdProgressSpinnerModule.forRoot = function () { return { ngModule: MdProgressSpinnerModule, providers: [] }; }; MdProgressSpinnerModule = __decorate([ NgModule({ imports: [CompatibilityModule], exports: [ MdProgressSpinner, MdSpinner, CompatibilityModule, MdProgressSpinnerCssMatStyler, MdProgressCircleCssMatStyler ], declarations: [ MdProgressSpinner, MdSpinner, MdProgressSpinnerCssMatStyler, MdProgressCircleCssMatStyler ], }), __metadata('design:paramtypes', []) ], MdProgressSpinnerModule); return MdProgressSpinnerModule; }()); //# sourceMappingURL=progress-spinner.js.map
(function() { this.GroupMembers = (function() { function GroupMembers() { $('li.group_member').bind('ajax:success', function() { return $(this).fadeOut(); }); } return GroupMembers; })(); }).call(this);
var ascli = require("../ascli.js").app("myapp"); ascli.banner("staying straight".green.bold, "v1.0.0 through ascli"); console.log("Hello world!".white.bold); console.log("...of ascli\n"); console.log("Command line arguments".white.bold); console.log(ascli.opt, ascli.argv); ascli.banner("abcdefghijklmnopqrstuvwxyz 0123456789"); ascli.ok("yep, that worked.");
'use strict'; const common = require('../common'); // This immediate should not execute as it was unrefed // and nothing else is keeping the event loop alive setImmediate(() => { setImmediate(common.mustNotCall()).unref(); });
var parent = require('../../actual/error/to-string'); module.exports = parent;
/* Copyright (c) 2006-2011 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the Clear BSD license. * See http://svn.openlayers.org/trunk/openlayers/license.txt for the * full text of the license. */ /** * @requires OpenLayers/Format/XML.js * @requires OpenLayers/Geometry/Polygon.js * @requires OpenLayers/Geometry/Point.js * @requires OpenLayers/Geometry/MultiPolygon.js * @requires OpenLayers/Geometry/LinearRing.js */ /** * Class: OpenLayers.Format.ArcXML * Read/Wite ArcXML. Create a new instance with the <OpenLayers.Format.ArcXML> * constructor. * * Inherits from: * - <OpenLayers.Format> */ OpenLayers.Format.ArcXML = OpenLayers.Class(OpenLayers.Format.XML, { /** * Property: fontStyleKeys * {Array} List of keys used in font styling. */ fontStyleKeys: [ 'antialiasing', 'blockout', 'font', 'fontcolor','fontsize', 'fontstyle', 'glowing', 'interval', 'outline', 'printmode', 'shadow', 'transparency' ], /** * Property: request * A get_image request destined for an ArcIMS server. */ request: null, /** * Property: response * A parsed response from an ArcIMS server. */ response: null, /** * Constructor: OpenLayers.Format.ArcXML * Create a new parser/writer for ArcXML. Create an instance of this class * to begin authoring a request to an ArcIMS service. This is used * primarily by the ArcIMS layer, but could be used to do other wild * stuff, like geocoding. * * Parameters: * options - {Object} An optional object whose properties will be set on * this instance. */ initialize: function(options) { this.request = new OpenLayers.Format.ArcXML.Request(); this.response = new OpenLayers.Format.ArcXML.Response(); if (options) { if (options.requesttype == "feature") { this.request.get_image = null; var qry = this.request.get_feature.query; this.addCoordSys(qry.featurecoordsys, options.featureCoordSys); this.addCoordSys(qry.filtercoordsys, options.filterCoordSys); if (options.polygon) { qry.isspatial = true; qry.spatialfilter.polygon = options.polygon; } else if (options.envelope) { qry.isspatial = true; qry.spatialfilter.envelope = {minx:0, miny:0, maxx:0, maxy:0}; this.parseEnvelope(qry.spatialfilter.envelope, options.envelope); } } else if (options.requesttype == "image") { this.request.get_feature = null; var props = this.request.get_image.properties; this.parseEnvelope(props.envelope, options.envelope); this.addLayers(props.layerlist, options.layers); this.addImageSize(props.imagesize, options.tileSize); this.addCoordSys(props.featurecoordsys, options.featureCoordSys); this.addCoordSys(props.filtercoordsys, options.filterCoordSys); } else { // if an arcxml object is being created with no request type, it is // probably going to consume a response, so do not throw an error if // the requesttype is not defined this.request = null; } } OpenLayers.Format.XML.prototype.initialize.apply(this, [options]); }, /** * Method: parseEnvelope * Parse an array of coordinates into an ArcXML envelope structure. * * Parameters: * env - {Object} An envelope object that will contain the parsed coordinates. * arr - {Array(double)} An array of coordinates in the order: [ minx, miny, maxx, maxy ] */ parseEnvelope: function(env, arr) { if (arr && arr.length == 4) { env.minx = arr[0]; env.miny = arr[1]; env.maxx = arr[2]; env.maxy = arr[3]; } }, /** * Method: addLayers * Add a collection of layers to another collection of layers. Each layer in the list is tuple of * { id, visible }. These layer collections represent the * /ARCXML/REQUEST/get_image/PROPERTIES/LAYERLIST/LAYERDEF items in ArcXML * * TODO: Add support for dynamic layer rendering. * * Parameters: * ll - {Array({id,visible})} A list of layer definitions. * lyrs - {Array({id,visible})} A list of layer definitions. */ addLayers: function(ll, lyrs) { for(var lind = 0, len=lyrs.length; lind < len; lind++) { ll.push(lyrs[lind]); } }, /** * Method: addImageSize * Set the size of the requested image. * * Parameters: * imsize - {Object} An ArcXML imagesize object. * olsize - {OpenLayers.Size} The image size to set. */ addImageSize: function(imsize, olsize) { if (olsize !== null) { imsize.width = olsize.w; imsize.height = olsize.h; imsize.printwidth = olsize.w; imsize.printheight = olsize.h; } }, /** * Method: addCoordSys * Add the coordinate system information to an object. The object may be * * Parameters: * featOrFilt - {Object} A featurecoordsys or filtercoordsys ArcXML structure. * fsys - {String} or {OpenLayers.Projection} or {filtercoordsys} or * {featurecoordsys} A projection representation. If it's a {String}, * the value is assumed to be the SRID. If it's a {OpenLayers.Projection} * AND Proj4js is available, the projection number and name are extracted * from there. If it's a filter or feature ArcXML structure, it is copied. */ addCoordSys: function(featOrFilt, fsys) { if (typeof fsys == "string") { featOrFilt.id = parseInt(fsys); featOrFilt.string = fsys; } // is this a proj4js instance? else if (typeof fsys == "object" && fsys.proj !== null){ featOrFilt.id = fsys.proj.srsProjNumber; featOrFilt.string = fsys.proj.srsCode; } else { featOrFilt = fsys; } }, /** * APIMethod: iserror * Check to see if the response from the server was an error. * * Parameters: * data - {String} or {DOMElement} data to read/parse. If nothing is supplied, * the current response is examined. * * Returns: * {Boolean} true if the response was an error. */ iserror: function(data) { var ret = null; if (!data) { ret = (this.response.error !== ''); } else { data = OpenLayers.Format.XML.prototype.read.apply(this, [data]); var errorNodes = data.documentElement.getElementsByTagName("ERROR"); ret = (errorNodes !== null && errorNodes.length > 0); } return ret; }, /** * APIMethod: read * Read data from a string, and return an response. * * Parameters: * data - {String} or {DOMElement} data to read/parse. * * Returns: * {OpenLayers.Format.ArcXML.Response} An ArcXML response. Note that this response * data may change in the future. */ read: function(data) { if(typeof data == "string") { data = OpenLayers.Format.XML.prototype.read.apply(this, [data]); } var arcNode = null; if (data && data.documentElement) { if(data.documentElement.nodeName == "ARCXML") { arcNode = data.documentElement; } else { arcNode = data.documentElement.getElementsByTagName("ARCXML")[0]; } } // in Safari, arcNode will be there but will have a child named // parsererror if (!arcNode || arcNode.firstChild.nodeName === 'parsererror') { var error, source; try { error = data.firstChild.nodeValue; source = data.firstChild.childNodes[1].firstChild.nodeValue; } catch (err) { // pass } throw { message: "Error parsing the ArcXML request", error: error, source: source }; } var response = this.parseResponse(arcNode); return response; }, /** * APIMethod: write * Generate an ArcXml document string for sending to an ArcIMS server. * * Returns: * {String} A string representing the ArcXML document request. */ write: function(request) { if (!request) { request = this.request; } var root = this.createElementNS("", "ARCXML"); root.setAttribute("version","1.1"); var reqElem = this.createElementNS("", "REQUEST"); if (request.get_image != null) { var getElem = this.createElementNS("", "GET_IMAGE"); reqElem.appendChild(getElem); var propElem = this.createElementNS("", "PROPERTIES"); getElem.appendChild(propElem); var props = request.get_image.properties; if (props.featurecoordsys != null) { var feat = this.createElementNS("", "FEATURECOORDSYS"); propElem.appendChild(feat); if (props.featurecoordsys.id === 0) { feat.setAttribute("string", props.featurecoordsys['string']); } else { feat.setAttribute("id", props.featurecoordsys.id); } } if (props.filtercoordsys != null) { var filt = this.createElementNS("", "FILTERCOORDSYS"); propElem.appendChild(filt); if (props.filtercoordsys.id === 0) { filt.setAttribute("string", props.filtercoordsys.string); } else { filt.setAttribute("id", props.filtercoordsys.id); } } if (props.envelope != null) { var env = this.createElementNS("", "ENVELOPE"); propElem.appendChild(env); env.setAttribute("minx", props.envelope.minx); env.setAttribute("miny", props.envelope.miny); env.setAttribute("maxx", props.envelope.maxx); env.setAttribute("maxy", props.envelope.maxy); } var imagesz = this.createElementNS("", "IMAGESIZE"); propElem.appendChild(imagesz); imagesz.setAttribute("height", props.imagesize.height); imagesz.setAttribute("width", props.imagesize.width); if (props.imagesize.height != props.imagesize.printheight || props.imagesize.width != props.imagesize.printwidth) { imagesz.setAttribute("printheight", props.imagesize.printheight); imagesz.setArrtibute("printwidth", props.imagesize.printwidth); } if (props.background != null) { var backgrnd = this.createElementNS("", "BACKGROUND"); propElem.appendChild(backgrnd); backgrnd.setAttribute("color", props.background.color.r + "," + props.background.color.g + "," + props.background.color.b); if (props.background.transcolor !== null) { backgrnd.setAttribute("transcolor", props.background.transcolor.r + "," + props.background.transcolor.g + "," + props.background.transcolor.b); } } if (props.layerlist != null && props.layerlist.length > 0) { var layerlst = this.createElementNS("", "LAYERLIST"); propElem.appendChild(layerlst); for (var ld = 0; ld < props.layerlist.length; ld++) { var ldef = this.createElementNS("", "LAYERDEF"); layerlst.appendChild(ldef); ldef.setAttribute("id", props.layerlist[ld].id); ldef.setAttribute("visible", props.layerlist[ld].visible); if (typeof props.layerlist[ld].query == "object") { var query = props.layerlist[ld].query; if (query.where.length < 0) { continue; } var queryElem = null; if (typeof query.spatialfilter == "boolean" && query.spatialfilter) { // handle spatial filter madness queryElem = this.createElementNS("", "SPATIALQUERY"); } else { queryElem = this.createElementNS("", "QUERY"); } queryElem.setAttribute("where", query.where); if (typeof query.accuracy == "number" && query.accuracy > 0) { queryElem.setAttribute("accuracy", query.accuracy); } if (typeof query.featurelimit == "number" && query.featurelimit < 2000) { queryElem.setAttribute("featurelimit", query.featurelimit); } if (typeof query.subfields == "string" && query.subfields != "#ALL#") { queryElem.setAttribute("subfields", query.subfields); } if (typeof query.joinexpression == "string" && query.joinexpression.length > 0) { queryElem.setAttribute("joinexpression", query.joinexpression); } if (typeof query.jointables == "string" && query.jointables.length > 0) { queryElem.setAttribute("jointables", query.jointables); } ldef.appendChild(queryElem); } if (typeof props.layerlist[ld].renderer == "object") { this.addRenderer(ldef, props.layerlist[ld].renderer); } } } } else if (request.get_feature != null) { var getElem = this.createElementNS("", "GET_FEATURES"); getElem.setAttribute("outputmode", "newxml"); getElem.setAttribute("checkesc", "true"); if (request.get_feature.geometry) { getElem.setAttribute("geometry", request.get_feature.geometry); } else { getElem.setAttribute("geometry", "false"); } if (request.get_feature.compact) { getElem.setAttribute("compact", request.get_feature.compact); } if (request.get_feature.featurelimit == "number") { getElem.setAttribute("featurelimit", request.get_feature.featurelimit); } getElem.setAttribute("globalenvelope", "true"); reqElem.appendChild(getElem); if (request.get_feature.layer != null && request.get_feature.layer.length > 0) { var lyrElem = this.createElementNS("", "LAYER"); lyrElem.setAttribute("id", request.get_feature.layer); getElem.appendChild(lyrElem); } var fquery = request.get_feature.query; if (fquery != null) { var qElem = null; if (fquery.isspatial) { qElem = this.createElementNS("", "SPATIALQUERY"); } else { qElem = this.createElementNS("", "QUERY"); } getElem.appendChild(qElem); if (typeof fquery.accuracy == "number") { qElem.setAttribute("accuracy", fquery.accuracy); } //qElem.setAttribute("featurelimit", "5"); if (fquery.featurecoordsys != null) { var fcsElem1 = this.createElementNS("", "FEATURECOORDSYS"); if (fquery.featurecoordsys.id == 0) { fcsElem1.setAttribute("string", fquery.featurecoordsys.string); } else { fcsElem1.setAttribute("id", fquery.featurecoordsys.id); } qElem.appendChild(fcsElem1); } if (fquery.filtercoordsys != null) { var fcsElem2 = this.createElementNS("", "FILTERCOORDSYS"); if (fquery.filtercoordsys.id === 0) { fcsElem2.setAttribute("string", fquery.filtercoordsys.string); } else { fcsElem2.setAttribute("id", fquery.filtercoordsys.id); } qElem.appendChild(fcsElem2); } if (fquery.buffer > 0) { var bufElem = this.createElementNS("", "BUFFER"); bufElem.setAttribute("distance", fquery.buffer); qElem.appendChild(bufElem); } if (fquery.isspatial) { var spfElem = this.createElementNS("", "SPATIALFILTER"); spfElem.setAttribute("relation", fquery.spatialfilter.relation); qElem.appendChild(spfElem); if (fquery.spatialfilter.envelope) { var envElem = this.createElementNS("", "ENVELOPE"); envElem.setAttribute("minx", fquery.spatialfilter.envelope.minx); envElem.setAttribute("miny", fquery.spatialfilter.envelope.miny); envElem.setAttribute("maxx", fquery.spatialfilter.envelope.maxx); envElem.setAttribute("maxy", fquery.spatialfilter.envelope.maxy); spfElem.appendChild(envElem); } else if(typeof fquery.spatialfilter.polygon == "object") { spfElem.appendChild(this.writePolygonGeometry(fquery.spatialfilter.polygon)); } } if (fquery.where != null && fquery.where.length > 0) { qElem.setAttribute("where", fquery.where); } } } root.appendChild(reqElem); return OpenLayers.Format.XML.prototype.write.apply(this, [root]); }, addGroupRenderer: function(ldef, toprenderer) { var topRelem = this.createElementNS("", "GROUPRENDERER"); ldef.appendChild(topRelem); for (var rind = 0; rind < toprenderer.length; rind++) { var renderer = toprenderer[rind]; this.addRenderer(topRelem, renderer); } }, addRenderer: function(topRelem, renderer) { if (OpenLayers.Util.isArray(renderer)) { this.addGroupRenderer(topRelem, renderer); } else { var renderElem = this.createElementNS("", renderer.type.toUpperCase() + "RENDERER"); topRelem.appendChild(renderElem); if (renderElem.tagName == "VALUEMAPRENDERER") { this.addValueMapRenderer(renderElem, renderer); } else if (renderElem.tagName == "VALUEMAPLABELRENDERER") { this.addValueMapLabelRenderer(renderElem, renderer); } else if (renderElem.tagName == "SIMPLELABELRENDERER") { this.addSimpleLabelRenderer(renderElem, renderer); } else if (renderElem.tagName == "SCALEDEPENDENTRENDERER") { this.addScaleDependentRenderer(renderElem, renderer); } } }, addScaleDependentRenderer: function(renderElem, renderer) { if (typeof renderer.lower == "string" || typeof renderer.lower == "number") { renderElem.setAttribute("lower", renderer.lower); } if (typeof renderer.upper == "string" || typeof renderer.upper == "number") { renderElem.setAttribute("upper", renderer.upper); } this.addRenderer(renderElem, renderer.renderer); }, addValueMapLabelRenderer: function(renderElem, renderer) { renderElem.setAttribute("lookupfield", renderer.lookupfield); renderElem.setAttribute("labelfield", renderer.labelfield); if (typeof renderer.exacts == "object") { for (var ext=0, extlen=renderer.exacts.length; ext<extlen; ext++) { var exact = renderer.exacts[ext]; var eelem = this.createElementNS("", "EXACT"); if (typeof exact.value == "string") { eelem.setAttribute("value", exact.value); } if (typeof exact.label == "string") { eelem.setAttribute("label", exact.label); } if (typeof exact.method == "string") { eelem.setAttribute("method", exact.method); } renderElem.appendChild(eelem); if (typeof exact.symbol == "object") { var selem = null; if (exact.symbol.type == "text") { selem = this.createElementNS("", "TEXTSYMBOL"); } if (selem != null) { var keys = this.fontStyleKeys; for (var i = 0, len = keys.length; i < len; i++) { var key = keys[i]; if (exact.symbol[key]) { selem.setAttribute(key, exact.symbol[key]); } } eelem.appendChild(selem); } } } // for each exact } }, addValueMapRenderer: function(renderElem, renderer) { renderElem.setAttribute("lookupfield", renderer.lookupfield); if (typeof renderer.ranges == "object") { for(var rng=0, rnglen=renderer.ranges.length; rng<rnglen; rng++) { var range = renderer.ranges[rng]; var relem = this.createElementNS("", "RANGE"); relem.setAttribute("lower", range.lower); relem.setAttribute("upper", range.upper); renderElem.appendChild(relem); if (typeof range.symbol == "object") { var selem = null; if (range.symbol.type == "simplepolygon") { selem = this.createElementNS("", "SIMPLEPOLYGONSYMBOL"); } if (selem != null) { if (typeof range.symbol.boundarycolor == "string") { selem.setAttribute("boundarycolor", range.symbol.boundarycolor); } if (typeof range.symbol.fillcolor == "string") { selem.setAttribute("fillcolor", range.symbol.fillcolor); } if (typeof range.symbol.filltransparency == "number") { selem.setAttribute("filltransparency", range.symbol.filltransparency); } relem.appendChild(selem); } } } // for each range } else if (typeof renderer.exacts == "object") { for (var ext=0, extlen=renderer.exacts.length; ext<extlen; ext++) { var exact = renderer.exacts[ext]; var eelem = this.createElementNS("", "EXACT"); if (typeof exact.value == "string") { eelem.setAttribute("value", exact.value); } if (typeof exact.label == "string") { eelem.setAttribute("label", exact.label); } if (typeof exact.method == "string") { eelem.setAttribute("method", exact.method); } renderElem.appendChild(eelem); if (typeof exact.symbol == "object") { var selem = null; if (exact.symbol.type == "simplemarker") { selem = this.createElementNS("", "SIMPLEMARKERSYMBOL"); } if (selem != null) { if (typeof exact.symbol.antialiasing == "string") { selem.setAttribute("antialiasing", exact.symbol.antialiasing); } if (typeof exact.symbol.color == "string") { selem.setAttribute("color", exact.symbol.color); } if (typeof exact.symbol.outline == "string") { selem.setAttribute("outline", exact.symbol.outline); } if (typeof exact.symbol.overlap == "string") { selem.setAttribute("overlap", exact.symbol.overlap); } if (typeof exact.symbol.shadow == "string") { selem.setAttribute("shadow", exact.symbol.shadow); } if (typeof exact.symbol.transparency == "number") { selem.setAttribute("transparency", exact.symbol.transparency); } //if (typeof exact.symbol.type == "string") // selem.setAttribute("type", exact.symbol.type); if (typeof exact.symbol.usecentroid == "string") { selem.setAttribute("usecentroid", exact.symbol.usecentroid); } if (typeof exact.symbol.width == "number") { selem.setAttribute("width", exact.symbol.width); } eelem.appendChild(selem); } } } // for each exact } }, addSimpleLabelRenderer: function(renderElem, renderer) { renderElem.setAttribute("field", renderer.field); var keys = ['featureweight', 'howmanylabels', 'labelbufferratio', 'labelpriorities', 'labelweight', 'linelabelposition', 'rotationalangles']; for (var i=0, len=keys.length; i<len; i++) { var key = keys[i]; if (renderer[key]) { renderElem.setAttribute(key, renderer[key]); } } if (renderer.symbol.type == "text") { var symbol = renderer.symbol; var selem = this.createElementNS("", "TEXTSYMBOL"); renderElem.appendChild(selem); var keys = this.fontStyleKeys; for (var i=0, len=keys.length; i<len; i++) { var key = keys[i]; if (symbol[key]) { selem.setAttribute(key, renderer[key]); } } } }, writePolygonGeometry: function(polygon) { if (!(polygon instanceof OpenLayers.Geometry.Polygon)) { throw { message:'Cannot write polygon geometry to ArcXML with an ' + polygon.CLASS_NAME + ' object.', geometry: polygon }; } var polyElem = this.createElementNS("", "POLYGON"); for (var ln=0, lnlen=polygon.components.length; ln<lnlen; ln++) { var ring = polygon.components[ln]; var ringElem = this.createElementNS("", "RING"); for (var rn=0, rnlen=ring.components.length; rn<rnlen; rn++) { var point = ring.components[rn]; var pointElem = this.createElementNS("", "POINT"); pointElem.setAttribute("x", point.x); pointElem.setAttribute("y", point.y); ringElem.appendChild(pointElem); } polyElem.appendChild(ringElem); } return polyElem; }, /** * Method: parseResponse * Take an ArcXML response, and parse in into this object's internal properties. * * Parameters: * data - {String} or {DOMElement} The ArcXML response, as either a string or the * top level DOMElement of the response. */ parseResponse: function(data) { if(typeof data == "string") { var newData = new OpenLayers.Format.XML(); data = newData.read(data); } var response = new OpenLayers.Format.ArcXML.Response(); var errorNode = data.getElementsByTagName("ERROR"); if (errorNode != null && errorNode.length > 0) { response.error = this.getChildValue(errorNode, "Unknown error."); } else { var responseNode = data.getElementsByTagName("RESPONSE"); if (responseNode == null || responseNode.length == 0) { response.error = "No RESPONSE tag found in ArcXML response."; return response; } var rtype = responseNode[0].firstChild.nodeName; if (rtype == "#text") { rtype = responseNode[0].firstChild.nextSibling.nodeName; } if (rtype == "IMAGE") { var envelopeNode = data.getElementsByTagName("ENVELOPE"); var outputNode = data.getElementsByTagName("OUTPUT"); if (envelopeNode == null || envelopeNode.length == 0) { response.error = "No ENVELOPE tag found in ArcXML response."; } else if (outputNode == null || outputNode.length == 0) { response.error = "No OUTPUT tag found in ArcXML response."; } else { var envAttr = this.parseAttributes(envelopeNode[0]); var outputAttr = this.parseAttributes(outputNode[0]); if (typeof outputAttr.type == "string") { response.image = { envelope: envAttr, output: { type: outputAttr.type, data: this.getChildValue(outputNode[0]) } }; } else { response.image = { envelope: envAttr, output: outputAttr }; } } } else if (rtype == "FEATURES") { var features = responseNode[0].getElementsByTagName("FEATURES"); // get the feature count var featureCount = features[0].getElementsByTagName("FEATURECOUNT"); response.features.featurecount = featureCount[0].getAttribute("count"); if (response.features.featurecount > 0) { // get the feature envelope var envelope = features[0].getElementsByTagName("ENVELOPE"); response.features.envelope = this.parseAttributes(envelope[0], typeof(0)); // get the field values per feature var featureList = features[0].getElementsByTagName("FEATURE"); for (var fn = 0; fn < featureList.length; fn++) { var feature = new OpenLayers.Feature.Vector(); var fields = featureList[fn].getElementsByTagName("FIELD"); for (var fdn = 0; fdn < fields.length; fdn++) { var fieldName = fields[fdn].getAttribute("name"); var fieldValue = fields[fdn].getAttribute("value"); feature.attributes[ fieldName ] = fieldValue; } var geom = featureList[fn].getElementsByTagName("POLYGON"); if (geom.length > 0) { // if there is a polygon, create an openlayers polygon, and assign // it to the .geometry property of the feature var ring = geom[0].getElementsByTagName("RING"); var polys = []; for (var rn = 0; rn < ring.length; rn++) { var linearRings = []; linearRings.push(this.parsePointGeometry(ring[rn])); var holes = ring[rn].getElementsByTagName("HOLE"); for (var hn = 0; hn < holes.length; hn++) { linearRings.push(this.parsePointGeometry(holes[hn])); } holes = null; polys.push(new OpenLayers.Geometry.Polygon(linearRings)); linearRings = null; } ring = null; if (polys.length == 1) { feature.geometry = polys[0]; } else { feature.geometry = new OpenLayers.Geometry.MultiPolygon(polys); } } response.features.feature.push(feature); } } } else { response.error = "Unidentified response type."; } } return response; }, /** * Method: parseAttributes * * Parameters: * node - {<DOMElement>} An element to parse attributes from. * * Returns: * {Object} An attributes object, with properties set to attribute values. */ parseAttributes: function(node,type) { var attributes = {}; for(var attr = 0; attr < node.attributes.length; attr++) { if (type == "number") { attributes[node.attributes[attr].nodeName] = parseFloat(node.attributes[attr].nodeValue); } else { attributes[node.attributes[attr].nodeName] = node.attributes[attr].nodeValue; } } return attributes; }, /** * Method: parsePointGeometry * * Parameters: * node - {<DOMElement>} An element to parse <COORDS> or <POINT> arcxml data from. * * Returns: * {OpenLayers.Geometry.LinearRing} A linear ring represented by the node's points. */ parsePointGeometry: function(node) { var ringPoints = []; var coords = node.getElementsByTagName("COORDS"); if (coords.length > 0) { // if coords is present, it's the only coords item var coordArr = this.getChildValue(coords[0]); coordArr = coordArr.split(/;/); for (var cn = 0; cn < coordArr.length; cn++) { var coordItems = coordArr[cn].split(/ /); ringPoints.push(new OpenLayers.Geometry.Point(coordItems[0], coordItems[1])); } coords = null; } else { var point = node.getElementsByTagName("POINT"); if (point.length > 0) { for (var pn = 0; pn < point.length; pn++) { ringPoints.push( new OpenLayers.Geometry.Point( parseFloat(point[pn].getAttribute("x")), parseFloat(point[pn].getAttribute("y")) ) ); } } point = null; } return new OpenLayers.Geometry.LinearRing(ringPoints); }, CLASS_NAME: "OpenLayers.Format.ArcXML" }); OpenLayers.Format.ArcXML.Request = OpenLayers.Class({ initialize: function(params) { var defaults = { get_image: { properties: { background: null, /*{ color: { r:255, g:255, b:255 }, transcolor: null },*/ draw: true, envelope: { minx: 0, miny: 0, maxx: 0, maxy: 0 }, featurecoordsys: { id:0, string:"", datumtransformid:0, datumtransformstring:"" }, filtercoordsys:{ id:0, string:"", datumtransformid:0, datumtransformstring:"" }, imagesize:{ height:0, width:0, dpi:96, printheight:0, printwidth:0, scalesymbols:false }, layerlist:[], /* no support for legends */ output:{ baseurl:"", legendbaseurl:"", legendname:"", legendpath:"", legendurl:"", name:"", path:"", type:"jpg", url:"" } } }, get_feature: { layer: "", query: { isspatial: false, featurecoordsys: { id:0, string:"", datumtransformid:0, datumtransformstring:"" }, filtercoordsys: { id:0, string:"", datumtransformid:0, datumtransformstring:"" }, buffer:0, where:"", spatialfilter: { relation: "envelope_intersection", envelope: null } } }, environment: { separators: { cs:" ", ts:";" } }, layer: [], workspaces: [] }; return OpenLayers.Util.extend(this, defaults); }, CLASS_NAME: "OpenLayers.Format.ArcXML.Request" }); OpenLayers.Format.ArcXML.Response = OpenLayers.Class({ initialize: function(params) { var defaults = { image: { envelope:null, output:'' }, features: { featurecount: 0, envelope: null, feature: [] }, error:'' }; return OpenLayers.Util.extend(this, defaults); }, CLASS_NAME: "OpenLayers.Format.ArcXML.Response" });
import React, {Component} from 'react'; import { ScrollView, TouchableOpacity, StyleSheet, Image, Text, View, Platform, ScrolView } from 'react-native'; import {SharedElementTransition} from 'react-native-navigation'; import * as Animatable from 'react-native-animatable'; import * as setStyles from './styles'; const SHOW_DURATION = 400; const HIDE_DURATION = 300; export default class InfoScreen extends Component { static navigatorStyle = { ...setStyles.navigatorStyle, navBarHideOnScroll: false }; constructor(props) { super(props); this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent.bind(this)); this.state = { animationType: 'fadeInRight', animationDuration: SHOW_DURATION } } onNavigatorEvent(event) { if (event.id === 'backPress') { this.setState({ animationType: 'fadeOutRight', animationDuration: HIDE_DURATION }); this.props.navigator.pop(); } } render() { return ( <View style={styles.container}> {this._renderImage()} {this._renderContent()} </View> ); } _renderImage() { return ( <SharedElementTransition style={styles.imageContainer} sharedElementId={this.props.sharedImageId} showDuration={SHOW_DURATION} hideDuration={HIDE_DURATION} animateClipBounds={true} showInterpolation={ { type: 'linear', easing: 'FastOutSlowIn' } } hideInterpolation={ { type: 'linear', easing:'FastOutSlowIn' } } > <Image style={styles.image} source={require('../../../img/beach.jpg')} /> </SharedElementTransition> ); } _renderContent() { return ( <Animatable.View style={styles.content} duration={this.state.animationDuration} animation={this.state.animationType} useNativeDriver={true} > <Text style={styles.text}>Line 1</Text> <Text style={styles.text}>Line 2</Text> <Text style={styles.text}>Line 3</Text> <Text style={styles.text}>Line 4</Text> <Text style={styles.text}>Line 5</Text> <Text style={styles.text}>Line 6</Text> <Text style={styles.text}>Line 7</Text> <Text style={styles.text}>Line 8</Text> </Animatable.View> ); } } const styles = StyleSheet.create({ container: { flex: 1 }, content: { flex: 1, marginTop: 190, backgroundColor: 'white' }, imageContainer: { position: 'absolute', top: 0, left: 0, right: 0, }, image: { height: 190 }, text: { fontSize: 17, paddingVertical: 4, paddingLeft: 8 } });
import Vue from 'vue'; import component from '~/vue_shared/components/code_block.vue'; import mountComponent from '../../helpers/vue_mount_component_helper'; describe('Code Block', () => { const Component = Vue.extend(component); let vm; afterEach(() => { vm.$destroy(); }); it('renders a code block with the provided code', () => { const code = "Failure/Error: is_expected.to eq(3)\n\n expected: 3\n got: -1\n\n (compared using ==)\n./spec/test_spec.rb:12:in `block (4 levels) in \u003ctop (required)\u003e'"; vm = mountComponent(Component, { code, }); expect(vm.$el.querySelector('code').textContent).toEqual(code); }); it('escapes XSS injections', () => { const code = 'CCC&lt;img src=x onerror=alert(document.domain)&gt;'; vm = mountComponent(Component, { code, }); expect(vm.$el.querySelector('code').textContent).toEqual(code); }); });
/*! * numbro.js language configuration * language : Russian * locale : Ukraine * author : Anatoli Papirovski : https://github.com/apapirovski */ (function () { 'use strict'; var language = { langLocaleCode: 'ru-UA', delimiters: { thousands: ' ', decimal: ',' }, abbreviations: { thousand: 'тыс.', million: 'млн', billion: 'b', trillion: 't' }, ordinal: function () { // not ideal, but since in Russian it can taken on // different forms (masculine, feminine, neuter) // this is all we can do return '.'; }, currency: { symbol: '\u20B4', position: 'postfix' }, defaults: { currencyFormat: ',0000 a' }, formats: { fourDigits: '0000 a', fullWithTwoDecimals: ',0.00 $', fullWithTwoDecimalsNoCurrency: ',0.00', fullWithNoDecimals: ',0 $' } }; // Node if (typeof module !== 'undefined' && module.exports) { module.exports = language; } // Browser if (typeof window !== 'undefined' && window.numbro && window.numbro.language) { window.numbro.language(language.langLocaleCode, language); } }.call(typeof window === 'undefined' ? this : window));
'use strict'; 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; }; }(); var _three = require('three'); var THREE = _interopRequireWildcard(_three); var _ReactPropTypes = require('react/lib/ReactPropTypes'); var _ReactPropTypes2 = _interopRequireDefault(_ReactPropTypes); var _GeometryDescriptorBase = require('./GeometryDescriptorBase'); var _GeometryDescriptorBase2 = _interopRequireDefault(_GeometryDescriptorBase); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } 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 ParametricGeometryDescriptor = function (_GeometryDescriptorBa) { _inherits(ParametricGeometryDescriptor, _GeometryDescriptorBa); function ParametricGeometryDescriptor(react3Instance) { _classCallCheck(this, ParametricGeometryDescriptor); var _this = _possibleConstructorReturn(this, (ParametricGeometryDescriptor.__proto__ || Object.getPrototypeOf(ParametricGeometryDescriptor)).call(this, react3Instance)); ['slices', 'stacks'].forEach(function (propName) { _this.hasProp(propName, { type: _ReactPropTypes2.default.number.isRequired, update: _this.triggerRemount, default: undefined }); }); _this.hasProp('parametricFunction', { type: _ReactPropTypes2.default.func.isRequired, update: _this.triggerRemount, default: undefined }); return _this; } _createClass(ParametricGeometryDescriptor, [{ key: 'construct', value: function construct(props) { var parametricFunction = props.parametricFunction, slices = props.slices, stacks = props.stacks; return new THREE.ParametricGeometry(parametricFunction, slices, stacks); } }]); return ParametricGeometryDescriptor; }(_GeometryDescriptorBase2.default); module.exports = ParametricGeometryDescriptor;
cordova.define("org.apache.cordova.statusbar.statusbar", function(require, exports, module) {/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var argscheck = require('cordova/argscheck'), utils = require('cordova/utils'), exec = require('cordova/exec'); // prime it exec(null, null, "StatusBar", "_ready", []); var StatusBar = function() { }; StatusBar.overlaysWebView = function(doOverlay) { exec(null, null, "StatusBar", "overlaysWebView", [doOverlay]); }; StatusBar.styleDefault = function() { exec(null, null, "StatusBar", "styleDefault", []); }; StatusBar.styleLightContent = function() { exec(null, null, "StatusBar", "styleLightContent", []); }; StatusBar.styleBlackTranslucent = function() { exec(null, null, "StatusBar", "styleBlackTranslucent", []); }; StatusBar.styleBlackOpaque = function() { exec(null, null, "StatusBar", "styleBlackOpaque", []); }; StatusBar.backgroundColorByName = function(colorname) { exec(null, null, "StatusBar", "backgroundColorByName", [colorname]); } StatusBar.backgroundColorByHexString = function(hexString) { exec(null, null, "StatusBar", "backgroundColorByHexString", [hexString]); } StatusBar.hide = function() { exec(null, null, "StatusBar", "hide", []); } StatusBar.show = function() { exec(null, null, "StatusBar", "show", []); } StatusBar.isVisible = true; module.exports = StatusBar; });
var version = require("vtree/version") module.exports = isVirtualPatch function isVirtualPatch(x) { return x && x.type === "VirtualPatch" && x.version === version }
/** * @name Filter BandPass * @description Apply a p5.BandPass filter to white noise. * Visualize the sound with FFT. * Map mouseX to the bandpass frequency * and mouseY to resonance/width of the a BandPass filter * * <p><em><span class="small"> To run this example locally, you will need the * <a href="http://p5js.org/reference/#/libraries/p5.sound">p5.sound library</a> * a sound file, and a running <a href="https://github.com/processing/p5.js/wiki/Local-server">local server</a>.</span></em></p> */ var noise; var fft; var filter, filterFreq, filterWidth; function setup() { createCanvas(710, 256); fill(255, 40, 255); filter = new p5.BandPass(); noise = new p5.Noise(); noise.disconnect(); // Disconnect soundfile from master output... filter.process(noise); // ...and connect to filter so we'll only hear BandPass. noise.start(); fft = new p5.FFT(); } function draw() { background(30); // Map mouseX to a bandpass freq from the FFT spectrum range: 10Hz - 22050Hz filterFreq = map (mouseX, 0, width, 10, 22050); // Map mouseY to resonance/width filterWidth = map(mouseY, 0, height, 0, 90); // set filter parameters filter.set(filterFreq, filterWidth); // Draw every value in the FFT spectrum analysis where // x = lowest (10Hz) to highest (22050Hz) frequencies, // h = energy / amplitude at that frequency var spectrum = fft.analyze(); noStroke(); for (var i = 0; i< spectrum.length; i++){ var x = map(i, 0, spectrum.length, 0, width); var h = -height + map(spectrum[i], 0, 255, height, 0); rect(x, height, width/spectrum.length, h) ; } }
YUI.add('gallery-y64', function(Y) { /*global YUI*/ var Base64 = Y.Base64; /* * Copyright (c) 2009 Nicholas C. Zakas. All rights reserved. * http://www.nczonline.net/ */ /** * Y64 encoder/decoder * @module gallery-y64 */ /** * Y64 encoder/decoder * @class Y64 * @static */ Y.Y64 = { /** * Y64-decodes a string of text. * @param {String} text The text to decode. * @return {String} The Y64-decoded string. */ decode: function(text){ //ignore white space text = text.replace(/\s/g,""); //first check for any unexpected input if(!(/^[a-z0-9\._\s]+\-{0,2}$/i.test(text)) || text.length % 4 > 0){ throw new Error("Not a Y64-encoded string."); } //change to base64 format text = text.replace(/[\._\-]/g, function(match){ switch(match){ case ".": return "+"; case "-": return "="; case "_": return "/"; } }); //decode it return Base64.decode(text); }, /** * Y64-encodes a string of text. * @param {String} text The text to encode. * @return {String} The Y64-encoded string. */ encode: function(text){ if (/([^\u0000-\u00ff])/.test(text)){ throw new Error("Can't Y64 encode non-ASCII characters."); } //first, base64 encode var output = Base64.encode(text); //then, replace the appropriate characters output = output.replace(/[\+=\/]/g, function(match){ switch(match){ case "+": return "."; case "=": return "-"; case "/": return "_"; } }); return output; } }; }, 'gallery-2010.06.16-19-51' ,{requires:['gallery-base64']});
function multiUrlPickerController($scope, angularHelper, localizationService, entityResource, iconHelper, editorService) { var vm = { labels: { general_recycleBin: "" } }; $scope.renderModel = []; if ($scope.preview) { return; } if (!Array.isArray($scope.model.value)) { $scope.model.value = []; } var currentForm = angularHelper.getCurrentForm($scope); $scope.sortableOptions = { axis: "y", containment: "parent", distance: 10, opacity: 0.7, tolerance: "pointer", scroll: true, zIndex: 6000, update: function () { currentForm.$setDirty(); } }; $scope.model.value.forEach(function (link) { link.icon = iconHelper.convertFromLegacyIcon(link.icon); $scope.renderModel.push(link); }); $scope.$on("formSubmitting", function () { $scope.model.value = $scope.renderModel; }); $scope.$watch( function () { return $scope.renderModel.length; }, function () { //Validate! if ($scope.model.config && $scope.model.config.minNumber && parseInt($scope.model.config.minNumber) > $scope.renderModel.length) { $scope.multiUrlPickerForm.minCount.$setValidity("minCount", false); } else { $scope.multiUrlPickerForm.minCount.$setValidity("minCount", true); } if ($scope.model.config && $scope.model.config.maxNumber && parseInt($scope.model.config.maxNumber) < $scope.renderModel.length) { $scope.multiUrlPickerForm.maxCount.$setValidity("maxCount", false); } else { $scope.multiUrlPickerForm.maxCount.$setValidity("maxCount", true); } $scope.sortableOptions.disabled = $scope.renderModel.length === 1; } ); $scope.remove = function ($index) { $scope.renderModel.splice($index, 1); currentForm.$setDirty(); }; $scope.openLinkPicker = function (link, $index) { var target = link ? { name: link.name, anchor: link.queryString, udi: link.udi, url: link.url, target: link.target } : null; var linkPicker = { currentTarget: target, dataTypeKey: $scope.model.dataTypeKey, ignoreUserStartNodes : ($scope.model.config && $scope.model.config.ignoreUserStartNodes) ? $scope.model.config.ignoreUserStartNodes : "0", hideAnchor: $scope.model.config && $scope.model.config.hideAnchor ? true : false, submit: function (model) { if (model.target.url || model.target.anchor) { // if an anchor exists, check that it is appropriately prefixed if (model.target.anchor && model.target.anchor[0] !== '?' && model.target.anchor[0] !== '#') { model.target.anchor = (model.target.anchor.indexOf('=') === -1 ? '#' : '?') + model.target.anchor; } if (link) { link.udi = model.target.udi; link.name = model.target.name || model.target.url || model.target.anchor; link.queryString = model.target.anchor; link.target = model.target.target; link.url = model.target.url; } else { link = { name: model.target.name || model.target.url || model.target.anchor, queryString: model.target.anchor, target: model.target.target, udi: model.target.udi, url: model.target.url }; $scope.renderModel.push(link); } if (link.udi) { var entityType = model.target.isMedia ? "Media" : "Document"; entityResource.getById(link.udi, entityType).then(function (data) { link.icon = iconHelper.convertFromLegacyIcon(data.icon); link.published = (data.metaData && data.metaData.IsPublished === false && entityType === "Document") ? false : true; link.trashed = data.trashed; if (link.trashed) { item.url = vm.labels.general_recycleBin; } }); } else { link.icon = "icon-link"; link.published = true; } currentForm.$setDirty(); } editorService.close(); }, close: function () { editorService.close(); } }; editorService.linkPicker(linkPicker); }; function init() { localizationService.localizeMany(["general_recycleBin"]) .then(function (data) { vm.labels.general_recycleBin = data[0]; }); // if the property is mandatory, set the minCount config to 1 (unless of course it is set to something already), // that way the minCount/maxCount validation handles the mandatory as well if ($scope.model.validation && $scope.model.validation.mandatory && !$scope.model.config.minNumber) { $scope.model.config.minNumber = 1; } _.each($scope.model.value, function (item){ // we must reload the "document" link URLs to match the current editor culture if (item.udi && item.udi.indexOf("/document/") > 0) { item.url = null; entityResource.getUrlByUdi(item.udi).then(function (data) { item.url = data; }); } }); } init(); } angular.module("umbraco").controller("Umbraco.PropertyEditors.MultiUrlPickerController", multiUrlPickerController);
describe('[Regression](GH-2153)', function () { it('Shadow element should not appear in user event handler', function () { return runTests('testcafe-fixtures/index.js'); }); });
function x () { global.answer = 'x'; } function y () { global.answer = 'y'; } export default Math.random() < 0.5 ? x : y;
const udp = require('dgram'); const dns = require('dns'); const Constants = require('../../util/Constants'); const EventEmitter = require('events').EventEmitter; class VoiceConnectionUDPClient extends EventEmitter { constructor(voiceConnection, data) { super(); this.voiceConnection = voiceConnection; this.count = 0; this.data = data; this.dnsLookup(); } dnsLookup() { dns.lookup(this.voiceConnection.endpoint, (err, address) => { if (err) { this.emit('error', err); return; } this.connectUDP(address); }); } send(packet) { if (this.udpSocket) { try { this.udpSocket.send(packet, 0, packet.length, this.data.port, this.udpIP); } catch (err) { this.emit('error', err); } } } _shutdown() { if (this.udpSocket) { try { this.udpSocket.close(); } catch (err) { if (err.message !== 'Not running') this.emit('error', err); } this.udpSocket = null; } } connectUDP(address) { this.udpIP = address; this.udpSocket = udp.createSocket('udp4'); // finding local IP // https://discordapp.com/developers/docs/topics/voice-connections#ip-discovery this.udpSocket.once('message', message => { const packet = new Buffer(message); this.localIP = ''; for (let i = 4; i < packet.indexOf(0, i); i++) this.localIP += String.fromCharCode(packet[i]); this.localPort = parseInt(packet.readUIntLE(packet.length - 2, 2).toString(10), 10); this.voiceConnection.websocket.send({ op: Constants.VoiceOPCodes.SELECT_PROTOCOL, d: { protocol: 'udp', data: { address: this.localIP, port: this.localPort, mode: 'xsalsa20_poly1305', }, }, }); }); this.udpSocket.on('error', (error, message) => { this.emit('error', { error, message }); }); this.udpSocket.on('close', error => { this.emit('close', error); }); const blankMessage = new Buffer(70); blankMessage.writeUIntBE(this.data.ssrc, 0, 4); this.send(blankMessage); } } module.exports = VoiceConnectionUDPClient;
var pv = require("bio-pv"); var viewer = pv.Viewer(document.getElementById('hereGoesTheViewer'), { quality: 'medium', width: 'auto', height: 'auto', antialias: true, outline: true, slabMode: 'auto' }); function load(name, pdbId) { pv.io.fetchPdb('../pdbs/' + pdbId + '.pdb', function(structure) { // render everything as helix/sheet/coil cartoon, coloring by secondary // structure succession var go = viewer.cartoon('structure', structure, { color: pv.color.ssSuccession(), showRelated: '1', }); // find camera orientation such that the molecules biggest extents are // aligned to the screen plane. var rotation = pv.viewpoint.principalAxes(go); viewer.setRotation(rotation) // adapt zoom level to contain the whole structure viewer.autoZoom(); }); } // load default load('kinase', '1ake'); // tell viewer to resize when window size changes. window.onresize = function(event) { viewer.fitParent(); }
(function ($) { $.fn.countdown = function (options) { var settings = $.extend({ endDateTime: new Date() }, options); return this.each(function () { var timeoutInterval = null; var container = $(this); settings.endDateTime = new Date(container.data("countdown")) updateCounter(); getCountDown(); function getCountDown() { clearTimeout(timeoutInterval); timeoutInterval = setTimeout(function () { updateCounter(); }, 1000); } function getCurrentCountDown() { var currentDateTime = new Date(); var diff = parseFloat(settings.endDateTime - currentDateTime); var seconds = 0; var minutes = 0; var hours = 0; var total = parseFloat(((((diff / 1000.0) / 60.0) / 60.0) / 24.0)); var days = parseInt(total); total -= days; total *= 24.0; hours = parseInt(total); total -= hours; total *= 60.0; minutes = parseInt(total); total -= minutes; total *= 60; seconds = parseInt(total); return { days: formatNumber(Math.max(0, days), true), hours: formatNumber(Math.max(0, hours), false), minutes: formatNumber(Math.max(0, minutes), false), seconds: formatNumber(Math.max(0, seconds), false) }; } function updateCounter() { var countDown = getCurrentCountDown(); var days = container.find(".days .countdown-time").first(); var hours = container.find(".hours .countdown-time").first(); var minutes = container.find(".minutes .countdown-time").first(); var seconds = container.find(".seconds .countdown-time").first(); var dayVal = days.html(); var hourVal = hours.html(); var minuteVal = minutes.html(); var secondVal = seconds.html(); if (countDown.days == 0) { days.parent().addClass("zero"); } if (countDown.hours == 0) { hours.parent().addClass("zero"); } if (countDown.minutes == 0) { minutes.parent().addClass("zero"); } if (countDown.seconds == 0) { seconds.parent().addClass("zero"); } if (dayVal != countDown.days) { days.html(countDown.days); } if (hourVal != countDown.hours) { hours.html(countDown.hours); } if (minuteVal != countDown.minutes) { minutes.html(countDown.minutes); } if (secondVal != countDown.seconds) { seconds.html(countDown.seconds); } getCountDown(); } function formatNumber(number, isday) { var strNumber = number.toString(); return strNumber; } }); } })(jQuery);
/* version: 0.3.151, born: 25-2-2014 23:32 */ var Organic = (function(w){ var o = { helpers: {}, lib: { atoms: {}, molecules: {} } } var require = function(v) { if(v == "./helpers/extend") { return o.helpers.extend; } else if(v == "/helpers/snippets" || v == "../../helpers/snippets") { return o.helpers.snippets; } else if(v == "/lib/atoms/atoms" || v == "../../lib/atoms/atoms" || v == "../atoms/atoms.js") { return o.lib.atoms.atoms; } else if(v == "../../helpers/units") { return o.helpers.units; } else if(v == "../../helpers/args") { return o.helpers.args; } else if(v == "path") { return { basename: function(f) { return f.split("/").pop(); } } } else { var moduleParts = v.split("/"); return (function getModule(currentModule) { var part = moduleParts.shift().replace(".js", ""); if(currentModule[part]) { if(moduleParts.length == 0) { return currentModule[part]; } else { return getModule(currentModule[part]) } } })(o); } } var __dirname = ''; var walkClientSide = function(res, obj, path) { if(typeof res == 'undefined') res = []; if(typeof obj == 'undefined') obj = o.lib; if(typeof path == 'undefined') path = "lib/"; for(var part in obj) { if(typeof obj[part] == 'function') { res.push(path + part + ".js"); } else { walkClientSide(res, obj[part], path + part + "/"); } } return res; };o.helpers.args = function(value) { value = value.toString().replace(/\/ /g, '/').split('/'); return value; } o.helpers.extend = function() { var process = function(destination, source) { for (var key in source) { if (hasOwnProperty.call(source, key)) { destination[key] = source[key]; } } return destination; }; var result = arguments[0]; for(var i=1; i<arguments.length; i++) { result = process(result, arguments[i]); } return result; } o.helpers.snippets = function() { // http://peters-playground.com/Emmet-Css-Snippets-for-Sublime-Text-2/ return { // Visual Formatting "pos": "position", "pos:s": "position:static", "pos:a": "position:absolute", "pos:r": "position:relative", "pos:f": "position:fixed", // "top": "top", "t:a": "top:auto", "rig": "right", "r:a": "right:auto", "bot": "bottom", // "b:a": "bottom:auto", // breaks the multiple comma selectors "lef": "left", "l:a": "left:auto", "zin": "z-index", "z:a": "z-index:auto", "fl": "float", "fl:n": "float:none", "fl:l": "float:left", "fl:r": "float:right", "cl": "clear", "cl:n": "clear:none", "cl:l": "clear:left", "cl:r": "clear:right", "cl:b": "clear:both", "dis": "display", "d:n": "display:none", "d:b": "display:block", "d:i": "display:inline", "d:ib": "display:inline-block", "d:li": "display:list-item", "d:ri": "display:run-in", "d:cp": "display:compact", "d:tb": "display:table", "d:itb": "display:inline-table", "d:tbcp": "display:table-caption", "d:tbcl": "display:table-column", "d:tbclg": "display:table-column-group", "d:tbhg": "display:table-header-group", "d:tbfg": "display:table-footer-group", "d:tbr": "display:table-row", "d:tbrg": "display:table-row-group", "d:tbc": "display:table-cell", "d:rb": "display:ruby", "d:rbb": "display:ruby-base", "d:rbbg": "display:ruby-base-group", "d:rbt": "display:ruby-text", "d:rbtg": "display:ruby-text-group", "vis": "visibility", "v:v": "visibility:visible", "v:h": "visibility:hidden", "v:c": "visibility:collapse", "ov": "overflow", "ov:v": "overflow:visible", "ov:h": "overflow:hidden", "ov:s": "overflow:scroll", "ov:a": "overflow:auto", "ovx": "overflow-x", "ovx:v": "overflow-x:visible", "ovx:h": "overflow-x:hidden", "ovx:s": "overflow-x:scroll", "ovx:a": "overflow-x:auto", "ovy": "overflow-y", "ovy:v": "overflow-y:visible", "ovy:h": "overflow-y:hidden", "ovy:s": "overflow-y:scroll", "ovy:a": "overflow-y:auto", "ovs": "overflow-style", "ovs:a": "overflow-style:auto", "ovs:s": "overflow-style:scrollbar", "ovs:p": "overflow-style:panner", "ovs:m": "overflow-style:move", "ovs:mq": "overflow-style:marquee", "zoo": "zoom:1", "cp": "clip", "cp:a": "clip:auto", "cp:r": "clip:rect()", "rz": "resize", "rz:n": "resize:none", "rz:b": "resize:both", "rz:h": "resize:horizontal", "rz:v": "resize:vertical", "cur": "cursor", "cur:a": "cursor:auto", "cur:d": "cursor:default", "cur:c": "cursor:crosshair", "cur:ha": "cursor:hand", "cur:he": "cursor:help", "cur:m": "cursor:move", "cur:p": "cursor:pointer", "cur:t": "cursor:text", // Margin & Padding "mar": "margin", "m:au": "margin:0 auto", "mt": "margin-top", "mt:a": "margin-top:auto", "mr": "margin-right", "mr:a": "margin-right:auto", "mb": "margin-bottom", "mb:a": "margin-bottom:auto", "ml": "margin-left", "ml:a": "margin-left:auto", "pad": "padding", "pt": "padding-top", "pr": "padding-right", "pb": "padding-bottom", "pl": "padding-left", // Box Sizing "bxz": "box-sizing", "bxz:cb": "box-sizing:content-box", "bxz:bb": "box-sizing:border-box", "bxsh": "box-shadow", "bxsh:n": "box-shadow:none", "bxsh+": "box-shadow:0 0 0 #000", "wid": "width", "w:a": "width:auto", "hei": "height", "h:a": "height:auto", "maw": "max-width", "maw:n": "max-width:none", "mah": "max-height", "mah:n": "max-height:none", "miw": "min-width", "mih": "min-height", // Font "fon": "font", "fon+": "font:1em Arial, sans-serif", "fw": "font-weight", "fw:n": "font-weight:normal", "fw:b": "font-weight:bold", "fw:br": "font-weight:bolder", "fw:lr": "font-weight:lighter", "fs": "font-style", "fs:n": "font-style:normal", "fs:i": "font-style:italic", "fs:o": "font-style:oblique", "fv": "font-variant", "fv:n": "font-variant:normal", "fv:sc": "font-variant:small-caps", "fz": "font-size", "fza": "font-size-adjust", "fza:n": "font-size-adjust:none", "ff": "font-family", "ff:s": "font-family:serif", "ff:ss": "font-family:sans-serif", "ff:c": "font-family:cursive", "ff:f": "font-family:fantasy", "ff:m": "font-family:monospace", "fef": "font-effect", "fef:n": "font-effect:none", "fef:eg": "font-effect:engrave", "fef:eb": "font-effect:emboss", "fef:o": "font-effect:outline", "fem": "font-emphasize", "femp": "font-emphasize-position", "femp:b": "font-emphasize-position:before", "femp:a": "font-emphasize-position:after", "fems": "font-emphasize-style", "fems:n": "font-emphasize-style:none", "fems:ac": "font-emphasize-style:accent", "fems:dt": "font-emphasize-style:dot", "fems:c": "font-emphasize-style:circle", "fems:ds": "font-emphasize-style:disc", "fsm": "font-smooth", "fsm:au": "font-smooth:auto", "fsm:n": "font-smooth:never", "fsm:al": "font-smooth:always", "fst": "font-stretch", "fst:n": "font-stretch:normal", "fst:uc": "font-stretch:ultra-condensed", "fst:ec": "font-stretch:extra-condensed", "fst:c": "font-stretch:condensed", "fst:sc": "font-stretch:semi-condensed", "fst:se": "font-stretch:semi-expanded", "fst:e": "font-stretch:expanded", "fst:ee": "font-stretch:extra-expanded", "fst:ue": "font-stretch:ultra-expanded", // Text "va": "vertical-align", "va:sup": "vertical-align:super", "va:t": "vertical-align:top", "va:tt": "vertical-align:text-top", "va:m": "vertical-align:middle", "va:bl": "vertical-align:baseline", "va:b": "vertical-align:bottom", "va:tb": "vertical-align:text-bottom", "va:sub": "vertical-align:sub", "ta": "text-align", "ta:le": "text-align:left", "ta:c": "text-align:center", "ta:r": "text-align:right", "ta:j": "text-align:justify", "tal": "text-align-last", "tal:a": "text-align-last:auto", "tal:l": "text-align-last:left", "tal:c": "text-align-last:center", "tal:r": "text-align-last:right", "ted": "text-decoration", "ted:n": "text-decoration:none", "ted:u": "text-decoration:underline", "ted:o": "text-decoration:overline", "ted:l": "text-decoration:line-through", "te": "text-emphasis", "te:n": "text-emphasis:none", "te:ac": "text-emphasis:accent", "te:dt": "text-emphasis:dot", "te:c": "text-emphasis:circle", "te:ds": "text-emphasis:disc", "te:b": "text-emphasis:before", "te:a": "text-emphasis:after", "teh": "text-height", "teh:a": "text-height:auto", "teh:f": "text-height:font-size", "teh:t": "text-height:text-size", "teh:m": "text-height:max-size", "ti": "text-indent", "ti:-": "text-indent:-9999px", "tj": "text-justify", "tj:a": "text-justify:auto", "tj:iw": "text-justify:inter-word", "tj:ii": "text-justify:inter-ideograph", "tj:ic": "text-justify:inter-cluster", "tj:d": "text-justify:distribute", "tj:k": "text-justify:kashida", "tj:t": "text-justify:tibetan", "tol": "text-outline", "tol+": "text-outline:0 0 #000", "tol:n": "text-outline:none", "tr": "text-replace", "tr:n": "text-replace:none", "tt": "text-transform", "tt:n": "text-transform:none", "tt:c": "text-transform:capitalize", "tt:u": "text-transform:uppercase", "tt:l": "text-transform:lowercase", "tw": "text-wrap", "tw:n": "text-wrap:normal", "tw:no": "text-wrap:none", "tw:u": "text-wrap:unrestricted", "tw:s": "text-wrap:suppress", "tsh": "text-shadow", "tsh+": "text-shadow:0 0 0 #000", "tsh:n": "text-shadow:none", "lh": "line-height", "lts": "letter-spacing", "whs": "white-space", "whs:n": "white-space:normal", "whs:p": "white-space:pre", "whs:nw": "white-space:nowrap", "whs:pw": "white-space:pre-wrap", "whs:pl": "white-space:pre-line", "whsc": "white-space-collapse", "whsc:n": "white-space-collapse:normal", "whsc:k": "white-space-collapse:keep-all", "whsc:l": "white-space-collapse:loose", "whsc:bs": "white-space-collapse:break-strict", "whsc:ba": "white-space-collapse:break-all", "wob": "word-break", "wob:n": "word-break:normal", "wob:k": "word-break:keep-all", "wob:l": "word-break:loose", "wob:bs": "word-break:break-strict", "wob:ba": "word-break:break-all", "wos": "word-spacing", "wow": "word-wrap", "wow:nm": "word-wrap:normal", "wow:n": "word-wrap:none", "wow:u": "word-wrap:unrestricted", "wow:s": "word-wrap:suppress", // Background "bg": "background", "bg+": "background:#fff url() 0 0 no-repeat", "bg:n": "background:none", "bgc": "background-color:#fff", "bgc:t": "background-color:transparent", "bgi": "background-image:url()", "bgi:n": "background-image:none", "bgr": "background-repeat", "bgr:r": "background-repeat:repeat", "bgr:n": "background-repeat:no-repeat", "bgr:x": "background-repeat:repeat-x", "bgr:y": "background-repeat:repeat-y", "bga": "background-attachment", "bga:f": "background-attachment:fixed", "bga:s": "background-attachment:scroll", "bgp": "background-position:0 0", "bgpx": "background-position-x", "bgpy": "background-position-y", "bgbk": "background-break", "bgbk:bb": "background-break:bounding-box", "bgbk:eb": "background-break:each-box", "bgbk:c": "background-break:continuous", "bgcp": "background-clip", "bgcp:bb": "background-clip:border-box", "bgcp:pb": "background-clip:padding-box", "bgcp:cb": "background-clip:content-box", "bgcp:nc": "background-clip:no-clip", "bgo": "background-origin", "bgo:pb": "background-origin:padding-box", "bgo:bb": "background-origin:border-box", "bgo:cb": "background-origin:content-box", "bgz": "background-size", "bgz:a": "background-size:auto", "bgz:ct": "background-size:contain", "bgz:cv": "background-size:cover", // Color "col": "color:#000", "op": "opacity", "hsl": "hsl(359,100%,100%)", "hsla": "hsla(359,100%,100%,0.5)", "rgb": "rgb(255,255,255)", "rgba": "rgba(255,255,255,0.5)", // Generated Content "ct": "content", "ct:n": "content:normal", "ct:oq": "content:open-quote", "ct:noq": "content:no-open-quote", "ct:cq": "content:close-quote", "ct:ncq": "content:no-close-quote", "ct:a": "content:attr()", "ct:c": "content:counter()", "ct:cs": "content:counters()", "quo": "quotes", "q:n": "quotes:none", "q:ru": "quotes:'\00AB' '\00BB' '\201E' '\201C'", "q:en": "quotes:'\201C' '\201D' '\2018' '\2019'", "coi": "counter-increment", "cor": "counter-reset", // Outline "out": "outline", "o:n": "outline:none", "oo": "outline-offset", "ow": "outline-width", "os": "outline-style", "oc": "outline-color:#000", "oc:i": "outline-color:invert", // Table "tbl": "table-layout", "tbl:a": "table-layout:auto", "tbl:f": "table-layout:fixed", "cps": "caption-side", "cps:t": "caption-side:top", "cps:b": "caption-side:bottom", "ec": "empty-cells", "ec:s": "empty-cells:show", "ec:h": "empty-cells:hide", // Border "bd": "border", "bd+": "border:1px solid #000", "bd:n": "border:none", "bdbk": "border-break", "bdbk:c": "border-break:close", "bdcl": "border-collapse", "bdcl:c": "border-collapse:collapse", "bdcl:s": "border-collapse:separate", "bdc": "border-color:#000", "bdi": "border-image:url()", "bdi:n": "border-image:none", "bdti": "border-top-image:url()", "bdti:n": "border-top-image:none", "bdri": "border-right-image:url()", "bdri:n": "border-right-image:none", "bdbi": "border-bottom-image:url()", "bdbi:n": "border-bottom-image:none", "bdli": "border-left-image:url()", "bdli:n": "border-left-image:none", "bdci": "border-corner-image:url()", "bdci:n": "border-corner-image:none", "bdci:c": "border-corner-image:continue", "bdtli": "border-top-left-image:url()", "bdtli:n": "border-top-left-image:none", "bdtli:c": "border-top-left-image:continue", "bdtri": "border-top-right-image:url()", "bdtri:n": "border-top-right-image:none", "bdtri:c": "border-top-right-image:continue", "bdbri": "border-bottom-right-image:url()", "bdbri:n": "border-bottom-right-image:none", "bdbri:c": "border-bottom-right-image:continue", "bdbli": "border-bottom-left-image:url()", "bdbli:n": "border-bottom-left-image:none", "bdbli:c": "border-bottom-left-image:continue", "bdf": "border-fit", "bdf:c": "border-fit:clip", "bdf:r": "border-fit:repeat", "bdf:sc": "border-fit:scale", "bdf:st": "border-fit:stretch", "bdf:ow": "border-fit:overwrite", "bdf:of": "border-fit:overflow", "bdf:sp": "border-fit:space", "bdlt": "border-length", "bdlt:a": "border-length:auto", "bdsp": "border-spacing", "bds": "border-style", "bds:n": "border-style:none", "bds:h": "border-style:hidden", "bds:dt": "border-style:dotted", "bds:ds": "border-style:dashed", "bds:s": "border-style:solid", "bds:db": "border-style:double", "bds:dd": "border-style:dot-dash", "bds:ddd": "border-style:dot-dot-dash", "bds:w": "border-style:wave", "bds:g": "border-style:groove", "bds:r": "border-style:ridge", "bds:i": "border-style:inset", "bds:o": "border-style:outset", "bdw": "border-width", "bdt": "border-top", "bdt+": "border-top:1px solid #000", "bdt:n": "border-top:none", "bdtw": "border-top-width", "bdts": "border-top-style", "bdts:n": "border-top-style:none", "bdtc": "border-top-color:#000", "bdr": "border-right", "bdr+": "border-right:1px solid #000", "bdr:n": "border-right:none", "bdrw": "border-right-width", "bdrs": "border-right-style", "bdrs:n": "border-right-style:none", "bdrc": "border-right-color:#000", "bdb": "border-bottom", "bdb+": "border-bottom:1px solid #000", "bdb:n": "border-bottom:none", "bdbw": "border-bottom-width", "bdbs": "border-bottom-style", "bdbs:n": "border-bottom-style:none", "bdbc": "border-bottom-color:#000", "bdl": "border-left", "bdl+": "border-left:1px solid #000", "bdl:n": "border-left:none", "bdlw": "border-left-width", "bdls": "border-left-style", "bdls:n": "border-left-style:none", "bdlc": "border-left-color:#000", "bdrsa": "border-radius", "bdtrrs": "border-top-right-radius", "bdtlrs": "border-top-left-radius", "bdbrrs": "border-bottom-right-radius", "bdblrs": "border-bottom-left-radius", // Lists "lis": "list-style", "lis:n": "list-style:none", "lisp": "list-style-position", "lisp:i": "list-style-position:inside", "lisp:o": "list-style-position:outside", "list": "list-style-type", "list:n": "list-style-type:none", "list:d": "list-style-type:disc", "list:c": "list-style-type:circle", "list:s": "list-style-type:square", "list:dc": "list-style-type:decimal", "list:dclz": "list-style-type:decimal-leading-zero", "list:lr": "list-style-type:lower-roman", "list:ur": "list-style-type:upper-roman", "lisi": "list-style-image", "lisi:n": "list-style-image:none", // Print "pgbb": "page-break-before", "pgbb:au": "page-break-before:auto", "pgbb:al": "page-break-before:always", "pgbb:l": "page-break-before:left", "pgbb:r": "page-break-before:right", "pgbi": "page-break-inside", "pgbi:au": "page-break-inside:auto", "pgbi:av": "page-break-inside:avoid", "pgba": "page-break-after", "pgba:au": "page-break-after:auto", "pgba:al": "page-break-after:always", "pgba:l": "page-break-after:left", "pgba:r": "page-break-after:right", "orp": "orphans", "widows": "widows", // Others "ipt": "!important", "ffa": "@font-family {<br>&nbsp;&nbsp;font-family:;<br>&nbsp;&nbsp;src:url();<br>}", "ffa+": "@font-family {<br>&nbsp;&nbsp;font-family: 'FontName';<br>&nbsp;&nbsp;src: url('FileName.eot');<br>&nbsp;&nbsp;src: url('FileName.eot?#iefix') format('embedded-opentype'),<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;url('FileName.woff') format('woff'),<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;url('FileName.ttf') format('truetype'),<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;url('FileName.svg#FontName') format('svg');<br>&nbsp;&nbsp;font-style: normal;<br>&nbsp;&nbsp;font-weight: normal;<br>}", "imp": "@import url()", "mp": "@media print {}", "bg:ie": "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='x.png',sizingMethod='crop')", "op:ie": "filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=100)", "op:ms": "-ms-filter:'progid:DXImageTransform.Microsoft.Alpha(Opacity=100)'", "trf": "transform", "trf:r": "transform:rotate(90deg)", "trf:sc": "transform:scale(x,y)", "trf:scx": "transform:scaleX(x)", "trf:scy": "transform:scaleY(y)", "trf:skx": "transform:skewX(90deg)", "trf:sky": "transform:skewY(90deg)", "trf:t": "transform:translate(x,y)", "trf:tx": "transform:translateX(x)", "trf:ty": "transform:translateY(y)", "trs": "transition", "trsde": "transition-delay", "trsdu": "transition-duration", "trsp": "transition-property", "trstf": "transition-timing-function", "ani": "animation", "ann": "animation-name", "adu": "animation-duration", "atf": "animation-timing-function", "ade": "animation-delay", "aic": "animation-iteration-count", "adi": "animation-direction", "aps": "animation-play-state", "key": "@keyframes {}", "ms": "@media screen and () {}", "in": "inherit", "tra": "transparent", "beh": "behavior:url()", "cha": "@charset''", // Pseudo Class "ac": " :active{}", "ac:a": "&:active{}", "af": " :after{}", "af:a": "&:after{}", "be": " :before{}", "be:a": "&:before{}", "ch": " :checked{}", "ch:a": "&:checked{}", "dsa": " :disabled{}<i>[da]</i>", "dsa:a": "&:disabled{}<i>[da:a]</i>", "en": " :enabled{}", "en:a": "&:enabled{}", "fc": " :first-child{}", "fc:a": "&:first-child{}", "fle": " :first-letter{}", "fle:a": "&:first-letter{}", "fli": " :first-line{}", "fli:a": "&:first-line{}", "foc": " :focus{}", "foc:a": "&:focus{}", "ho": " :hover{}", "ho:a": "&:hover{}", "ln": " :lang(){}", "ln:a": "&:lang(){}", "lc": " :last-child{}", "lc:a": "&:last-child{}", // "li": " :link{}", // "li:a": "&:link{}", "nc": " :nth-child(){}", "nc:a": "&:nth-child(){}", "vit": " :visited{}", "vit:a": "&:visited{}", "tgt": " :target{}", "tgt:a": "&:target{}", "fot": " :first-of-type{}", "fot:a": "&:first-of-type{}", "lot": " :last-of-type{}", "lot:a": "&:last-of-type{}", "not": " :nth-of-type(){}", "not:a": "&:nth-of-type(){}", // Scss & Sass "ext": "@extend", "inc": "@include", "mix": "@mixin", "ieh": "ie-hex-str()" }; } o.helpers.units = function(v, def) { if(!v.toString().match(/[%|in|cm|mm|em|ex|pt|pc|px|deg|ms|s]/)) return v + (def || '%'); else return v; } var extend = require("./helpers/extend"), fs = require('fs'), path = require('path') var walk = function(dir) { return walkClientSide(); var results = []; var list = fs.readdirSync(dir); for(var i=0; i<list.length; i++) { var file = dir + '/' + list[i]; var stat = fs.statSync(file); if (stat && stat.isDirectory()) { results = results.concat(walk(file)); } else { results.push(file); } } return results; }; o.index = { absurd: null, init: function(decoration) { if(typeof decoration != 'undefined') { this.absurd = decoration; } // getting atoms and molecules var files = walk(__dirname + "/lib/"), self = this; for(var i=0; i<files.length; i++) { var file = path.basename(files[i]); (function(m) { var module = require(m); self.absurd.plugin(file.replace(".js", ""), function(absurd, value) { return module(value); }); })(files[i]); } // converting snippets to plugins var snippets = require(__dirname + "/helpers/snippets")(); for(var atom in snippets) { atom = atom.split(":"); (function(pluginName) { self.absurd.plugin(pluginName, function(absurd, value, prefixes) { if(prefixes === false) { prefixes = ''; } var s, r = {}; if(s = snippets[pluginName + ':' + value]) { s = s.split(':'); r[prefixes + s[0]] = s[1] || ''; } else if(s = snippets[pluginName]){ r[prefixes + s] = value; } return r; }); })(atom.shift()); } return this; } } o.lib.atoms.atoms = function(value) { var toObj = function(value, r) { value = value.replace(/( )?:( )?/, ':').split(':'); r = r || {}; r[value[0]] = value[1] || ''; return r; } var processArr = function(value) { var r = {}; for(var i=0; i<value.length; i++) { toObj(value[i], r); } return r; } if(typeof value == 'string') { return processArr(value.replace(/( )?\/( )?/g, '/').split('/')); } else if(typeof value == 'object') { if(!(value instanceof Array)) { return value; } else { return processArr(value); } } } /*! Animate.css - http://daneden.me/animate Licensed under the MIT license Copyright (c) 2013 Daniel Eden 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. */ o.lib.molecules.animate = function(value) { var r = {}; r['-wmso-animation-name'] = ''; r['-wmso-animation-duration'] = '1s', name = ''; if(typeof value === 'string') { r['-wmso-animation-name'] = value; } else if(typeof value === 'object') { if(value instanceof Array) { if(value.length === 1) { r['-wmso-animation-name'] = value[0]; } else if(value.length === 2) { r = { keyframes: { name: value[0], frames: value[1] } }; } else { value = r = {}; } } else { r['-wmso-animation-name'] = value.name; value.duration ? r['-wmso-animation-duration'] = value.duration : ''; value.fillMode ? r['-wmso-animation-fill-mode'] = value.fillMode : ''; value.timingFunction ? r['-wmso-animation-timing-function'] = value.timingFunction : ''; value.iterationCount ? r['-wmso-animation-iteration-count'] = value.iterationCount : ''; value.delay ? r['-wmso-animation-delay'] = value.delay : ''; value.direction ? r['-wmso-animation-direction'] = value.direction : ''; value.playState ? r['-wmso-animation-play-state'] = value.playState : ''; if(value.frames) { r.keyframes = { name: value.name, frames: value.frames } } } } switch(r['-wmso-animation-name']) { case "blink": r.keyframes = { name: "blink", frames: { "0%, 100%": { transparent: 0 }, "50%": { transparent: 1 } } } break; case "bounce": r.keyframes = { name: "bounce", frames: { "0%, 20%, 50%, 80%, 100%": { "-wmso-transform": "translateY(0)" }, "40%": { "-wmso-transform": "translateY(-30px)" }, "60%": { "-wmso-transform": "translateY(-15px)" } } } break; case "flash": r.keyframes = { name: "flash", frames: { "0%, 50%, 100%": { "opacity": "1" }, "25%, 75%": { "opacity": "0" } } } break; case "pulse": r.keyframes = { name: "pulse", frames: { "0%": { "-wmso-transform": "scale(1)" }, "50%": { "-wmso-transform": "scale(1.1)" }, "100%": { "-wmso-transform": "scale(1)" } } } break; case "shake": r.keyframes = { name: "shake", frames: { "0%, 100%": { "-wmso-transform": "translateX(0)" }, "10%, 30%, 50%, 70%, 90%": { "-wmso-transform": "translateX(-10px)" }, "20%, 40%, 60%, 80%": { "-wmso-transform": "translateX(10px)" } } } break; case "swing": r.keyframes = { name: "swing", frames: { "20%": { "-wmso-transform": "rotate(15deg)" }, "40%": { "-wmso-transform": "rotate(-10deg)" }, "60%": { "-wmso-transform": "rotate(5deg)" }, "80%": { "-wmso-transform": "rotate(-5deg)" }, "100%": { "-wmso-transform": "rotate(0deg)" } } } break; case "tada": r.keyframes = { name: "tada", frames: { "0%": { "-wmso-transform": "scale(1)" }, "10%, 20%": { "-wmso-transform": "scale(0.9) rotate(-3deg)" }, "30%, 50%, 70%, 90%": { "-wmso-transform": "scale(1.1) rotate(3deg)" }, "40%, 60%, 80%": { "-wmso-transform": "scale(1.1) rotate(-3deg)" }, "100%": { "-wmso-transform": "scale(1) rotate(0)" } } } break; case "wobble": r.keyframes = { name: "wobble", frames: { "0%": { "-wmso-transform": "translateX(0%)" }, "15%": { "-wmso-transform": "translateX(-25%) rotate(-5deg)" }, "30%": { "-wmso-transform": "translateX(20%) rotate(3deg)" }, "45%": { "-wmso-transform": "translateX(-15%) rotate(-3deg)" }, "60%": { "-wmso-transform": "translateX(10%) rotate(2deg)" }, "75%": { "-wmso-transform": "translateX(-5%) rotate(-1deg)" }, "100%": { "-wmso-transform": "translateX(0%)" } } } break; case "bounceIn": r.keyframes = { name: "bounceIn", frames: { "0%": { "opacity": "0", "-wmso-transform": "scale(.3)" }, "50%": { "opacity": "1", "-wmso-transform": "scale(1.05)" }, "70%": { "-wmso-transform": "scale(.9)" }, "100%": { "-wmso-transform": "scale(1)" } } } break; case "bounceInDown": r.keyframes = { name: "bounceInDown", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateY(-2000px)" }, "60%": { "opacity": "1", "-wmso-transform": "translateY(30px)" }, "80%": { "-wmso-transform": "translateY(-10px)" }, "100%": { "-wmso-transform": "translateY(0)" } } } break; case "bounceInLeft": r.keyframes = { name: "bounceInLeft", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateX(-2000px)" }, "60%": { "opacity": "1", "-wmso-transform": "translateX(30px)" }, "80%": { "-wmso-transform": "translateX(-10px)" }, "100%": { "-wmso-transform": "translateX(0)" } } } break; case "bounceInRight": r.keyframes = { name: "bounceInRight", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateX(2000px)" }, "60%": { "opacity": "1", "-wmso-transform": "translateX(-30px)" }, "80%": { "-wmso-transform": "translateX(10px)" }, "100%": { "-wmso-transform": "translateX(0)" } } } break; case "bounceInUp": r.keyframes = { name: "bounceInUp", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateY(2000px)" }, "60%": { "opacity": "1", "-wmso-transform": "translateY(-30px)" }, "80%": { "-wmso-transform": "translateY(10px)" }, "100%": { "-wmso-transform": "translateY(0)" } } } break; case "bounceOut": r.keyframes = { name: "bounceOut", frames: { "0%": { "-wmso-transform": "scale(1)" }, "25%": { "-wmso-transform": "scale(.95)" }, "50%": { "opacity": "1", "-wmso-transform": "scale(1.1)" }, "100%": { "opacity": "0", "-wmso-transform": "scale(.3)" } } } break; case "bounceOutDown": r.keyframes = { name: "bounceOutDown", frames: { "0%": { "-wmso-transform": "translateY(0)" }, "20%": { "opacity": "1", "-wmso-transform": "translateY(-20px)" }, "100%": { "opacity": "0", "-wmso-transform": "translateY(2000px)" } } } break; case "bounceOutLeft": r.keyframes = { name: "bounceOutLeft", frames: { "0%": { "-wmso-transform": "translateX(0)" }, "20%": { "opacity": "1", "-wmso-transform": "translateX(20px)" }, "100%": { "opacity": "0", "-wmso-transform": "translateX(-2000px)" } } } break; case "bounceOutRight": r.keyframes = { name: "bounceOutRight", frames: { "0%": { "-wmso-transform": "translateX(0)" }, "20%": { "opacity": "1", "-wmso-transform": "translateX(-20px)" }, "100%": { "opacity": "0", "-wmso-transform": "translateX(2000px)" } } } break; case "bounceOutUp": r.keyframes = { name: "bounceOutUp", frames: { "0%": { "-wmso-transform": "translateY(0)" }, "20%": { "opacity": "1", "-wmso-transform": "translateY(20px)" }, "100%": { "opacity": "0", "-wmso-transform": "translateY(-2000px)" } } } break; case "fadeIn": r.keyframes = { name: "fadeIn", frames: { "0%": { "opacity": "0" }, "100%": { "opacity": "1" } } } break; case "fadeInDown": r.keyframes = { name: "fadeInDown", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateY(-20px)" }, "100%": { "opacity": "1", "-wmso-transform": "translateY(0)" } } } break; case "fadeInDownBig": r.keyframes = { name: "fadeInDownBig", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateY(-2000px)" }, "100%": { "opacity": "1", "-wmso-transform": "translateY(0)" } } } break; case "fadeInLeft": r.keyframes = { name: "fadeInLeft", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateX(-20px)" }, "100%": { "opacity": "1", "-wmso-transform": "translateX(0)" } } } break; case "fadeInLeftBig": r.keyframes = { name: "fadeInLeftBig", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateX(-2000px)" }, "100%": { "opacity": "1", "-wmso-transform": "translateX(0)" } } } break; case "fadeInRight": r.keyframes = { name: "fadeInRight", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateX(20px)" }, "100%": { "opacity": "1", "-wmso-transform": "translateX(0)" } } } break; case "fadeInRightBig": r.keyframes = { name: "fadeInRightBig", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateX(2000px)" }, "100%": { "opacity": "1", "-wmso-transform": "translateX(0)" } } } break; case "fadeInUp": r.keyframes = { name: "fadeInUp", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateY(20px)" }, "100%": { "opacity": "1", "-wmso-transform": "translateY(0)" } } } break; case "fadeInUpBig": r.keyframes = { name: "fadeInUpBig", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateY(2000px)" }, "100%": { "opacity": "1", "-wmso-transform": "translateY(0)" } } } break; case "fadeOut": r.keyframes = { name: "fadeOut", frames: { "0%": { "opacity": "1" }, "100%": { "opacity": "0" } } } break; case "fadeOutDown": r.keyframes = { name: "fadeOutDown", frames: { "0%": { "opacity": "1", "-wmso-transform": "translateY(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateY(20px)" } } } break; case "fadeOutDownBig": r.keyframes = { name: "fadeOutDownBig", frames: { "0%": { "opacity": "1", "-wmso-transform": "translateY(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateY(2000px)" } } } break; case "fadeOutLeft": r.keyframes = { name: "fadeOutLeft", frames: { "0%": { "opacity": "1", "-wmso-transform": "translateX(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateX(-20px)" } } } break; case "fadeOutLeftBig": r.keyframes = { name: "fadeOutLeftBig", frames: { "0%": { "opacity": "1", "-wmso-transform": "translateX(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateX(-2000px)" } } } break; case "fadeOutRight": r.keyframes = { name: "fadeOutRight", frames: { "0%": { "opacity": "1", "-wmso-transform": "translateX(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateX(20px)" } } } break; case "fadeOutRightBig": r.keyframes = { name: "fadeOutRightBig", frames: { "0%": { "opacity": "1", "-wmso-transform": "translateX(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateX(2000px)" } } } break; case "fadeOutUp": r.keyframes = { name: "fadeOutUp", frames: { "0%": { "opacity": "1", "-wmso-transform": "translateY(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateY(-20px)" } } } break; case "fadeOutUpBig": r.keyframes = { name: "fadeOutUpBig", frames: { "0%": { "opacity": "1", "-wmso-transform": "translateY(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateY(-2000px)" } } } break; case "flip": r.keyframes = { name: "flip", frames: { "0%": { "-wmso-transform": "perspective(400px) translateZ(0) rotateY(0) scale(1)", "animation-timing-function": "ease-out" }, "40%": { "-wmso-transform": "perspective(400px) translateZ(150px) rotateY(170deg) scale(1)", "animation-timing-function": "ease-out" }, "50%": { "-wmso-transform": "perspective(400px) translateZ(150px) rotateY(190deg) scale(1)", "animation-timing-function": "ease-in" }, "80%": { "-wmso-transform": "perspective(400px) translateZ(0) rotateY(360deg) scale(.95)", "animation-timing-function": "ease-in" }, "100%": { "-wmso-transform": "perspective(400px) translateZ(0) rotateY(360deg) scale(1)", "animation-timing-function": "ease-in" } } } break; case "flipInX": r.keyframes = { name: "flipInX", frames: { "0%": { "-wmso-transform": "perspective(400px) rotateX(90deg)", "opacity": "0" }, "40%": { "-wmso-transform": "perspective(400px) rotateX(-10deg)" }, "70%": { "-wmso-transform": "perspective(400px) rotateX(10deg)" }, "100%": { "-wmso-transform": "perspective(400px) rotateX(0deg)", "opacity": "1" } } } break; case "flipInY": r.keyframes = { name: "flipInY", frames: { "0%": { "-wmso-transform": "perspective(400px) rotateY(90deg)", "opacity": "0" }, "40%": { "-wmso-transform": "perspective(400px) rotateY(-10deg)" }, "70%": { "-wmso-transform": "perspective(400px) rotateY(10deg)" }, "100%": { "-wmso-transform": "perspective(400px) rotateY(0deg)", "opacity": "1" } } } break; case "flipOutX": r.keyframes = { name: "flipOutX", frames: { "0%": { "-wmso-transform": "perspective(400px) rotateX(0deg)", "opacity": "1" }, "100%": { "-wmso-transform": "perspective(400px) rotateX(90deg)", "opacity": "0" } } } break; case "flipOutY": r.keyframes = { name: "flipOutY", frames: { "0%": { "-wmso-transform": "perspective(400px) rotateY(0deg)", "opacity": "1" }, "100%": { "-wmso-transform": "perspective(400px) rotateY(90deg)", "opacity": "0" } } } break; case "lightSpeedIn": r.keyframes = { name: "lightSpeedIn", frames: { "0%": { "-wmso-transform": "translateX(100%) skewX(-30deg)", "opacity": "0" }, "60%": { "-wmso-transform": "translateX(-20%) skewX(30deg)", "opacity": "1" }, "80%": { "-wmso-transform": "translateX(0%) skewX(-15deg)", "opacity": "1" }, "100%": { "-wmso-transform": "translateX(0%) skewX(0deg)", "opacity": "1" } } } break; case "lightSpeedOut": r.keyframes = { name: "lightSpeedOut", frames: { "0%": { "-wmso-transform": "translateX(0%) skewX(0deg)", "opacity": "1" }, "100%": { "-wmso-transform": "translateX(100%) skewX(-30deg)", "opacity": "0" } } } break; case "rotateIn": r.keyframes = { name: "rotateIn", frames: { "0%": { "transform-origin": "center center", "-wmso-transform": "rotate(-200deg)", "opacity": "0" }, "100%": { "transform-origin": "center center", "-wmso-transform": "rotate(0)", "opacity": "1" } } } break; case "rotateInDownLeft": r.keyframes = { name: "rotateInDownLeft", frames: { "0%": { "transform-origin": "left bottom", "-wmso-transform": "rotate(-90deg)", "opacity": "0" }, "100%": { "transform-origin": "left bottom", "-wmso-transform": "rotate(0)", "opacity": "1" } } } break; case "rotateInDownRight": r.keyframes = { name: "rotateInDownRight", frames: { "0%": { "transform-origin": "right bottom", "-wmso-transform": "rotate(90deg)", "opacity": "0" }, "100%": { "transform-origin": "right bottom", "-wmso-transform": "rotate(0)", "opacity": "1" } } } break; case "rotateInUpLeft": r.keyframes = { name: "rotateInUpLeft", frames: { "0%": { "transform-origin": "left bottom", "-wmso-transform": "rotate(90deg)", "opacity": "0" }, "100%": { "transform-origin": "left bottom", "-wmso-transform": "rotate(0)", "opacity": "1" } } } break; case "rotateInUpRight": r.keyframes = { name: "rotateInUpRight", frames: { "0%": { "transform-origin": "right bottom", "-wmso-transform": "rotate(-90deg)", "opacity": "0" }, "100%": { "transform-origin": "right bottom", "-wmso-transform": "rotate(0)", "opacity": "1" } } } break; case "rotateOut": r.keyframes = { name: "rotateOut", frames: { "0%": { "transform-origin": "center center", "-wmso-transform": "rotate(0)", "opacity": "1" }, "100%": { "transform-origin": "center center", "-wmso-transform": "rotate(200deg)", "opacity": "0" } } } break; case "rotateOutDownLeft": r.keyframes = { name: "rotateOutDownLeft", frames: { "0%": { "transform-origin": "left bottom", "-wmso-transform": "rotate(0)", "opacity": "1" }, "100%": { "transform-origin": "left bottom", "-wmso-transform": "rotate(90deg)", "opacity": "0" } } } break; case "rotateOutDownRight": r.keyframes = { name: "rotateOutDownRight", frames: { "0%": { "transform-origin": "right bottom", "-wmso-transform": "rotate(0)", "opacity": "1" }, "100%": { "transform-origin": "right bottom", "-wmso-transform": "rotate(-90deg)", "opacity": "0" } } } break; case "rotateOutUpLeft": r.keyframes = { name: "rotateOutUpLeft", frames: { "0%": { "transform-origin": "left bottom", "-wmso-transform": "rotate(0)", "opacity": "1" }, "100%": { "transform-origin": "left bottom", "-wmso-transform": "rotate(-90deg)", "opacity": "0" } } } break; case "rotateOutUpRight": r.keyframes = { name: "rotateOutUpRight", frames: { "0%": { "transform-origin": "right bottom", "-wmso-transform": "rotate(0)", "opacity": "1" }, "100%": { "transform-origin": "right bottom", "-wmso-transform": "rotate(90deg)", "opacity": "0" } } } break; case "slideInDown": r.keyframes = { name: "slideInDown", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateY(-2000px)" }, "100%": { "-wmso-transform": "translateY(0)" } } } break; case "slideInLeft": r.keyframes = { name: "slideInLeft", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateX(-2000px)" }, "100%": { "-wmso-transform": "translateX(0)" } } } break; case "slideInRight": r.keyframes = { name: "slideInRight", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateX(2000px)" }, "100%": { "-wmso-transform": "translateX(0)" } } } break; case "slideOutLeft": r.keyframes = { name: "slideOutLeft", frames: { "0%": { "-wmso-transform": "translateX(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateX(-2000px)" } } } break; case "slideOutRight": r.keyframes = { name: "slideOutRight", frames: { "0%": { "-wmso-transform": "translateX(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateX(2000px)" } } } break; case "slideOutUp": r.keyframes = { name: "slideOutUp", frames: { "0%": { "-wmso-transform": "translateY(0)" }, "100%": { "opacity": "0", "-wmso-transform": "translateY(-2000px)" } } } break; case "hinge": r.keyframes = { name: "hinge", frames: { "0%": { "-wmso-transform": "rotate(0)", "transform-origin": "top left", "animation-timing-function": "ease-in-out" }, "20%, 60%": { "-wmso-transform": "rotate(80deg)", "transform-origin": "top left", "animation-timing-function": "ease-in-out" }, "40%": { "-wmso-transform": "rotate(60deg)", "transform-origin": "top left", "animation-timing-function": "ease-in-out" }, "80%": { "-wmso-transform": "rotate(60deg) translateY(0)", "opacity": "1", "transform-origin": "top left", "animation-timing-function": "ease-in-out" }, "100%": { "-wmso-transform": "translateY(700px)", "opacity": "0" } } } break; case "rollIn": r.keyframes = { name: "rollIn", frames: { "0%": { "opacity": "0", "-wmso-transform": "translateX(-100%) rotate(-120deg)" }, "100%": { "opacity": "1", "-wmso-transform": "translateX(0px) rotate(0deg)" } } } break; case "rollOut": r.keyframes = { name: "rollOut", frames: { "0%": { "opacity": "1", "-wmso-transform": "translateX(0px) rotate(0deg)" }, "100%": { "opacity": "0", "-wmso-transform": "translateX(100%) rotate(120deg)" } } } break; } return r; } o.lib.molecules.blur = function(value) { return { '-wms-filter': 'blur(' + value + 'px)' } } o.lib.molecules.brightness = function(value) { return { '-wms-filter': 'brightness(' + value + ')' } } o.lib.molecules.calc = function(value) { var args = require('../../helpers/args')(value), r = {}; r['LhProperty'] = '0'; r['~~1~~' + args[0]] = '-webkit-calc(' + args[1] + ')'; r['~~2~~' + args[0]] = '-moz-calc(' + args[1] + ')'; r['~~3~~' + args[0]] = 'calc(' + args[1] + ')'; return r; } o.lib.molecules.cf = function(value) { var r = {}, clearing = { content: '" "', display: 'table', clear: 'both' }; switch(value) { case 'before': r['&:before'] = clearing; break; case 'after': r['&:after'] = clearing; break; default: r['&:before'] = clearing; r['&:after'] = clearing; break; } return r; } o.lib.molecules.contrast = function(value) { return { '-wms-filter': 'contrast(' + value + '%)' } } o.lib.molecules.dropshadow = function(value) { return { '-wms-filter': 'drop-shadow(' + value + ')' } } var getMSColor = function(color) { color = color.toString().replace('#', ''); if(color.length == 3) { var tmp = ''; for(var i=0; i<color.length; i++) { tmp += color[i] + color[i]; } color = tmp; } return '#FF' + color.toUpperCase(); } o.lib.molecules.gradient = function(value) { var r = {}, args = require('../../helpers/args')(value); switch(typeof value) { case 'string': var deg = args[args.length-1]; if(deg.indexOf('deg') > 0) { deg = parseInt(args.pop().replace('deg', '')); } else { deg = 0; } var numOfStops = args.length, stepsPercents = Math.floor(100 / (numOfStops-1)).toFixed(2), gradientValue = [], msGradientType = (deg >= 45 && deg <= 135) || (deg >= 225 && deg <= 315) ? 1 : 0, msStartColor = msGradientType === 0 ? getMSColor(args[args.length-1]) : getMSColor(args[0]), msEndColor = msGradientType === 0 ? getMSColor(args[0]) : getMSColor(args[args.length-1]); for(var i=0; i<numOfStops; i++) { if(args[i].indexOf('%') > 0) { gradientValue.push(args[i]); } else { gradientValue.push(args[i] + ' ' + (i*stepsPercents) + '%'); } } gradientValue = deg + 'deg, ' + gradientValue.join(', '); return [ { 'background': '-webkit-linear-gradient(' + gradientValue + ')' }, { '~~1~~background': '-moz-linear-gradient(' + gradientValue + ')' }, { '~~2~~background': '-ms-linear-gradient(' + gradientValue + ')' }, { '~~3~~background': '-o-linear-gradient(' + gradientValue + ')' }, { '~~4~~background': 'linear-gradient(' + gradientValue + ')' }, { 'filter': 'progid:DXImageTransform.Microsoft.gradient(startColorstr=\'' + msStartColor + '\', endColorstr=\'' + msEndColor + '\',GradientType=' + msGradientType + ')' }, { 'MsFilter': 'progid:DXImageTransform.Microsoft.gradient(startColorstr=\'' + msStartColor + '\',endColorstr=\'' + msEndColor + '\',GradientType=' + msGradientType + ')' } ] break; } return {}; } o.lib.molecules.grid = function(value) { var args = require('../../helpers/args')(value); if(args.length == 2) { var res = { cf: 'both' } res[args[1]] = { fl: 'l', '-mw-bxz': 'bb', wid: (100 / parseInt(args[0])).toFixed(2) + '%' } return res; } else { return {}; } } o.lib.molecules.invert = function(value) { return { '-wms-filter': 'invert(' + value + '%)' } } o.lib.molecules.moveto = function(value) { var units = require('../../helpers/units'), args = require('../../helpers/args')(value), x = units(!args[0] || args[0] == '' ? 0 : args[0], 'px'), y = units(!args[1] || args[1] == '' ? 0 : args[1], 'px'), z = units(!args[2] || args[2] == '' ? 0 : args[2], 'px'); if(args.length == 2) { return {"-ws-trf": ">translate(" + x + "," + y + ")"}; } else if(args.length == 3) { return {"-ws-trf": ">translate3d(" + x + "," + y + "," + z + ")"}; } } o.lib.molecules.rotateto = function(value) { var units = require('../../helpers/units'), args = require('../../helpers/args')(value); if(args.length == 1) { return {"-ws-trf": ">rotate(" + units(args[0], 'deg') + ")"}; } } o.lib.molecules.saturate = function(value) { return { '-wms-filter': 'saturate(' + value + 'deg)' } } o.lib.molecules.scaleto = function(value) { var args = require('../../helpers/args')(value), x = !args[0] || args[0] == '' ? 0 : args[0], y = !args[1] || args[1] == '' ? 0 : args[1]; if(args.length == 2) { return {"-ws-trf": ">scale(" + x + "," + y + ")"}; } } o.lib.molecules.sepia = function(value) { return { '-wms-filter': 'sepia(' + value + '%)' } } o.lib.molecules.size = function(value) { var units = require('../../helpers/units'), args = require('../../helpers/args')(value), r = {}; if(args.length == 2) { if(args[0] != '') { r.width = units(args[0]); } if(args[1] != '') { r.height = units(args[1]); } return r; } else { return { width: units(args[0]), height: units(args[0]) } } } o.lib.molecules.transparent = function(value) { var args = require('../../helpers/args')(value), r = {}; value = parseFloat(value); r['-s-filter'] = 'progid:DXImageTransform.Microsoft.Alpha(Opacity=' + (value * 100) + ')'; r['filter'] = 'alpha(opacity=' + (value * 100) + ')'; r['-m-opacity'] = value; r['opacity'] = value; r['KhtmlOpacity'] = value; return r; } o.lib.molecules.trsform = function(value) { return { '-wmso-transform': value } }; return o.index; })(window);
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: First expression is evaluated first, and then second expression es5id: 11.8.1_A2.4_T2 description: Checking with "throw" ---*/ //CHECK#1 var x = function () { throw "x"; }; var y = function () { throw "y"; }; try { x() < y(); $ERROR('#1.1: var x = function () { throw "x"; }; var y = function () { throw "y"; }; x() < y() throw "x". Actual: ' + (x() < y())); } catch (e) { if (e === "y") { $ERROR('#1.2: First expression is evaluated first, and then second expression'); } else { if (e !== "x") { $ERROR('#1.3: var x = function () { throw "x"; }; var y = function () { throw "y"; }; x() < y() throw "x". Actual: ' + (e)); } } }
var binding = require('bindings')('binding'); var assert = require('assert'); /** * Compress asyncronous. * If input isn't a string or buffer, automatically convert to buffer by using * JSON.stringify. */ exports.compress = function (input, callback) { if (!(typeof (input) === 'string' || Buffer.isBuffer(input))) { return callback(new Error('input must be a String or a Buffer')); } binding.compress(input, callback); }; exports.compressSync = function (input) { assert(typeof (input) === 'string' || Buffer.isBuffer(input), 'input must be a String or a Buffer'); return binding.compressSync(input); }; /** * Asyncronous decide if a buffer is compressed in a correct way. */ exports.isValidCompressed = binding.isValidCompressed; exports.isValidCompressedSync = binding.isValidCompressedSync; /** * Asyncronous uncompress previously compressed data. * A parser can be attached. If no parser is attached, return buffer. */ exports.uncompress = function (compressed, opts, callback) { if (!callback) { callback = opts; } if (!Buffer.isBuffer(compressed)) { return callback(new Error('input must be a Buffer')); } binding.uncompress(compressed, uncompressOpts(opts), callback); }; exports.uncompressSync = function (compressed, opts) { assert(Buffer.isBuffer(compressed), 'input must be a Buffer'); return binding.uncompressSync(compressed, uncompressOpts(opts)); }; function uncompressOpts (opts) { return (opts && typeof opts.asBuffer === 'boolean') ? opts : {asBuffer: true}; }
define(['mout/date/isSame'], function(isSame){ describe('date/isSame', function(){ it('should check if dates are equal', function(){ expect( isSame(new Date(2013,3,5), new Date(2013,3,5)) ).toBe(true); expect( isSame(new Date(2013,3,5), new Date(2013,3,5,1)) ).toBe(false); }); it('should allow specifying the comparisson', function () { var d1 = new Date(2013,3,5); var d2 = new Date(2013,3,6); expect( isSame(d1, d2, 'year') ).toEqual( true ); expect( isSame(d1, d2, 'month') ).toEqual( true ); expect( isSame(d1, d2, 'day') ).toEqual( false ); }); }); });
/*! UIkit 3.0.0-rc.9 | http://www.getuikit.com | (c) 2014 - 2017 YOOtheme | MIT License */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('uikit-util')) : typeof define === 'function' && define.amd ? define('uikitnotification', ['uikit-util'], factory) : (global.UIkitNotification = factory(global.UIkit.util)); }(this, (function (uikitUtil) { 'use strict'; var obj; var containers = {}; var Component = { functional: true, args: ['message', 'status'], data: { message: '', status: '', timeout: 5000, group: null, pos: 'top-center', clsClose: 'uk-notification-close', clsMsg: 'uk-notification-message' }, install: install, created: function() { if (!containers[this.pos]) { containers[this.pos] = uikitUtil.append(this.$container, ("<div class=\"uk-notification uk-notification-" + (this.pos) + "\"></div>")); } var container = uikitUtil.css(containers[this.pos], 'display', 'block'); this.$mount(uikitUtil.append(container, ("<div class=\"" + (this.clsMsg) + (this.status ? (" " + (this.clsMsg) + "-" + (this.status)) : '') + "\"> <a href=\"#\" class=\"" + (this.clsClose) + "\" data-uk-close></a> <div>" + (this.message) + "</div> </div>") )); }, ready: function() { var this$1 = this; var marginBottom = uikitUtil.toFloat(uikitUtil.css(this.$el, 'marginBottom')); uikitUtil.Transition.start( uikitUtil.css(this.$el, {opacity: 0, marginTop: -this.$el.offsetHeight, marginBottom: 0}), {opacity: 1, marginTop: 0, marginBottom: marginBottom} ).then(function () { if (this$1.timeout) { this$1.timer = setTimeout(this$1.close, this$1.timeout); } }); }, events: ( obj = { click: function(e) { if (uikitUtil.closest(e.target, 'a[href="#"]')) { e.preventDefault(); } this.close(); } }, obj[uikitUtil.pointerEnter] = function () { if (this.timer) { clearTimeout(this.timer); } }, obj[uikitUtil.pointerLeave] = function () { if (this.timeout) { this.timer = setTimeout(this.close, this.timeout); } }, obj ), methods: { close: function(immediate) { var this$1 = this; var removeFn = function () { uikitUtil.trigger(this$1.$el, 'close', [this$1]); uikitUtil.remove(this$1.$el); if (!containers[this$1.pos].children.length) { uikitUtil.css(containers[this$1.pos], 'display', 'none'); } }; if (this.timer) { clearTimeout(this.timer); } if (immediate) { removeFn(); } else { uikitUtil.Transition.start(this.$el, { opacity: 0, marginTop: -this.$el.offsetHeight, marginBottom: 0 }).then(removeFn); } } } }; function install(UIkit) { UIkit.notification.closeAll = function (group, immediate) { uikitUtil.apply(document.body, function (el) { var notification = UIkit.getComponent(el, 'notification'); if (notification && (!group || group === notification.group)) { notification.close(immediate); } }); }; } /* global UIkit, 'notification' */ if (typeof window !== 'undefined' && window.UIkit) { window.UIkit.component('notification', Component); } return Component; })));
steal('can/construct',function($){ var isFunction = can.isFunction, isArray = can.isArray, makeArray = can.makeArray, proxy = function( funcs ) { //args that should be curried var args = makeArray(arguments), self; // get the functions to callback funcs = args.shift(); // if there is only one function, make funcs into an array if (!isArray(funcs) ) { funcs = [funcs]; } // keep a reference to us in self self = this; //!steal-remove-start for( var i =0; i< funcs.length;i++ ) { if(typeof funcs[i] == "string" && !isFunction(this[funcs[i]])){ throw ("class.js "+( this.fullName || this.Class.fullName)+" does not have a "+funcs[i]+"method!"); } } //!steal-remove-end return function class_cb() { // add the arguments after the curried args var cur = args.concat(makeArray(arguments)), isString, length = funcs.length, f = 0, func; // go through each function to call back for (; f < length; f++ ) { func = funcs[f]; if (!func ) { continue; } // set called with the name of the function on self (this is how this.view works) isString = typeof func == "string"; // call the function cur = (isString ? self[func] : func).apply(self, cur || []); // pass the result to the next function (if there is a next function) if ( f < length - 1 ) { cur = !isArray(cur) || cur._use_call ? [cur] : cur } } return cur; } } can.Construct.proxy = can.Construct.prototype.proxy = proxy; });
var assert = require('assert'); var path = require('path'); var fs = require('fs'); var util = require('util'); var temp = require('../lib/temp'); temp.track(); var existsSync = function(path){ try { fs.statSync(path); return true; } catch (e){ return false; } }; // Use path.exists for 0.6 if necessary var safeExists = fs.exists || path.exists; var mkdirFired = false; var mkdirPath = null; temp.mkdir('foo', function(err, tpath) { mkdirFired = true; assert.ok(!err, "temp.mkdir did not execute without errors"); assert.ok(path.basename(tpath).slice(0, 3) == 'foo', 'temp.mkdir did not use the prefix'); assert.ok(existsSync(tpath), 'temp.mkdir did not create the directory'); fs.writeFileSync(path.join(tpath, 'a file'), 'a content'); temp.cleanupSync(); assert.ok(!existsSync(tpath), 'temp.cleanupSync did not remove the directory'); mkdirPath = tpath; }); var openFired = false; var openPath = null; temp.open('bar', function(err, info) { openFired = true; assert.equal('object', typeof(info), "temp.open did not invoke the callback with the err and info object"); assert.equal('number', typeof(info.fd), 'temp.open did not invoke the callback with an fd'); fs.writeSync(info.fd, 'foo'); fs.closeSync(info.fd); assert.equal('string', typeof(info.path), 'temp.open did not invoke the callback with a path'); assert.ok(existsSync(info.path), 'temp.open did not create a file'); temp.cleanupSync(); assert.ok(!existsSync(info.path), 'temp.cleanupSync did not remove the file'); openPath = info.path; }); var stream = temp.createWriteStream('baz'); assert.ok(stream instanceof fs.WriteStream, 'temp.createWriteStream did not invoke the callback with the err and stream object'); stream.write('foo'); stream.end("More text here\nand more..."); assert.ok(existsSync(stream.path), 'temp.createWriteStream did not create a file'); // cleanupSync() temp.cleanupSync(); assert.ok(!existsSync(stream.path), 'temp.cleanupSync did not remove the createWriteStream file'); // cleanup() var cleanupFired = false; // Make a temp file just to cleanup var tempFile = temp.openSync(); fs.writeSync(tempFile.fd, 'foo'); fs.closeSync(tempFile.fd); assert.ok(existsSync(tempFile.path), 'temp.openSync did not create a file for cleanup'); // run cleanup() temp.cleanup(function(err, counts) { cleanupFired = true; assert.ok(!err, 'temp.cleanup did not run without encountering an error'); assert.ok(!existsSync(tempFile.path), 'temp.cleanup did not remove the openSync file for cleanup'); assert.equal(1, counts.files, 'temp.cleanup did not report the correct removal statistics'); }); var tempPath = temp.path(); assert.ok(path.dirname(tempPath) === temp.dir, "temp.path does not work in default os temporary directory"); tempPath = temp.path({dir: process.cwd()}); assert.ok(path.dirname(tempPath) === process.cwd(), "temp.path does not work in user-provided temporary directory"); for (var i=0; i <= 10; i++) { temp.openSync(); } assert.equal(process.listeners('exit').length, 1, 'temp created more than one listener for exit'); process.addListener('exit', function() { assert.ok(mkdirFired, "temp.mkdir callback did not fire"); assert.ok(openFired, "temp.open callback did not fire"); assert.ok(cleanupFired, "temp.cleanup callback did not fire"); });
/** * Return true, if the value is a valid date, also making this formal check dd/mm/yyyy. * * @example $.validator.methods.date("01/01/1900") * @result true * * @example $.validator.methods.date("01/13/1990") * @result false * * @example $.validator.methods.date("01.01.1900") * @result false * * @example <input name="pippo" class="{dateITA:true}" /> * @desc Declares an optional input element whose value must be a valid date. * * @name $.validator.methods.dateITA * @type Boolean * @cat Plugins/Validate/Methods */ $.validator.addMethod( "dateITA", function( value, element ) { var check = false, re = /^\d{1,2}\/\d{1,2}\/\d{4}$/, adata, gg, mm, aaaa, xdata; if ( re.test( value ) ) { adata = value.split( "/" ); gg = parseInt( adata[ 0 ], 10 ); mm = parseInt( adata[ 1 ], 10 ); aaaa = parseInt( adata[ 2 ], 10 ); xdata = new Date( Date.UTC( aaaa, mm - 1, gg, 12, 0, 0, 0 ) ); if ( ( xdata.getUTCFullYear() === aaaa ) && ( xdata.getUTCMonth () === mm - 1 ) && ( xdata.getUTCDate() === gg ) ) { check = true; } else { check = false; } } else { check = false; } return this.optional( element ) || check; }, $.validator.messages.date );
/** * ProgressState.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.ui.ProgressState', [ 'tinymce.core.ui.Throbber' ], function (Throbber) { var setup = function (editor, theme) { var throbber; editor.on('ProgressState', function (e) { throbber = throbber || new Throbber(theme.panel.getEl('body')); if (e.state) { throbber.show(e.time); } else { throbber.hide(); } }); }; return { setup: setup }; } );
var parent = require('../../stable/number/is-nan'); module.exports = parent;
/*! * froala_editor v2.8.2 (https://www.froala.com/wysiwyg-editor) * License https://froala.com/wysiwyg-editor/terms/ * Copyright 2014-2018 Froala Labs */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('FroalaEditor')) : typeof define === 'function' && define.amd ? define(['FroalaEditor'], factory) : (factory(global.$.FroalaEditor)); }(this, (function (FE) { 'use strict'; FE = FE && FE.hasOwnProperty('default') ? FE['default'] : FE; /** * Swedish */ FE.LANGUAGE['sv'] = { translation: { // Place holder "Type something": 'Ange n\xE5got', // Basic formatting "Bold": "Fetstil", "Italic": "Kursiv stil", "Underline": "Understruken", "Strikethrough": "Genomstruken", // Main buttons "Insert": "Infoga", "Delete": "Radera", "Cancel": "Avbryt", "OK": "Ok", "Back": "Tillbaka", "Remove": "Ta bort", "More": "Mer", "Update": "Uppdatera", "Style": "Stil", // Font "Font Family": "Teckensnitt", "Font Size": "Teckenstorlek", // Colors "Colors": 'F\xE4rger', "Background": "Bakgrund", "Text": "Text", "HEX Color": "Hex färg", // Paragraphs "Paragraph Format": "Format", "Normal": "Normal", "Code": "Kod", "Heading 1": "Rubrik 1", "Heading 2": "Rubrik 2", "Heading 3": "Rubrik 3", "Heading 4": "Rubrik 4", // Style "Paragraph Style": "Styckesformat", "Inline Style": "Infogad stil", // Alignment "Align": "Justera", "Align Left": "Vänsterjustera", "Align Center": "Centrera", "Align Right": "Högerjustera", "Align Justify": "Justera", "None": "Inget", // Lists "Ordered List": "Ordnad lista", "Unordered List": "Oordnad lista", // Indent "Decrease Indent": "Minska indrag", "Increase Indent": '\xD6ka indrag', // Links "Insert Link": 'Infoga l\xE4nk', "Open in new tab": '\xD6ppna i ny flik', "Open Link": '\xD6ppna l\xE4nk', "Edit Link": 'Redigera l\xE4nk', "Unlink": 'Ta bort l\xE4nk', "Choose Link": 'V\xE4lj l\xE4nk', // Images "Insert Image": "Infoga bild", "Upload Image": "Ladda upp en bild", "By URL": "Genom URL", "Browse": 'Bl\xE4ddra', "Drop image": 'Sl\xE4pp bild', "or click": "eller klicka", "Manage Images": "Hantera bilder", "Loading": "Laddar", "Deleting": "Raderar", "Tags": "Etiketter", "Are you sure? Image will be deleted.": '\xC4r du s\xE4ker? Bild kommer att raderas.', "Replace": 'Ers\xE4tt', "Uploading": "Laddar up", "Loading image": "Laddar bild", "Display": "Visa", "Inline": "I linje", "Break Text": "Bryt text", "Alternative Text": "Alternativ text", "Change Size": '\xC4ndra storlek', "Width": "Bredd", "Height": 'H\xF6jd', "Something went wrong. Please try again.": 'N\xE5got gick fel. Var god f\xF6rs\xF6k igen.', "Image Caption": "Bildtext", "Advanced Edit": "Avancerad redigering", // Video "Insert Video": "Infoga video", "Embedded Code": 'Inb\xE4ddad kod', "Paste in a video URL": "Klistra in i en video url", "Drop video": "Släpp video", "Your browser does not support HTML5 video.": "Din webbläsare stöder inte html5-video.", "Upload Video": "Ladda upp video", // Tables "Insert Table": "Infoga tabell", "Table Header": "Tabell huvud", "Remove Table": "Ta bort tabellen", "Table Style": "Tabellformat", "Horizontal Align": "Horisontell justering", "Row": "Rad", "Insert row above": 'Infoga rad f\xF6re', "Insert row below": "Infoga rad efter", "Delete row": "Ta bort rad", "Column": "Kolumn", "Insert column before": 'Infoga kollumn f\xF6re', "Insert column after": "Infoga kolumn efter", "Delete column": "Ta bort kolumn", "Cell": "Cell", "Merge cells": "Sammanfoga celler", "Horizontal split": "Dela horisontellt", "Vertical split": "Dela vertikalt", "Cell Background": "Cellbakgrund", "Vertical Align": "Vertikal justering", "Top": "Överst", "Middle": "Mitten", "Bottom": "Nederst", "Align Top": "Justera överst", "Align Middle": "Justera mitten", "Align Bottom": "Justera nederst", "Cell Style": "Cellformat", // Files "Upload File": "Ladda upp fil", "Drop file": 'Sl\xE4pp fil', // Emoticons "Emoticons": "Uttryckssymboler", "Grinning face": "Grina ansikte", "Grinning face with smiling eyes": 'Grina ansikte med leende \xF6gon', "Face with tears of joy": 'Face med gl\xE4djet\xE5rar', "Smiling face with open mouth": 'Leende ansikte med \xF6ppen mun', "Smiling face with open mouth and smiling eyes": 'Leende ansikte med \xF6ppen mun och leende \xF6gon', "Smiling face with open mouth and cold sweat": 'Leende ansikte med \xF6ppen mun och kallsvett', "Smiling face with open mouth and tightly-closed eyes": 'Leende ansikte med \xF6ppen mun och t\xE4tt slutna \xF6gon', "Smiling face with halo": "Leende ansikte med halo", "Smiling face with horns": "Leende ansikte med horn", "Winking face": "Blinka ansikte", "Smiling face with smiling eyes": 'Leende ansikte med leende \xF6gon', "Face savoring delicious food": 'Ansikte smaka uts\xF6kt mat', "Relieved face": 'L\xE4ttad ansikte', "Smiling face with heart-shaped eyes": 'Leende ansikte med hj\xE4rtformade \xF6gon', "Smiling face with sunglasses": 'Leende ansikte med solglas\xF6gon', "Smirking face": "Flinande ansikte", "Neutral face": "Neutral ansikte", "Expressionless face": "Uttryckslöst ansikte", "Unamused face": "Inte roade ansikte", "Face with cold sweat": "Ansikte med kallsvett", "Pensive face": 'Eftert\xE4nksamt ansikte', "Confused face": 'F\xF6rvirrad ansikte', "Confounded face": 'F\xF6rbryllade ansikte', "Kissing face": "Kyssande ansikte", "Face throwing a kiss": "Ansikte kasta en kyss", "Kissing face with smiling eyes": 'Kyssa ansikte med leende \xF6gon', "Kissing face with closed eyes": 'Kyssa ansikte med slutna \xF6gon', "Face with stuck out tongue": "Ansikte med stack ut tungan", "Face with stuck out tongue and winking eye": 'Ansikte med stack ut tungan och blinkande \xF6ga', "Face with stuck out tongue and tightly-closed eyes": 'Ansikte med stack ut tungan och t\xE4tt slutna \xF6gon', "Disappointed face": "Besviken ansikte", "Worried face": "Orolig ansikte", "Angry face": "Argt ansikte", "Pouting face": 'Sk\xE4ggtorsk ansikte', "Crying face": 'Gr\xE5tande ansikte', "Persevering face": 'Uth\xE5llig ansikte', "Face with look of triumph": 'Ansikte med utseendet p\xE5 triumf', "Disappointed but relieved face": 'Besviken men l\xE4ttad ansikte', "Frowning face with open mouth": 'Rynkar pannan ansikte med \xF6ppen mun', "Anguished face": '\xC5ngest ansikte', "Fearful face": 'R\xE4dda ansikte', "Weary face": 'Tr\xF6tta ansikte', "Sleepy face": 'S\xF6mnig ansikte', "Tired face": 'Tr\xF6tt ansikte', "Grimacing face": "Grimaserande ansikte", "Loudly crying face": 'H\xF6gt gr\xE5tande ansikte', "Face with open mouth": 'Ansikte med \xF6ppen mun', "Hushed face": 'D\xE4mpade ansikte', "Face with open mouth and cold sweat": 'Ansikte med \xF6ppen mun och kallsvett', "Face screaming in fear": 'Face skriker i skr\xE4ck', "Astonished face": 'F\xF6rv\xE5nad ansikte', "Flushed face": "Ansiktsrodnad", "Sleeping face": "Sovande anskite", "Dizzy face": "Yr ansikte", "Face without mouth": "Ansikte utan mun", "Face with medical mask": "Ansikte med medicinsk maskera", // Line breaker "Break": "Ny rad", // Math "Subscript": 'Neds\xE4nkt', "Superscript": 'Upph\xF6jd', // Full screen "Fullscreen": 'Helsk\xE4rm', // Horizontal line "Insert Horizontal Line": "Infoga horisontell linje", // Clear formatting "Clear Formatting": "Ta bort formatering", // Undo, redo "Undo": '\xC5ngra', "Redo": 'G\xF6r om', // Select all "Select All": "Markera allt", // Code view "Code View": "Kodvy", // Quote "Quote": "Citat", "Increase": '\xD6ka', "Decrease": "Minska", // Quick Insert "Quick Insert": "Snabbinfoga", // Spcial Characters "Special Characters": "Specialtecken", "Latin": "Latin", "Greek": "Grekisk", "Cyrillic": "Cyrillic", "Punctuation": "Skiljetecken", "Currency": "Valuta", "Arrows": "Pilar", "Math": "Matematik", "Misc": "Övrigt", // Print. "Print": "Skriva ut", // Spell Checker. "Spell Checker": "Stavningskontroll", // Help "Help": "Hjälp", "Shortcuts": "Genvägar", "Inline Editor": "Inline editor", "Show the editor": "Visa redigeraren", "Common actions": "Vanliga kommandon", "Copy": "Kopiera", "Cut": "Klipp ut", "Paste": "Klistra in", "Basic Formatting": "Grundläggande formatering", "Increase quote level": "Öka citatnivå", "Decrease quote level": "Minska citatnivå", "Image / Video": "Bild / video", "Resize larger": "Öka storlek", "Resize smaller": "Minska storlek", "Table": "Tabell", "Select table cell": "Markera tabellcell", "Extend selection one cell": "Utöka markering en cell", "Extend selection one row": "Utöka markering en rad", "Navigation": "Navigering", "Focus popup / toolbar": "Fokusera popup / verktygsfältet", "Return focus to previous position": "Byt fokus till föregående plats", // Embed.ly "Embed URL": "Bädda in url", "Paste in a URL to embed": "Klistra in i en url för att bädda in", // Word Paste. "The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?": "Den inklippta texten kommer från ett Microsoft Word-dokument. Vill du behålla formateringen eller städa upp det?", "Keep": "Behåll", "Clean": "Städa upp", "Word Paste Detected": "Urklipp från Word upptäckt" }, direction: "ltr" }; }))); //# sourceMappingURL=sv.js.map
/** * @version: 3.0.1 * @author: Dan Grossman http://www.dangrossman.info/ * @copyright: Copyright (c) 2012-2018 Dan Grossman. All rights reserved. * @license: Licensed under the MIT license. See http://www.opensource.org/licenses/mit-license.php * @website: http://www.daterangepicker.com/ */ // Following the UMD template https://github.com/umdjs/umd/blob/master/templates/returnExportsGlobal.js (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Make globaly available as well define(['moment', 'jquery'], function (moment, jquery) { if (!jquery.fn) jquery.fn = {}; // webpack server rendering return factory(moment, jquery); }); } else if (typeof module === 'object' && module.exports) { // Node / Browserify //isomorphic issue var jQuery = (typeof window != 'undefined') ? window.jQuery : undefined; if (!jQuery) { jQuery = require('jquery'); if (!jQuery.fn) jQuery.fn = {}; } var moment = (typeof window != 'undefined' && typeof window.moment != 'undefined') ? window.moment : require('moment'); module.exports = factory(moment, jQuery); } else { // Browser globals root.daterangepicker = factory(root.moment, root.jQuery); } }(this, function(moment, $) { var DateRangePicker = function(element, options, cb) { //default settings for options this.parentEl = 'body'; this.element = $(element); this.startDate = moment().startOf('day'); this.endDate = moment().endOf('day'); this.minDate = false; this.maxDate = false; this.maxSpan = false; this.autoApply = false; this.singleDatePicker = false; this.showDropdowns = false; this.minYear = moment().subtract(100, 'year').format('YYYY'); this.maxYear = moment().add(100, 'year').format('YYYY'); this.showWeekNumbers = false; this.showISOWeekNumbers = false; this.showCustomRangeLabel = true; this.timePicker = false; this.timePicker24Hour = false; this.timePickerIncrement = 1; this.timePickerSeconds = false; this.linkedCalendars = true; this.autoUpdateInput = true; this.alwaysShowCalendars = false; this.ranges = {}; this.opens = 'right'; if (this.element.hasClass('pull-right')) this.opens = 'left'; this.drops = 'down'; if (this.element.hasClass('dropup')) this.drops = 'up'; this.buttonClasses = 'btn btn-sm'; this.applyButtonClasses = 'btn-primary'; this.cancelButtonClasses = 'btn-default'; this.locale = { direction: 'ltr', format: moment.localeData().longDateFormat('L'), separator: ' - ', applyLabel: 'Apply', cancelLabel: 'Cancel', weekLabel: 'W', customRangeLabel: 'Custom Range', daysOfWeek: moment.weekdaysMin(), monthNames: moment.monthsShort(), firstDay: moment.localeData().firstDayOfWeek() }; this.callback = function() { }; //some state information this.isShowing = false; this.leftCalendar = {}; this.rightCalendar = {}; //custom options from user if (typeof options !== 'object' || options === null) options = {}; //allow setting options with data attributes //data-api options will be overwritten with custom javascript options options = $.extend(this.element.data(), options); //html template for the picker UI if (typeof options.template !== 'string' && !(options.template instanceof $)) options.template = '<div class="daterangepicker">' + '<div class="ranges"></div>' + '<div class="calendar left">' + '<div class="calendar-table"></div>' + '<div class="calendar-time"></div>' + '</div>' + '<div class="calendar right">' + '<div class="calendar-table"></div>' + '<div class="calendar-time"></div>' + '</div>' + '<div class="drp-buttons">' + '<span class="drp-selected"></span>' + '<button class="cancelBtn" type="button"></button>' + '<button class="applyBtn" disabled="disabled" type="button"></button> ' + '</div>' + '</div>'; this.parentEl = (options.parentEl && $(options.parentEl).length) ? $(options.parentEl) : $(this.parentEl); this.container = $(options.template).appendTo(this.parentEl); // // handle all the possible options overriding defaults // if (typeof options.locale === 'object') { if (typeof options.locale.direction === 'string') this.locale.direction = options.locale.direction; if (typeof options.locale.format === 'string') this.locale.format = options.locale.format; if (typeof options.locale.separator === 'string') this.locale.separator = options.locale.separator; if (typeof options.locale.daysOfWeek === 'object') this.locale.daysOfWeek = options.locale.daysOfWeek.slice(); if (typeof options.locale.monthNames === 'object') this.locale.monthNames = options.locale.monthNames.slice(); if (typeof options.locale.firstDay === 'number') this.locale.firstDay = options.locale.firstDay; if (typeof options.locale.applyLabel === 'string') this.locale.applyLabel = options.locale.applyLabel; if (typeof options.locale.cancelLabel === 'string') this.locale.cancelLabel = options.locale.cancelLabel; if (typeof options.locale.weekLabel === 'string') this.locale.weekLabel = options.locale.weekLabel; if (typeof options.locale.customRangeLabel === 'string'){ //Support unicode chars in the custom range name. var elem = document.createElement('textarea'); elem.innerHTML = options.locale.customRangeLabel; var rangeHtml = elem.value; this.locale.customRangeLabel = rangeHtml; } } this.container.addClass(this.locale.direction); if (typeof options.startDate === 'string') this.startDate = moment(options.startDate, this.locale.format); if (typeof options.endDate === 'string') this.endDate = moment(options.endDate, this.locale.format); if (typeof options.minDate === 'string') this.minDate = moment(options.minDate, this.locale.format); if (typeof options.maxDate === 'string') this.maxDate = moment(options.maxDate, this.locale.format); if (typeof options.startDate === 'object') this.startDate = moment(options.startDate); if (typeof options.endDate === 'object') this.endDate = moment(options.endDate); if (typeof options.minDate === 'object') this.minDate = moment(options.minDate); if (typeof options.maxDate === 'object') this.maxDate = moment(options.maxDate); // sanity check for bad options if (this.minDate && this.startDate.isBefore(this.minDate)) this.startDate = this.minDate.clone(); // sanity check for bad options if (this.maxDate && this.endDate.isAfter(this.maxDate)) this.endDate = this.maxDate.clone(); if (typeof options.applyButtonClasses === 'string') this.applyButtonClasses = options.applyButtonClasses; if (typeof options.applyClass === 'string') //backwards compat this.applyButtonClasses = options.applyClass; if (typeof options.cancelButtonClasses === 'string') this.cancelButtonClasses = options.cancelButtonClasses; if (typeof options.cancelClass === 'string') //backwards compat this.cancelButtonClasses = options.cancelClass; if (typeof options.maxSpan === 'object') this.maxSpan = options.maxSpan; if (typeof options.dateLimit === 'object') //backwards compat this.maxSpan = options.dateLimit; if (typeof options.opens === 'string') this.opens = options.opens; if (typeof options.drops === 'string') this.drops = options.drops; if (typeof options.showWeekNumbers === 'boolean') this.showWeekNumbers = options.showWeekNumbers; if (typeof options.showISOWeekNumbers === 'boolean') this.showISOWeekNumbers = options.showISOWeekNumbers; if (typeof options.buttonClasses === 'string') this.buttonClasses = options.buttonClasses; if (typeof options.buttonClasses === 'object') this.buttonClasses = options.buttonClasses.join(' '); if (typeof options.showDropdowns === 'boolean') this.showDropdowns = options.showDropdowns; if (typeof options.minYear === 'number') this.minYear = options.minYear; if (typeof options.maxYear === 'number') this.maxYear = options.maxYear; if (typeof options.showCustomRangeLabel === 'boolean') this.showCustomRangeLabel = options.showCustomRangeLabel; if (typeof options.singleDatePicker === 'boolean') { this.singleDatePicker = options.singleDatePicker; if (this.singleDatePicker) this.endDate = this.startDate.clone(); } if (typeof options.timePicker === 'boolean') this.timePicker = options.timePicker; if (typeof options.timePickerSeconds === 'boolean') this.timePickerSeconds = options.timePickerSeconds; if (typeof options.timePickerIncrement === 'number') this.timePickerIncrement = options.timePickerIncrement; if (typeof options.timePicker24Hour === 'boolean') this.timePicker24Hour = options.timePicker24Hour; if (typeof options.autoApply === 'boolean') this.autoApply = options.autoApply; if (typeof options.autoUpdateInput === 'boolean') this.autoUpdateInput = options.autoUpdateInput; if (typeof options.linkedCalendars === 'boolean') this.linkedCalendars = options.linkedCalendars; if (typeof options.isInvalidDate === 'function') this.isInvalidDate = options.isInvalidDate; if (typeof options.isCustomDate === 'function') this.isCustomDate = options.isCustomDate; if (typeof options.alwaysShowCalendars === 'boolean') this.alwaysShowCalendars = options.alwaysShowCalendars; // update day names order to firstDay if (this.locale.firstDay != 0) { var iterator = this.locale.firstDay; while (iterator > 0) { this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift()); iterator--; } } var start, end, range; //if no start/end dates set, check if an input element contains initial values if (typeof options.startDate === 'undefined' && typeof options.endDate === 'undefined') { if ($(this.element).is('input[type=text]')) { var val = $(this.element).val(), split = val.split(this.locale.separator); start = end = null; if (split.length == 2) { start = moment(split[0], this.locale.format); end = moment(split[1], this.locale.format); } else if (this.singleDatePicker && val !== "") { start = moment(val, this.locale.format); end = moment(val, this.locale.format); } if (start !== null && end !== null) { this.setStartDate(start); this.setEndDate(end); } } } if (typeof options.ranges === 'object') { for (range in options.ranges) { if (typeof options.ranges[range][0] === 'string') start = moment(options.ranges[range][0], this.locale.format); else start = moment(options.ranges[range][0]); if (typeof options.ranges[range][1] === 'string') end = moment(options.ranges[range][1], this.locale.format); else end = moment(options.ranges[range][1]); // If the start or end date exceed those allowed by the minDate or maxSpan // options, shorten the range to the allowable period. if (this.minDate && start.isBefore(this.minDate)) start = this.minDate.clone(); var maxDate = this.maxDate; if (this.maxSpan && maxDate && start.clone().add(this.maxSpan).isAfter(maxDate)) maxDate = start.clone().add(this.maxSpan); if (maxDate && end.isAfter(maxDate)) end = maxDate.clone(); // If the end of the range is before the minimum or the start of the range is // after the maximum, don't display this range option at all. if ((this.minDate && end.isBefore(this.minDate, this.timepicker ? 'minute' : 'day')) || (maxDate && start.isAfter(maxDate, this.timepicker ? 'minute' : 'day'))) continue; //Support unicode chars in the range names. var elem = document.createElement('textarea'); elem.innerHTML = range; var rangeHtml = elem.value; this.ranges[rangeHtml] = [start, end]; } var list = '<ul>'; for (range in this.ranges) { list += '<li data-range-key="' + range + '">' + range + '</li>'; } if (this.showCustomRangeLabel) { list += '<li data-range-key="' + this.locale.customRangeLabel + '">' + this.locale.customRangeLabel + '</li>'; } list += '</ul>'; this.container.find('.ranges').prepend(list); } if (typeof cb === 'function') { this.callback = cb; } if (!this.timePicker) { this.startDate = this.startDate.startOf('day'); this.endDate = this.endDate.endOf('day'); this.container.find('.calendar-time').hide(); } //can't be used together for now if (this.timePicker && this.autoApply) this.autoApply = false; if (this.autoApply) { this.container.addClass('auto-apply'); } if (typeof options.ranges === 'object') this.container.addClass('show-ranges'); if (this.singleDatePicker) { this.container.addClass('single'); this.container.find('.calendar.left').addClass('single'); this.container.find('.calendar.left').show(); this.container.find('.calendar.right').hide(); if (!this.timePicker) { this.container.addClass('auto-apply'); } } if ((typeof options.ranges === 'undefined' && !this.singleDatePicker) || this.alwaysShowCalendars) { this.container.addClass('show-calendar'); } this.container.addClass('opens' + this.opens); //apply CSS classes and labels to buttons this.container.find('.applyBtn, .cancelBtn').addClass(this.buttonClasses); if (this.applyButtonClasses.length) this.container.find('.applyBtn').addClass(this.applyButtonClasses); if (this.cancelButtonClasses.length) this.container.find('.cancelBtn').addClass(this.cancelButtonClasses); this.container.find('.applyBtn').html(this.locale.applyLabel); this.container.find('.cancelBtn').html(this.locale.cancelLabel); // // event listeners // this.container.find('.calendar') .on('click.daterangepicker', '.prev', $.proxy(this.clickPrev, this)) .on('click.daterangepicker', '.next', $.proxy(this.clickNext, this)) .on('mousedown.daterangepicker', 'td.available', $.proxy(this.clickDate, this)) .on('change.daterangepicker', 'select.yearselect', $.proxy(this.monthOrYearChanged, this)) .on('change.daterangepicker', 'select.monthselect', $.proxy(this.monthOrYearChanged, this)) .on('change.daterangepicker', 'select.hourselect,select.minuteselect,select.secondselect,select.ampmselect', $.proxy(this.timeChanged, this)) this.container.find('.ranges') .on('click.daterangepicker', 'li', $.proxy(this.clickRange, this)) this.container.find('.drp-buttons') .on('click.daterangepicker', 'button.applyBtn', $.proxy(this.clickApply, this)) .on('click.daterangepicker', 'button.cancelBtn', $.proxy(this.clickCancel, this)) if (this.element.is('input') || this.element.is('button')) { this.element.on({ 'click.daterangepicker': $.proxy(this.show, this), 'focus.daterangepicker': $.proxy(this.show, this), 'keyup.daterangepicker': $.proxy(this.elementChanged, this), 'keydown.daterangepicker': $.proxy(this.keydown, this) //IE 11 compatibility }); } else { this.element.on('click.daterangepicker', $.proxy(this.toggle, this)); this.element.on('keydown.daterangepicker', $.proxy(this.toggle, this)); } // // if attached to a text input, set the initial value // if (this.element.is('input') && !this.singleDatePicker && this.autoUpdateInput) { this.element.val(this.startDate.format(this.locale.format) + this.locale.separator + this.endDate.format(this.locale.format)); this.element.trigger('change'); } else if (this.element.is('input') && this.autoUpdateInput) { this.element.val(this.startDate.format(this.locale.format)); this.element.trigger('change'); } }; DateRangePicker.prototype = { constructor: DateRangePicker, setStartDate: function(startDate) { if (typeof startDate === 'string') this.startDate = moment(startDate, this.locale.format); if (typeof startDate === 'object') this.startDate = moment(startDate); if (!this.timePicker) this.startDate = this.startDate.startOf('day'); if (this.timePicker && this.timePickerIncrement) this.startDate.minute(Math.round(this.startDate.minute() / this.timePickerIncrement) * this.timePickerIncrement); if (this.minDate && this.startDate.isBefore(this.minDate)) { this.startDate = this.minDate.clone(); if (this.timePicker && this.timePickerIncrement) this.startDate.minute(Math.round(this.startDate.minute() / this.timePickerIncrement) * this.timePickerIncrement); } if (this.maxDate && this.startDate.isAfter(this.maxDate)) { this.startDate = this.maxDate.clone(); if (this.timePicker && this.timePickerIncrement) this.startDate.minute(Math.floor(this.startDate.minute() / this.timePickerIncrement) * this.timePickerIncrement); } if (!this.isShowing) this.updateElement(); this.updateMonthsInView(); }, setEndDate: function(endDate) { if (typeof endDate === 'string') this.endDate = moment(endDate, this.locale.format); if (typeof endDate === 'object') this.endDate = moment(endDate); if (!this.timePicker) this.endDate = this.endDate.add(1,'d').startOf('day').subtract(1,'second'); if (this.timePicker && this.timePickerIncrement) this.endDate.minute(Math.round(this.endDate.minute() / this.timePickerIncrement) * this.timePickerIncrement); if (this.endDate.isBefore(this.startDate)) this.endDate = this.startDate.clone(); if (this.maxDate && this.endDate.isAfter(this.maxDate)) this.endDate = this.maxDate.clone(); if (this.maxSpan && this.startDate.clone().add(this.maxSpan).isBefore(this.endDate)) this.endDate = this.startDate.clone().add(this.maxSpan); this.previousRightTime = this.endDate.clone(); this.container.find('.drp-selected').html(this.startDate.format(this.locale.format) + this.locale.separator + this.endDate.format(this.locale.format)); if (!this.isShowing) this.updateElement(); this.updateMonthsInView(); }, isInvalidDate: function() { return false; }, isCustomDate: function() { return false; }, updateView: function() { if (this.timePicker) { this.renderTimePicker('left'); this.renderTimePicker('right'); if (!this.endDate) { this.container.find('.right .calendar-time select').attr('disabled', 'disabled').addClass('disabled'); } else { this.container.find('.right .calendar-time select').removeAttr('disabled').removeClass('disabled'); } } if (this.endDate) this.container.find('.drp-selected').html(this.startDate.format(this.locale.format) + this.locale.separator + this.endDate.format(this.locale.format)); this.updateMonthsInView(); this.updateCalendars(); this.updateFormInputs(); }, updateMonthsInView: function() { if (this.endDate) { //if both dates are visible already, do nothing if (!this.singleDatePicker && this.leftCalendar.month && this.rightCalendar.month && (this.startDate.format('YYYY-MM') == this.leftCalendar.month.format('YYYY-MM') || this.startDate.format('YYYY-MM') == this.rightCalendar.month.format('YYYY-MM')) && (this.endDate.format('YYYY-MM') == this.leftCalendar.month.format('YYYY-MM') || this.endDate.format('YYYY-MM') == this.rightCalendar.month.format('YYYY-MM')) ) { return; } this.leftCalendar.month = this.startDate.clone().date(2); if (!this.linkedCalendars && (this.endDate.month() != this.startDate.month() || this.endDate.year() != this.startDate.year())) { this.rightCalendar.month = this.endDate.clone().date(2); } else { this.rightCalendar.month = this.startDate.clone().date(2).add(1, 'month'); } } else { if (this.leftCalendar.month.format('YYYY-MM') != this.startDate.format('YYYY-MM') && this.rightCalendar.month.format('YYYY-MM') != this.startDate.format('YYYY-MM')) { this.leftCalendar.month = this.startDate.clone().date(2); this.rightCalendar.month = this.startDate.clone().date(2).add(1, 'month'); } } if (this.maxDate && this.linkedCalendars && !this.singleDatePicker && this.rightCalendar.month > this.maxDate) { this.rightCalendar.month = this.maxDate.clone().date(2); this.leftCalendar.month = this.maxDate.clone().date(2).subtract(1, 'month'); } }, updateCalendars: function() { if (this.timePicker) { var hour, minute, second; if (this.endDate) { hour = parseInt(this.container.find('.left .hourselect').val(), 10); minute = parseInt(this.container.find('.left .minuteselect').val(), 10); second = this.timePickerSeconds ? parseInt(this.container.find('.left .secondselect').val(), 10) : 0; if (!this.timePicker24Hour) { var ampm = this.container.find('.left .ampmselect').val(); if (ampm === 'PM' && hour < 12) hour += 12; if (ampm === 'AM' && hour === 12) hour = 0; } } else { hour = parseInt(this.container.find('.right .hourselect').val(), 10); minute = parseInt(this.container.find('.right .minuteselect').val(), 10); second = this.timePickerSeconds ? parseInt(this.container.find('.right .secondselect').val(), 10) : 0; if (!this.timePicker24Hour) { var ampm = this.container.find('.right .ampmselect').val(); if (ampm === 'PM' && hour < 12) hour += 12; if (ampm === 'AM' && hour === 12) hour = 0; } } this.leftCalendar.month.hour(hour).minute(minute).second(second); this.rightCalendar.month.hour(hour).minute(minute).second(second); } this.renderCalendar('left'); this.renderCalendar('right'); //highlight any predefined range matching the current start and end dates this.container.find('.ranges li').removeClass('active'); if (this.endDate == null) return; this.calculateChosenLabel(); }, renderCalendar: function(side) { // // Build the matrix of dates that will populate the calendar // var calendar = side == 'left' ? this.leftCalendar : this.rightCalendar; var month = calendar.month.month(); var year = calendar.month.year(); var hour = calendar.month.hour(); var minute = calendar.month.minute(); var second = calendar.month.second(); var daysInMonth = moment([year, month]).daysInMonth(); var firstDay = moment([year, month, 1]); var lastDay = moment([year, month, daysInMonth]); var lastMonth = moment(firstDay).subtract(1, 'month').month(); var lastYear = moment(firstDay).subtract(1, 'month').year(); var daysInLastMonth = moment([lastYear, lastMonth]).daysInMonth(); var dayOfWeek = firstDay.day(); //initialize a 6 rows x 7 columns array for the calendar var calendar = []; calendar.firstDay = firstDay; calendar.lastDay = lastDay; for (var i = 0; i < 6; i++) { calendar[i] = []; } //populate the calendar with date objects var startDay = daysInLastMonth - dayOfWeek + this.locale.firstDay + 1; if (startDay > daysInLastMonth) startDay -= 7; if (dayOfWeek == this.locale.firstDay) startDay = daysInLastMonth - 6; var curDate = moment([lastYear, lastMonth, startDay, 12, minute, second]); var col, row; for (var i = 0, col = 0, row = 0; i < 42; i++, col++, curDate = moment(curDate).add(24, 'hour')) { if (i > 0 && col % 7 === 0) { col = 0; row++; } calendar[row][col] = curDate.clone().hour(hour).minute(minute).second(second); curDate.hour(12); if (this.minDate && calendar[row][col].format('YYYY-MM-DD') == this.minDate.format('YYYY-MM-DD') && calendar[row][col].isBefore(this.minDate) && side == 'left') { calendar[row][col] = this.minDate.clone(); } if (this.maxDate && calendar[row][col].format('YYYY-MM-DD') == this.maxDate.format('YYYY-MM-DD') && calendar[row][col].isAfter(this.maxDate) && side == 'right') { calendar[row][col] = this.maxDate.clone(); } } //make the calendar object available to hoverDate/clickDate if (side == 'left') { this.leftCalendar.calendar = calendar; } else { this.rightCalendar.calendar = calendar; } // // Display the calendar // var minDate = side == 'left' ? this.minDate : this.startDate; var maxDate = this.maxDate; var selected = side == 'left' ? this.startDate : this.endDate; var arrow = this.locale.direction == 'ltr' ? {left: 'chevron-left', right: 'chevron-right'} : {left: 'chevron-right', right: 'chevron-left'}; var html = '<table class="table-condensed">'; html += '<thead>'; html += '<tr>'; // add empty cell for week number if (this.showWeekNumbers || this.showISOWeekNumbers) html += '<th></th>'; if ((!minDate || minDate.isBefore(calendar.firstDay)) && (!this.linkedCalendars || side == 'left')) { html += '<th class="prev available"><span></span></th>'; } else { html += '<th></th>'; } var dateHtml = this.locale.monthNames[calendar[1][1].month()] + calendar[1][1].format(" YYYY"); if (this.showDropdowns) { var currentMonth = calendar[1][1].month(); var currentYear = calendar[1][1].year(); var maxYear = (maxDate && maxDate.year()) || (this.maxYear); var minYear = (minDate && minDate.year()) || (this.minYear); var inMinYear = currentYear == minYear; var inMaxYear = currentYear == maxYear; var monthHtml = '<select class="monthselect">'; for (var m = 0; m < 12; m++) { if ((!inMinYear || m >= minDate.month()) && (!inMaxYear || m <= maxDate.month())) { monthHtml += "<option value='" + m + "'" + (m === currentMonth ? " selected='selected'" : "") + ">" + this.locale.monthNames[m] + "</option>"; } else { monthHtml += "<option value='" + m + "'" + (m === currentMonth ? " selected='selected'" : "") + " disabled='disabled'>" + this.locale.monthNames[m] + "</option>"; } } monthHtml += "</select>"; var yearHtml = '<select class="yearselect">'; for (var y = minYear; y <= maxYear; y++) { yearHtml += '<option value="' + y + '"' + (y === currentYear ? ' selected="selected"' : '') + '>' + y + '</option>'; } yearHtml += '</select>'; dateHtml = monthHtml + yearHtml; } html += '<th colspan="5" class="month">' + dateHtml + '</th>'; if ((!maxDate || maxDate.isAfter(calendar.lastDay)) && (!this.linkedCalendars || side == 'right' || this.singleDatePicker)) { html += '<th class="next available"><span></span></th>'; } else { html += '<th></th>'; } html += '</tr>'; html += '<tr>'; // add week number label if (this.showWeekNumbers || this.showISOWeekNumbers) html += '<th class="week">' + this.locale.weekLabel + '</th>'; $.each(this.locale.daysOfWeek, function(index, dayOfWeek) { html += '<th>' + dayOfWeek + '</th>'; }); html += '</tr>'; html += '</thead>'; html += '<tbody>'; //adjust maxDate to reflect the maxSpan setting in order to //grey out end dates beyond the maxSpan if (this.endDate == null && this.maxSpan) { var maxLimit = this.startDate.clone().add(this.maxSpan).endOf('day'); if (!maxDate || maxLimit.isBefore(maxDate)) { maxDate = maxLimit; } } for (var row = 0; row < 6; row++) { html += '<tr>'; // add week number if (this.showWeekNumbers) html += '<td class="week">' + calendar[row][0].week() + '</td>'; else if (this.showISOWeekNumbers) html += '<td class="week">' + calendar[row][0].isoWeek() + '</td>'; for (var col = 0; col < 7; col++) { var classes = []; //highlight today's date if (calendar[row][col].isSame(new Date(), "day")) classes.push('today'); //highlight weekends if (calendar[row][col].isoWeekday() > 5) classes.push('weekend'); //grey out the dates in other months displayed at beginning and end of this calendar if (calendar[row][col].month() != calendar[1][1].month()) classes.push('off'); //don't allow selection of dates before the minimum date if (this.minDate && calendar[row][col].isBefore(this.minDate, 'day')) classes.push('off', 'disabled'); //don't allow selection of dates after the maximum date if (maxDate && calendar[row][col].isAfter(maxDate, 'day')) classes.push('off', 'disabled'); //don't allow selection of date if a custom function decides it's invalid if (this.isInvalidDate(calendar[row][col])) classes.push('off', 'disabled'); //highlight the currently selected start date if (calendar[row][col].format('YYYY-MM-DD') == this.startDate.format('YYYY-MM-DD')) classes.push('active', 'start-date'); //highlight the currently selected end date if (this.endDate != null && calendar[row][col].format('YYYY-MM-DD') == this.endDate.format('YYYY-MM-DD')) classes.push('active', 'end-date'); //highlight dates in-between the selected dates if (this.endDate != null && calendar[row][col] > this.startDate && calendar[row][col] < this.endDate) classes.push('in-range'); //apply custom classes for this date var isCustom = this.isCustomDate(calendar[row][col]); if (isCustom !== false) { if (typeof isCustom === 'string') classes.push(isCustom); else Array.prototype.push.apply(classes, isCustom); } var cname = '', disabled = false; for (var i = 0; i < classes.length; i++) { cname += classes[i] + ' '; if (classes[i] == 'disabled') disabled = true; } if (!disabled) cname += 'available'; html += '<td class="' + cname.replace(/^\s+|\s+$/g, '') + '" data-title="' + 'r' + row + 'c' + col + '">' + calendar[row][col].date() + '</td>'; } html += '</tr>'; } html += '</tbody>'; html += '</table>'; this.container.find('.calendar.' + side + ' .calendar-table').html(html); }, renderTimePicker: function(side) { // Don't bother updating the time picker if it's currently disabled // because an end date hasn't been clicked yet if (side == 'right' && !this.endDate) return; var html, selected, minDate, maxDate = this.maxDate; if (this.maxSpan && (!this.maxDate || this.startDate.clone().add(this.maxSpan).isAfter(this.maxDate))) maxDate = this.startDate.clone().add(this.maxSpan); if (side == 'left') { selected = this.startDate.clone(); minDate = this.minDate; } else if (side == 'right') { selected = this.endDate.clone(); minDate = this.startDate; //Preserve the time already selected var timeSelector = this.container.find('.calendar.right .calendar-time'); if (timeSelector.html() != '') { selected.hour(selected.hour() || timeSelector.find('.hourselect option:selected').val()); selected.minute(selected.minute() || timeSelector.find('.minuteselect option:selected').val()); selected.second(selected.second() || timeSelector.find('.secondselect option:selected').val()); if (!this.timePicker24Hour) { var ampm = timeSelector.find('.ampmselect option:selected').val(); if (ampm === 'PM' && selected.hour() < 12) selected.hour(selected.hour() + 12); if (ampm === 'AM' && selected.hour() === 12) selected.hour(0); } } if (selected.isBefore(this.startDate)) selected = this.startDate.clone(); if (maxDate && selected.isAfter(maxDate)) selected = maxDate.clone(); } // // hours // html = '<select class="hourselect">'; var start = this.timePicker24Hour ? 0 : 1; var end = this.timePicker24Hour ? 23 : 12; for (var i = start; i <= end; i++) { var i_in_24 = i; if (!this.timePicker24Hour) i_in_24 = selected.hour() >= 12 ? (i == 12 ? 12 : i + 12) : (i == 12 ? 0 : i); var time = selected.clone().hour(i_in_24); var disabled = false; if (minDate && time.minute(59).isBefore(minDate)) disabled = true; if (maxDate && time.minute(0).isAfter(maxDate)) disabled = true; if (i_in_24 == selected.hour() && !disabled) { html += '<option value="' + i + '" selected="selected">' + i + '</option>'; } else if (disabled) { html += '<option value="' + i + '" disabled="disabled" class="disabled">' + i + '</option>'; } else { html += '<option value="' + i + '">' + i + '</option>'; } } html += '</select> '; // // minutes // html += ': <select class="minuteselect">'; for (var i = 0; i < 60; i += this.timePickerIncrement) { var padded = i < 10 ? '0' + i : i; var time = selected.clone().minute(i); var disabled = false; if (minDate && time.second(59).isBefore(minDate)) disabled = true; if (maxDate && time.second(0).isAfter(maxDate)) disabled = true; if (selected.minute() == i && !disabled) { html += '<option value="' + i + '" selected="selected">' + padded + '</option>'; } else if (disabled) { html += '<option value="' + i + '" disabled="disabled" class="disabled">' + padded + '</option>'; } else { html += '<option value="' + i + '">' + padded + '</option>'; } } html += '</select> '; // // seconds // if (this.timePickerSeconds) { html += ': <select class="secondselect">'; for (var i = 0; i < 60; i++) { var padded = i < 10 ? '0' + i : i; var time = selected.clone().second(i); var disabled = false; if (minDate && time.isBefore(minDate)) disabled = true; if (maxDate && time.isAfter(maxDate)) disabled = true; if (selected.second() == i && !disabled) { html += '<option value="' + i + '" selected="selected">' + padded + '</option>'; } else if (disabled) { html += '<option value="' + i + '" disabled="disabled" class="disabled">' + padded + '</option>'; } else { html += '<option value="' + i + '">' + padded + '</option>'; } } html += '</select> '; } // // AM/PM // if (!this.timePicker24Hour) { html += '<select class="ampmselect">'; var am_html = ''; var pm_html = ''; if (minDate && selected.clone().hour(12).minute(0).second(0).isBefore(minDate)) am_html = ' disabled="disabled" class="disabled"'; if (maxDate && selected.clone().hour(0).minute(0).second(0).isAfter(maxDate)) pm_html = ' disabled="disabled" class="disabled"'; if (selected.hour() >= 12) { html += '<option value="AM"' + am_html + '>AM</option><option value="PM" selected="selected"' + pm_html + '>PM</option>'; } else { html += '<option value="AM" selected="selected"' + am_html + '>AM</option><option value="PM"' + pm_html + '>PM</option>'; } html += '</select>'; } this.container.find('.calendar.' + side + ' .calendar-time').html(html); }, updateFormInputs: function() { if (this.singleDatePicker || (this.endDate && (this.startDate.isBefore(this.endDate) || this.startDate.isSame(this.endDate)))) { this.container.find('button.applyBtn').removeAttr('disabled'); } else { this.container.find('button.applyBtn').attr('disabled', 'disabled'); } }, move: function() { var parentOffset = { top: 0, left: 0 }, containerTop; var parentRightEdge = $(window).width(); if (!this.parentEl.is('body')) { parentOffset = { top: this.parentEl.offset().top - this.parentEl.scrollTop(), left: this.parentEl.offset().left - this.parentEl.scrollLeft() }; parentRightEdge = this.parentEl[0].clientWidth + this.parentEl.offset().left; } if (this.drops == 'up') containerTop = this.element.offset().top - this.container.outerHeight() - parentOffset.top; else containerTop = this.element.offset().top + this.element.outerHeight() - parentOffset.top; this.container[this.drops == 'up' ? 'addClass' : 'removeClass']('drop-up'); if (this.opens == 'left') { this.container.css({ top: containerTop, right: parentRightEdge - this.element.offset().left - this.element.outerWidth(), left: 'auto' }); if (this.container.offset().left < 0) { this.container.css({ right: 'auto', left: 9 }); } } else if (this.opens == 'center') { this.container.css({ top: containerTop, left: this.element.offset().left - parentOffset.left + this.element.outerWidth() / 2 - this.container.outerWidth() / 2, right: 'auto' }); if (this.container.offset().left < 0) { this.container.css({ right: 'auto', left: 9 }); } } else { this.container.css({ top: containerTop, left: this.element.offset().left - parentOffset.left, right: 'auto' }); if (this.container.offset().left + this.container.outerWidth() > $(window).width()) { this.container.css({ left: 'auto', right: 0 }); } } }, show: function(e) { if (this.isShowing) return; // Create a click proxy that is private to this instance of datepicker, for unbinding this._outsideClickProxy = $.proxy(function(e) { this.outsideClick(e); }, this); // Bind global datepicker mousedown for hiding and $(document) .on('mousedown.daterangepicker', this._outsideClickProxy) // also support mobile devices .on('touchend.daterangepicker', this._outsideClickProxy) // also explicitly play nice with Bootstrap dropdowns, which stopPropagation when clicking them .on('click.daterangepicker', '[data-toggle=dropdown]', this._outsideClickProxy) // and also close when focus changes to outside the picker (eg. tabbing between controls) .on('focusin.daterangepicker', this._outsideClickProxy); // Reposition the picker if the window is resized while it's open $(window).on('resize.daterangepicker', $.proxy(function(e) { this.move(e); }, this)); this.oldStartDate = this.startDate.clone(); this.oldEndDate = this.endDate.clone(); this.previousRightTime = this.endDate.clone(); this.updateView(); this.container.show(); this.move(); this.element.trigger('show.daterangepicker', this); this.isShowing = true; }, hide: function(e) { if (!this.isShowing) return; //incomplete date selection, revert to last values if (!this.endDate) { this.startDate = this.oldStartDate.clone(); this.endDate = this.oldEndDate.clone(); } //if a new date range was selected, invoke the user callback function if (!this.startDate.isSame(this.oldStartDate) || !this.endDate.isSame(this.oldEndDate)) this.callback(this.startDate.clone(), this.endDate.clone(), this.chosenLabel); //if picker is attached to a text input, update it this.updateElement(); $(document).off('.daterangepicker'); $(window).off('.daterangepicker'); this.container.hide(); this.element.trigger('hide.daterangepicker', this); this.isShowing = false; }, toggle: function(e) { if (this.isShowing) { this.hide(); } else { this.show(); } }, outsideClick: function(e) { var target = $(e.target); // if the page is clicked anywhere except within the daterangerpicker/button // itself then call this.hide() if ( // ie modal dialog fix e.type == "focusin" || target.closest(this.element).length || target.closest(this.container).length || target.closest('.calendar-table').length ) return; this.hide(); this.element.trigger('outsideClick.daterangepicker', this); }, showCalendars: function() { this.container.addClass('show-calendar'); this.move(); this.element.trigger('showCalendar.daterangepicker', this); }, hideCalendars: function() { this.container.removeClass('show-calendar'); this.element.trigger('hideCalendar.daterangepicker', this); }, clickRange: function(e) { var label = e.target.getAttribute('data-range-key'); this.chosenLabel = label; if (label == this.locale.customRangeLabel) { this.showCalendars(); } else { var dates = this.ranges[label]; this.startDate = dates[0]; this.endDate = dates[1]; if (!this.timePicker) { this.startDate.startOf('day'); this.endDate.endOf('day'); } if (!this.alwaysShowCalendars) this.hideCalendars(); this.clickApply(); } }, clickPrev: function(e) { var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { this.leftCalendar.month.subtract(1, 'month'); if (this.linkedCalendars) this.rightCalendar.month.subtract(1, 'month'); } else { this.rightCalendar.month.subtract(1, 'month'); } this.updateCalendars(); }, clickNext: function(e) { var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { this.leftCalendar.month.add(1, 'month'); } else { this.rightCalendar.month.add(1, 'month'); if (this.linkedCalendars) this.leftCalendar.month.add(1, 'month'); } this.updateCalendars(); }, hoverDate: function(e) { //ignore mouse movements while an above-calendar text input has focus //if (this.container.find('input[name=daterangepicker_start]').is(":focus") || this.container.find('input[name=daterangepicker_end]').is(":focus")) // return; //ignore dates that can't be selected if (!$(e.target).hasClass('available')) return; //have the text inputs above calendars reflect the date being hovered over var title = $(e.target).attr('data-title'); var row = title.substr(1, 1); var col = title.substr(3, 1); var cal = $(e.target).parents('.calendar'); var date = cal.hasClass('left') ? this.leftCalendar.calendar[row][col] : this.rightCalendar.calendar[row][col]; //highlight the dates between the start date and the date being hovered as a potential end date var leftCalendar = this.leftCalendar; var rightCalendar = this.rightCalendar; var startDate = this.startDate; if (!this.endDate) { this.container.find('.calendar tbody td').each(function(index, el) { //skip week numbers, only look at dates if ($(el).hasClass('week')) return; var title = $(el).attr('data-title'); var row = title.substr(1, 1); var col = title.substr(3, 1); var cal = $(el).parents('.calendar'); var dt = cal.hasClass('left') ? leftCalendar.calendar[row][col] : rightCalendar.calendar[row][col]; if ((dt.isAfter(startDate) && dt.isBefore(date)) || dt.isSame(date, 'day')) { $(el).addClass('in-range'); } else { $(el).removeClass('in-range'); } }); } }, clickDate: function(e) { if (!$(e.target).hasClass('available')) return; var title = $(e.target).attr('data-title'); var row = title.substr(1, 1); var col = title.substr(3, 1); var cal = $(e.target).parents('.calendar'); var date = cal.hasClass('left') ? this.leftCalendar.calendar[row][col] : this.rightCalendar.calendar[row][col]; // // this function needs to do a few things: // * alternate between selecting a start and end date for the range, // * if the time picker is enabled, apply the hour/minute/second from the select boxes to the clicked date // * if autoapply is enabled, and an end date was chosen, apply the selection // * if single date picker mode, and time picker isn't enabled, apply the selection immediately // * if one of the inputs above the calendars was focused, cancel that manual input // if (this.endDate || date.isBefore(this.startDate, 'day')) { //picking start if (this.timePicker) { var hour = parseInt(this.container.find('.left .hourselect').val(), 10); if (!this.timePicker24Hour) { var ampm = this.container.find('.left .ampmselect').val(); if (ampm === 'PM' && hour < 12) hour += 12; if (ampm === 'AM' && hour === 12) hour = 0; } var minute = parseInt(this.container.find('.left .minuteselect').val(), 10); var second = this.timePickerSeconds ? parseInt(this.container.find('.left .secondselect').val(), 10) : 0; date = date.clone().hour(hour).minute(minute).second(second); } this.endDate = null; this.setStartDate(date.clone()); } else if (!this.endDate && date.isBefore(this.startDate)) { //special case: clicking the same date for start/end, //but the time of the end date is before the start date this.setEndDate(this.startDate.clone()); } else { // picking end if (this.timePicker) { var hour = parseInt(this.container.find('.right .hourselect').val(), 10); if (!this.timePicker24Hour) { var ampm = this.container.find('.right .ampmselect').val(); if (ampm === 'PM' && hour < 12) hour += 12; if (ampm === 'AM' && hour === 12) hour = 0; } var minute = parseInt(this.container.find('.right .minuteselect').val(), 10); var second = this.timePickerSeconds ? parseInt(this.container.find('.right .secondselect').val(), 10) : 0; date = date.clone().hour(hour).minute(minute).second(second); } this.setEndDate(date.clone()); if (this.autoApply) { this.calculateChosenLabel(); this.clickApply(); } } if (this.singleDatePicker) { this.setEndDate(this.startDate); if (!this.timePicker) this.clickApply(); } this.updateView(); //This is to cancel the blur event handler if the mouse was in one of the inputs e.stopPropagation(); }, calculateChosenLabel: function () { var customRange = true; var i = 0; for (var range in this.ranges) { if (this.timePicker) { var format = this.timePickerSeconds ? "YYYY-MM-DD hh:mm:ss" : "YYYY-MM-DD hh:mm"; //ignore times when comparing dates if time picker seconds is not enabled if (this.startDate.format(format) == this.ranges[range][0].format(format) && this.endDate.format(format) == this.ranges[range][1].format(format)) { customRange = false; this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')').addClass('active').attr('data-range-key'); break; } } else { //ignore times when comparing dates if time picker is not enabled if (this.startDate.format('YYYY-MM-DD') == this.ranges[range][0].format('YYYY-MM-DD') && this.endDate.format('YYYY-MM-DD') == this.ranges[range][1].format('YYYY-MM-DD')) { customRange = false; this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')').addClass('active').attr('data-range-key'); break; } } i++; } if (customRange) { if (this.showCustomRangeLabel) { this.chosenLabel = this.container.find('.ranges li:last').addClass('active').attr('data-range-key'); } else { this.chosenLabel = null; } this.showCalendars(); } }, clickApply: function(e) { this.hide(); this.element.trigger('apply.daterangepicker', this); }, clickCancel: function(e) { this.startDate = this.oldStartDate; this.endDate = this.oldEndDate; this.hide(); this.element.trigger('cancel.daterangepicker', this); }, monthOrYearChanged: function(e) { var isLeft = $(e.target).closest('.calendar').hasClass('left'), leftOrRight = isLeft ? 'left' : 'right', cal = this.container.find('.calendar.'+leftOrRight); // Month must be Number for new moment versions var month = parseInt(cal.find('.monthselect').val(), 10); var year = cal.find('.yearselect').val(); if (!isLeft) { if (year < this.startDate.year() || (year == this.startDate.year() && month < this.startDate.month())) { month = this.startDate.month(); year = this.startDate.year(); } } if (this.minDate) { if (year < this.minDate.year() || (year == this.minDate.year() && month < this.minDate.month())) { month = this.minDate.month(); year = this.minDate.year(); } } if (this.maxDate) { if (year > this.maxDate.year() || (year == this.maxDate.year() && month > this.maxDate.month())) { month = this.maxDate.month(); year = this.maxDate.year(); } } if (isLeft) { this.leftCalendar.month.month(month).year(year); if (this.linkedCalendars) this.rightCalendar.month = this.leftCalendar.month.clone().add(1, 'month'); } else { this.rightCalendar.month.month(month).year(year); if (this.linkedCalendars) this.leftCalendar.month = this.rightCalendar.month.clone().subtract(1, 'month'); } this.updateCalendars(); }, timeChanged: function(e) { var cal = $(e.target).closest('.calendar'), isLeft = cal.hasClass('left'); var hour = parseInt(cal.find('.hourselect').val(), 10); var minute = parseInt(cal.find('.minuteselect').val(), 10); var second = this.timePickerSeconds ? parseInt(cal.find('.secondselect').val(), 10) : 0; if (!this.timePicker24Hour) { var ampm = cal.find('.ampmselect').val(); if (ampm === 'PM' && hour < 12) hour += 12; if (ampm === 'AM' && hour === 12) hour = 0; } if (isLeft) { var start = this.startDate.clone(); start.hour(hour); start.minute(minute); start.second(second); this.setStartDate(start); if (this.singleDatePicker) { this.endDate = this.startDate.clone(); } else if (this.endDate && this.endDate.format('YYYY-MM-DD') == start.format('YYYY-MM-DD') && this.endDate.isBefore(start)) { this.setEndDate(start.clone()); } } else if (this.endDate) { var end = this.endDate.clone(); end.hour(hour); end.minute(minute); end.second(second); this.setEndDate(end); } //update the calendars so all clickable dates reflect the new time component this.updateCalendars(); //update the form inputs above the calendars with the new time this.updateFormInputs(); //re-render the time pickers because changing one selection can affect what's enabled in another this.renderTimePicker('left'); this.renderTimePicker('right'); }, elementChanged: function() { if (!this.element.is('input')) return; if (!this.element.val().length) return; var dateString = this.element.val().split(this.locale.separator), start = null, end = null; if (dateString.length === 2) { start = moment(dateString[0], this.locale.format); end = moment(dateString[1], this.locale.format); } if (this.singleDatePicker || start === null || end === null) { start = moment(this.element.val(), this.locale.format); end = start; } if (!start.isValid() || !end.isValid()) return; this.setStartDate(start); this.setEndDate(end); this.updateView(); }, keydown: function(e) { //hide on tab or enter if ((e.keyCode === 9) || (e.keyCode === 13)) { this.hide(); } //hide on esc and prevent propagation if (e.keyCode === 27) { e.preventDefault(); e.stopPropagation(); this.hide(); } }, updateElement: function() { if (this.element.is('input') && !this.singleDatePicker && this.autoUpdateInput) { this.element.val(this.startDate.format(this.locale.format) + this.locale.separator + this.endDate.format(this.locale.format)); this.element.trigger('change'); } else if (this.element.is('input') && this.autoUpdateInput) { this.element.val(this.startDate.format(this.locale.format)); this.element.trigger('change'); } }, remove: function() { this.container.remove(); this.element.off('.daterangepicker'); this.element.removeData(); } }; $.fn.daterangepicker = function(options, callback) { var implementOptions = $.extend(true, {}, $.fn.daterangepicker.defaultOptions, options); this.each(function() { var el = $(this); if (el.data('daterangepicker')) el.data('daterangepicker').remove(); el.data('daterangepicker', new DateRangePicker(el, implementOptions, callback)); }); return this; }; return DateRangePicker; }));
//var lsc = require("./lib/livescript.js"); var lsc = require("./livescript.js").LiveScript; var lineRegex = /on line (\d+)/; module.exports = function(info) { var text = info.inputs.text; try { lsc.compile(text); } catch (e) { var message = e.message; var match = lineRegex.exec(message); if (match) { var line = parseInt(match[1], 10); return [{ row: line, text: message.slice(0, match.index), type: "error" }]; } } return []; };
/*! * Bootstrap-select v1.13.7 (https://developer.snapappointments.com/bootstrap-select) * * Copyright 2012-2019 SnapAppointments, LLC * Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE) */ !function(e,o){void 0===e&&void 0!==window&&(e=window),"function"==typeof define&&define.amd?define(["jquery"],function(e){return o(e)}):"object"==typeof module&&module.exports?module.exports=o(require("jquery")):o(e.jQuery)}(this,function(e){e.fn.selectpicker.defaults={noneSelectedText:"No hay selecci\xf3n",noneResultsText:"No hay resultados {0}",countSelectedText:"Seleccionados {0} de {1}",maxOptionsText:["L\xedmite alcanzado ({n} {var} max)","L\xedmite del grupo alcanzado({n} {var} max)",["elementos","element"]],multipleSeparator:", ",selectAllText:"Seleccionar Todos",deselectAllText:"Desmarcar Todos"}});
/** * \@whatItDoes Represents the version of Angular * * \@stable */ export var Version = (function () { /** * @param {?} full */ function Version(full) { this.full = full; } Object.defineProperty(Version.prototype, "major", { /** * @return {?} */ get: function () { return this.full.split('.')[0]; }, enumerable: true, configurable: true }); Object.defineProperty(Version.prototype, "minor", { /** * @return {?} */ get: function () { return this.full.split('.')[1]; }, enumerable: true, configurable: true }); Object.defineProperty(Version.prototype, "patch", { /** * @return {?} */ get: function () { return this.full.split('.').slice(2).join('.'); }, enumerable: true, configurable: true }); return Version; }()); function Version_tsickle_Closure_declarations() { /** @type {?} */ Version.prototype.full; } /** * @stable */ export var /** @type {?} */ VERSION = new Version('2.4.8'); //# sourceMappingURL=version.js.map
define( //begin v1.x content { "field-quarter-short-relative+0": "dit kwartaal", "field-quarter-short-relative+1": "volgend kwartaal", "field-tue-relative+-1": "afgelopen dinsdag", "field-year": "jaar", "field-wed-relative+0": "deze woensdag", "field-wed-relative+1": "volgende week woensdag", "field-minute": "minuut", "field-month-narrow-relative+-1": "vorige maand", "field-tue-narrow-relative+0": "deze di", "field-tue-narrow-relative+1": "volgende week di", "field-day-short-relative+-1": "gisteren", "field-thu-short-relative+0": "deze donder.", "dateTimeFormat-short": "{1} {0}", "field-day-relative+0": "vandaag", "field-day-short-relative+-2": "eergisteren", "field-thu-short-relative+1": "volgende week donder.", "field-day-relative+1": "morgen", "field-week-narrow-relative+0": "deze week", "field-day-relative+2": "overmorgen", "field-week-narrow-relative+1": "volgende week", "field-wed-narrow-relative+-1": "afgelopen wo", "field-year-narrow": "jr", "field-era-short": "tijdperk", "field-year-narrow-relative+0": "dit jaar", "field-tue-relative+0": "deze dinsdag", "field-year-narrow-relative+1": "volgend jaar", "field-tue-relative+1": "volgende week dinsdag", "field-weekdayOfMonth": "weekdag van de maand", "field-second-short": "sec", "dateFormatItem-MMMd": "d MMM", "field-weekdayOfMonth-narrow": "wkdag v.d. mnd", "field-week-relative+0": "deze week", "field-month-relative+0": "deze maand", "field-week-relative+1": "volgende week", "field-month-relative+1": "volgende maand", "field-sun-narrow-relative+0": "deze zo", "field-mon-short-relative+0": "deze maan.", "field-sun-narrow-relative+1": "volgende week zo", "field-mon-short-relative+1": "volgende week maan.", "field-second-relative+0": "nu", "dateFormatItem-yyyyQQQ": "QQQ r (U)", "months-standAlone-narrow": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" ], "field-weekOfMonth": "week van de maand", "field-month-short": "mnd", "dateFormatItem-GyMMMEd": "E d MMM r (U)", "dateFormatItem-yyyyMd": "d-M-r", "field-day": "dag", "field-dayOfYear-short": "dag van het jr", "field-year-relative+-1": "vorig jaar", "field-sat-short-relative+-1": "afgelopen zater.", "field-hour-relative+0": "binnen een uur", "dateFormatItem-yyyyMEd": "E d-M-r", "field-second-short-relative+0": "nu", "field-wed-relative+-1": "afgelopen woensdag", "dateTimeFormat-medium": "{1} {0}", "field-sat-narrow-relative+-1": "afgelopen za", "field-second": "seconde", "dateFormat-long": "d MMMM r (U)", "dateFormatItem-GyMMMd": "d MMM r", "field-hour-short-relative+0": "binnen een uur", "field-quarter": "kwartaal", "field-week-short": "wk", "field-day-narrow-relative+0": "vandaag", "field-day-narrow-relative+1": "morgen", "field-day-narrow-relative+2": "overmorgen", "field-tue-short-relative+0": "deze dins.", "field-tue-short-relative+1": "volgende week dins.", "field-month-short-relative+-1": "vorige maand", "field-mon-relative+-1": "afgelopen maandag", "dateFormatItem-GyMMM": "MMM r (U)", "field-month": "maand", "field-day-narrow": "dag", "dateFormatItem-MMM": "LLL", "field-minute-short": "min", "field-dayperiod": "a.m./p.m.", "field-sat-short-relative+0": "deze zater.", "field-sat-short-relative+1": "volgende week zater.", "dateFormat-medium": "d MMM r", "dateFormatItem-yyyyMMMM": "MMMM r (U)", "dateFormatItem-UMMM": "MMM U", "dateFormatItem-yyyyM": "M-r", "field-second-narrow": "s", "field-mon-relative+0": "deze maandag", "field-mon-relative+1": "volgende week maandag", "field-day-narrow-relative+-1": "gisteren", "field-year-short": "jr", "field-day-narrow-relative+-2": "eergisteren", "months-format-narrow": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" ], "field-quarter-relative+-1": "vorig kwartaal", "dateFormatItem-yyyyMMMd": "d MMM r", "field-dayperiod-narrow": "a.m./p.m.", "field-week-narrow-relative+-1": "vorige week", "field-dayOfYear": "dag van het jaar", "field-sat-relative+-1": "afgelopen zaterdag", "dateTimeFormat-long": "{1} 'om' {0}", "dateFormatItem-Md": "d-M", "field-hour": "uur", "field-minute-narrow-relative+0": "binnen een minuut", "months-format-wide": [ "maand 1", "maand 2", "maand 3", "maand 4", "maand 5", "maand 6", "maand 7", "maand 8", "maand 9", "maand 10", "maand 11", "maand 12" ], "dateFormat-full": "EEEE d MMMM r (U)", "dateFormatItem-UMd": "d-MM U", "field-month-relative+-1": "vorige maand", "field-quarter-short": "kwartaal", "field-sat-narrow-relative+0": "deze za", "field-fri-relative+0": "deze vrijdag", "field-sat-narrow-relative+1": "volgende week za", "field-fri-relative+1": "volgende week vrijdag", "field-month-narrow-relative+0": "deze maand", "field-month-narrow-relative+1": "volgende maand", "field-sun-short-relative+0": "deze zon.", "field-sun-short-relative+1": "volgende week zon.", "field-week-relative+-1": "vorige week", "field-quarter-short-relative+-1": "vorig kwartaal", "field-minute-short-relative+0": "binnen een minuut", "months-format-abbr": [ "mnd 1", "mnd 2", "mnd 3", "mnd 4", "mnd 5", "mnd 6", "mnd 7", "mnd 8", "mnd 9", "mnd 10", "mnd 11", "mnd 12" ], "field-quarter-relative+0": "dit kwartaal", "field-minute-relative+0": "binnen een minuut", "field-quarter-relative+1": "volgend kwartaal", "field-wed-short-relative+-1": "afgelopen woens.", "dateFormat-short": "dd-MM-r", "field-year-narrow-relative+-1": "vorig jaar", "field-thu-short-relative+-1": "afgelopen donder.", "dateFormatItem-yyyyMMMEd": "E d MMM r (U)", "field-mon-narrow-relative+-1": "afgelopen ma", "dateFormatItem-MMMMd": "d MMMM", "field-thu-narrow-relative+-1": "afgelopen do", "dateFormatItem-E": "ccc", "field-weekOfMonth-short": "wk van de mnd", "field-tue-narrow-relative+-1": "afgelopen di", "dateFormatItem-yyyy": "r (U)", "dateFormatItem-M": "L", "months-standAlone-wide": [ "maand 1", "maand 2", "maand 3", "maand 4", "maand 5", "maand 6", "maand 7", "maand 8", "maand 9", "maand 10", "maand 11", "maand 12" ], "field-wed-short-relative+0": "deze woens.", "field-wed-short-relative+1": "volgende week woens.", "field-sun-relative+-1": "afgelopen zondag", "dateTimeFormat-full": "{1} 'om' {0}", "field-second-narrow-relative+0": "nu", "dateFormatItem-d": "d", "field-weekday": "dag van de week", "field-day-short-relative+0": "vandaag", "field-quarter-narrow-relative+0": "dit kwartaal", "field-day-short-relative+1": "morgen", "field-sat-relative+0": "deze zaterdag", "field-quarter-narrow-relative+1": "volgend kwartaal", "field-day-short-relative+2": "overmorgen", "field-sat-relative+1": "volgende week zaterdag", "field-week-short-relative+0": "deze week", "field-week-short-relative+1": "volgende week", "months-standAlone-abbr": [ "mnd 1", "mnd 2", "mnd 3", "mnd 4", "mnd 5", "mnd 6", "mnd 7", "mnd 8", "mnd 9", "mnd 10", "mnd 11", "mnd 12" ], "field-dayOfYear-narrow": "dag v.h. jr", "field-month-short-relative+0": "deze maand", "field-month-short-relative+1": "volgende maand", "field-weekdayOfMonth-short": "wkdag van de mnd", "dateFormatItem-MEd": "E d-M", "field-zone-narrow": "zone", "dateFormatItem-y": "r (U)", "field-thu-narrow-relative+0": "deze do", "field-sun-narrow-relative+-1": "afgelopen zo", "field-mon-short-relative+-1": "afgelopen maan.", "field-thu-narrow-relative+1": "volgende week do", "field-thu-relative+0": "deze donderdag", "field-thu-relative+1": "volgende week donderdag", "field-fri-short-relative+-1": "afgelopen vrij.", "field-thu-relative+-1": "afgelopen donderdag", "dateFormatItem-yMd": "d-M-r", "field-week": "week", "dateFormatItem-Ed": "E d", "field-wed-narrow-relative+0": "deze wo", "field-wed-narrow-relative+1": "volgende week wo", "field-quarter-narrow-relative+-1": "vorig kwartaal", "field-year-short-relative+0": "dit jaar", "dateFormatItem-yyyyMMM": "MMM r (U)", "field-dayperiod-short": "a.m./p.m.", "field-year-short-relative+1": "volgend jaar", "field-fri-short-relative+0": "deze vrij.", "field-fri-short-relative+1": "volgende week vrij.", "field-week-short-relative+-1": "vorige week", "field-hour-narrow-relative+0": "binnen een uur", "dateFormatItem-yyyyQQQQ": "QQQQ r (U)", "dateFormatItem-UMMMd": "d MMM U", "field-hour-short": "uur", "field-zone-short": "zone", "field-month-narrow": "mnd", "field-hour-narrow": "u", "field-fri-narrow-relative+-1": "afgelopen vr", "field-year-relative+0": "dit jaar", "field-year-relative+1": "volgend jaar", "field-era-narrow": "tijdperk", "field-fri-relative+-1": "afgelopen vrijdag", "field-tue-short-relative+-1": "afgelopen dins.", "field-minute-narrow": "min", "field-mon-narrow-relative+0": "deze ma", "field-mon-narrow-relative+1": "volgende week ma", "field-year-short-relative+-1": "vorig jaar", "field-zone": "tijdzone", "dateFormatItem-MMMEd": "E d MMM", "field-weekOfMonth-narrow": "wk v.d. mnd", "field-weekday-narrow": "dag v.d. wk", "field-quarter-narrow": "kwartaal", "field-sun-short-relative+-1": "afgelopen zon.", "field-day-relative+-1": "gisteren", "field-day-relative+-2": "eergisteren", "field-weekday-short": "dag van de wk", "field-sun-relative+0": "deze zondag", "field-sun-relative+1": "volgende week zondag", "dateFormatItem-Gy": "r (U)", "field-day-short": "dag", "field-week-narrow": "wk", "field-era": "tijdperk", "field-fri-narrow-relative+0": "deze vr", "dateFormatItem-UM": "MM U", "field-fri-narrow-relative+1": "volgende week vr" } //end v1.x content );
define( //begin v1.x content { "field-quarter-short-relative+0": "dit kwartaal", "field-quarter-short-relative+1": "volgend kwartaal", "field-tue-relative+-1": "afgelopen dinsdag", "field-year": "jaar", "field-wed-relative+0": "deze woensdag", "field-wed-relative+1": "volgende week woensdag", "field-minute": "minuut", "field-month-narrow-relative+-1": "vorige maand", "field-tue-narrow-relative+0": "deze di", "field-tue-narrow-relative+1": "volgende week di", "field-thu-short-relative+0": "deze donder.", "field-day-short-relative+-1": "gisteren", "field-thu-short-relative+1": "volgende week donder.", "field-day-relative+0": "vandaag", "field-day-short-relative+-2": "eergisteren", "field-day-relative+1": "morgen", "field-week-narrow-relative+0": "deze week", "field-day-relative+2": "overmorgen", "field-week-narrow-relative+1": "volgende week", "field-wed-narrow-relative+-1": "afgelopen wo", "field-year-narrow": "jr", "field-era-short": "tijdperk", "field-year-narrow-relative+0": "dit jaar", "field-tue-relative+0": "deze dinsdag", "field-year-narrow-relative+1": "volgend jaar", "field-tue-relative+1": "volgende week dinsdag", "field-weekdayOfMonth": "weekdag van de maand", "field-second-short": "sec", "field-weekdayOfMonth-narrow": "wkdag v.d. mnd", "field-week-relative+0": "deze week", "field-month-relative+0": "deze maand", "field-week-relative+1": "volgende week", "field-month-relative+1": "volgende maand", "field-sun-narrow-relative+0": "deze zo", "field-mon-short-relative+0": "deze maan.", "field-sun-narrow-relative+1": "volgende week zo", "field-mon-short-relative+1": "volgende week maan.", "field-second-relative+0": "nu", "eraNames": [ "tijdperk 0" ], "field-weekOfMonth": "week van de maand", "field-month-short": "mnd", "field-day": "dag", "field-dayOfYear-short": "dag van het jr", "field-year-relative+-1": "vorig jaar", "field-sat-short-relative+-1": "afgelopen zater.", "field-hour-relative+0": "binnen een uur", "field-second-short-relative+0": "nu", "field-wed-relative+-1": "afgelopen woensdag", "field-sat-narrow-relative+-1": "afgelopen za", "field-second": "seconde", "field-hour-short-relative+0": "binnen een uur", "field-quarter": "kwartaal", "field-week-short": "wk", "field-day-narrow-relative+0": "vandaag", "field-day-narrow-relative+1": "morgen", "field-day-narrow-relative+2": "overmorgen", "field-tue-short-relative+0": "deze dins.", "field-tue-short-relative+1": "volgende week dins.", "field-month-short-relative+-1": "vorige maand", "field-mon-relative+-1": "afgelopen maandag", "field-month": "maand", "field-day-narrow": "dag", "field-minute-short": "min", "field-dayperiod": "a.m./p.m.", "field-sat-short-relative+0": "deze zater.", "field-sat-short-relative+1": "volgende week zater.", "eraAbbr": [ "era 0" ], "field-second-narrow": "s", "field-mon-relative+0": "deze maandag", "field-mon-relative+1": "volgende week maandag", "field-day-narrow-relative+-1": "gisteren", "field-year-short": "jr", "field-day-narrow-relative+-2": "eergisteren", "field-quarter-relative+-1": "vorig kwartaal", "field-dayperiod-narrow": "a.m./p.m.", "field-week-narrow-relative+-1": "vorige week", "field-dayOfYear": "dag van het jaar", "field-sat-relative+-1": "afgelopen zaterdag", "field-hour": "uur", "field-minute-narrow-relative+0": "binnen een minuut", "field-month-relative+-1": "vorige maand", "field-quarter-short": "kwartaal", "field-sat-narrow-relative+0": "deze za", "field-fri-relative+0": "deze vrijdag", "field-sat-narrow-relative+1": "volgende week za", "field-fri-relative+1": "volgende week vrijdag", "field-month-narrow-relative+0": "deze maand", "field-month-narrow-relative+1": "volgende maand", "field-sun-short-relative+0": "deze zon.", "field-sun-short-relative+1": "volgende week zon.", "field-week-relative+-1": "vorige week", "field-quarter-short-relative+-1": "vorig kwartaal", "field-minute-short-relative+0": "binnen een minuut", "field-quarter-relative+0": "dit kwartaal", "field-minute-relative+0": "binnen een minuut", "field-quarter-relative+1": "volgend kwartaal", "field-wed-short-relative+-1": "afgelopen woens.", "field-thu-short-relative+-1": "afgelopen donder.", "field-year-narrow-relative+-1": "vorig jaar", "field-mon-narrow-relative+-1": "afgelopen ma", "field-thu-narrow-relative+-1": "afgelopen do", "field-tue-narrow-relative+-1": "afgelopen di", "field-weekOfMonth-short": "wk van de mnd", "field-wed-short-relative+0": "deze woens.", "field-wed-short-relative+1": "volgende week woens.", "field-sun-relative+-1": "afgelopen zondag", "field-second-narrow-relative+0": "nu", "field-weekday": "dag van de week", "field-day-short-relative+0": "vandaag", "field-quarter-narrow-relative+0": "dit kwartaal", "field-sat-relative+0": "deze zaterdag", "field-day-short-relative+1": "morgen", "field-quarter-narrow-relative+1": "volgend kwartaal", "field-sat-relative+1": "volgende week zaterdag", "field-day-short-relative+2": "overmorgen", "field-week-short-relative+0": "deze week", "field-week-short-relative+1": "volgende week", "field-dayOfYear-narrow": "dag v.h. jr", "field-month-short-relative+0": "deze maand", "field-month-short-relative+1": "volgende maand", "field-weekdayOfMonth-short": "wkdag van de mnd", "field-zone-narrow": "zone", "field-thu-narrow-relative+0": "deze do", "field-thu-narrow-relative+1": "volgende week do", "field-sun-narrow-relative+-1": "afgelopen zo", "field-mon-short-relative+-1": "afgelopen maan.", "field-thu-relative+0": "deze donderdag", "field-thu-relative+1": "volgende week donderdag", "field-fri-short-relative+-1": "afgelopen vrij.", "field-thu-relative+-1": "afgelopen donderdag", "field-week": "week", "field-wed-narrow-relative+0": "deze wo", "field-wed-narrow-relative+1": "volgende week wo", "field-quarter-narrow-relative+-1": "vorig kwartaal", "field-year-short-relative+0": "dit jaar", "field-dayperiod-short": "a.m./p.m.", "field-year-short-relative+1": "volgend jaar", "field-fri-short-relative+0": "deze vrij.", "field-fri-short-relative+1": "volgende week vrij.", "field-week-short-relative+-1": "vorige week", "field-hour-narrow-relative+0": "binnen een uur", "field-hour-short": "uur", "field-zone-short": "zone", "field-month-narrow": "mnd", "field-hour-narrow": "u", "field-fri-narrow-relative+-1": "afgelopen vr", "field-year-relative+0": "dit jaar", "field-year-relative+1": "volgend jaar", "field-era-narrow": "tijdperk", "field-fri-relative+-1": "afgelopen vrijdag", "eraNarrow": "era 0", "field-tue-short-relative+-1": "afgelopen dins.", "field-minute-narrow": "min", "field-mon-narrow-relative+0": "deze ma", "field-mon-narrow-relative+1": "volgende week ma", "field-year-short-relative+-1": "vorig jaar", "field-zone": "tijdzone", "field-weekOfMonth-narrow": "wk v.d. mnd", "field-weekday-narrow": "dag v.d. wk", "field-quarter-narrow": "kwartaal", "field-sun-short-relative+-1": "afgelopen zon.", "field-day-relative+-1": "gisteren", "field-day-relative+-2": "eergisteren", "field-weekday-short": "dag van de wk", "field-sun-relative+0": "deze zondag", "field-sun-relative+1": "volgende week zondag", "field-day-short": "dag", "field-week-narrow": "wk", "field-era": "tijdperk", "field-fri-narrow-relative+0": "deze vr", "field-fri-narrow-relative+1": "volgende week vr" } //end v1.x content );
// 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. /** * @fileoverview Unit tests for goog.position. * * @author eae@google.com (Emil A Eklund) */ /** @suppress {extraProvide} */ goog.provide('goog.positioningTest'); goog.require('goog.dom'); goog.require('goog.dom.DomHelper'); goog.require('goog.math.Box'); goog.require('goog.math.Coordinate'); goog.require('goog.math.Size'); goog.require('goog.positioning'); goog.require('goog.positioning.Corner'); goog.require('goog.positioning.Overflow'); goog.require('goog.positioning.OverflowStatus'); goog.require('goog.style'); goog.require('goog.testing.ExpectedFailures'); goog.require('goog.testing.jsunit'); goog.require('goog.userAgent'); goog.require('goog.userAgent.product'); goog.setTestOnly('goog.positioningTest'); // Allow positions to be off by one in gecko as it reports scrolling // offsets in steps of 2. Otherwise, allow for subpixel difference // as seen in IE10+ var ALLOWED_OFFSET = goog.userAgent.GECKO ? 1 : 0.1; // Error bar for positions since some browsers are not super accurate // in reporting them. var EPSILON = 2; var expectedFailures = new goog.testing.ExpectedFailures(); var corner = goog.positioning.Corner; var overflow = goog.positioning.Overflow; var testArea; function setUp() { window.scrollTo(0, 0); var viewportSize = goog.dom.getViewportSize(); // Some tests need enough size viewport. if (viewportSize.width < 600 || viewportSize.height < 600) { window.moveTo(0, 0); window.resizeTo(640, 640); } testArea = goog.dom.getElement('test-area'); } function tearDown() { expectedFailures.handleTearDown(); testArea.setAttribute('style', ''); testArea.innerHTML = ''; } /** * This is used to round pixel values on FF3 Mac. */ function assertRoundedEquals(a, b, c) { function round(x) { return goog.userAgent.GECKO && (goog.userAgent.MAC || goog.userAgent.X11) && goog.userAgent.isVersionOrHigher('1.9') ? Math.round(x) : x; } if (arguments.length == 3) { assertRoughlyEquals(a, round(b), round(c), ALLOWED_OFFSET); } else { assertRoughlyEquals(round(a), round(b), ALLOWED_OFFSET); } } function testPositionAtAnchorLeftToRight() { var anchor = document.getElementById('anchor1'); var popup = document.getElementById('popup1'); // Anchor top left to top left. goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT, popup, corner.TOP_LEFT); var anchorRect = goog.style.getBounds(anchor); var popupRect = goog.style.getBounds(popup); assertRoundedEquals('Left edge of popup should line up with left edge ' + 'of anchor.', anchorRect.left, popupRect.left); assertRoundedEquals('Popup should have the same y position as the anchor.', anchorRect.top, popupRect.top); // Anchor top left to bottom left. goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_LEFT, popup, corner.TOP_LEFT); anchorRect = goog.style.getBounds(anchor); popupRect = goog.style.getBounds(popup); assertRoundedEquals('Left edge of popup should line up with left edge ' + 'of anchor.', anchorRect.left, popupRect.left); assertRoundedEquals('Popup should be positioned just below the anchor.', anchorRect.top + anchorRect.height, popupRect.top); // Anchor top left to top right. goog.positioning.positionAtAnchor(anchor, corner.TOP_RIGHT, popup, corner.TOP_LEFT); anchorRect = goog.style.getBounds(anchor); popupRect = goog.style.getBounds(popup); assertRoundedEquals('Popup should be positioned just right of the anchor.', anchorRect.left + anchorRect.width, popupRect.left); assertRoundedEquals('Popup should have the same y position as the anchor.', anchorRect.top, popupRect.top); // Anchor top right to bottom right. goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_RIGHT, popup, corner.TOP_RIGHT); anchorRect = goog.style.getBounds(anchor); popupRect = goog.style.getBounds(popup); assertRoundedEquals('Right edge of popup should line up with right edge ' + 'of anchor.', anchorRect.left + anchorRect.width, popupRect.left + popupRect.width); assertRoundedEquals('Popup should be positioned just below the anchor.', anchorRect.top + anchorRect.height, popupRect.top); // Anchor top start to bottom start. goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_START, popup, corner.TOP_START); anchorRect = goog.style.getBounds(anchor); popupRect = goog.style.getBounds(popup); assertRoundedEquals('Left edge of popup should line up with left edge ' + 'of anchor.', anchorRect.left, popupRect.left); assertRoundedEquals('Popup should be positioned just below the anchor.', anchorRect.top + anchorRect.height, popupRect.top); } function testPositionAtAnchorWithOffset() { var anchor = document.getElementById('anchor1'); var popup = document.getElementById('popup1'); // Anchor top left to top left with an offset moving the popup away from the // anchor. goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT, popup, corner.TOP_LEFT, newCoord(-15, -20)); var anchorRect = goog.style.getBounds(anchor); var popupRect = goog.style.getBounds(popup); assertRoundedEquals('Left edge of popup should be fifteen pixels from ' + 'anchor.', anchorRect.left, popupRect.left + 15); assertRoundedEquals('Top edge of popup should be twenty pixels from anchor.', anchorRect.top, popupRect.top + 20); // Anchor top left to top left with an offset moving the popup towards the // anchor. goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT, popup, corner.TOP_LEFT, newCoord(3, 1)); anchorRect = goog.style.getBounds(anchor); popupRect = goog.style.getBounds(popup); assertRoundedEquals('Left edge of popup should be three pixels right of ' + 'the anchor\'s left edge', anchorRect.left, popupRect.left - 3); assertRoundedEquals('Top edge of popup should be one pixel below of the ' + 'anchor\'s top edge', anchorRect.top, popupRect.top - 1); } function testPositionAtAnchorOverflowLeftEdgeRightToLeft() { var anchor = document.getElementById('anchor5'); var popup = document.getElementById('popup5'); var status = goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT, popup, corner.TOP_RIGHT, undefined, undefined, overflow.FAIL_X); assertFalse('Positioning operation should have failed.', (status & goog.positioning.OverflowStatus.FAILED) == 0); // Change overflow strategy to ADJUST. status = goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT, popup, corner.TOP_RIGHT, undefined, undefined, overflow.ADJUST_X); // Fails in Chrome because of infrastructure issues, temporarily disabled. // See b/4274723. expectedFailures.expectFailureFor(goog.userAgent.product.CHROME); try { assertTrue('Positioning operation should have been successful.', (status & goog.positioning.OverflowStatus.FAILED) == 0); assertTrue('Positioning operation should have been adjusted.', (status & goog.positioning.OverflowStatus.ADJUSTED_X) != 0); } catch (e) { expectedFailures.handleException(e); } var anchorRect = goog.style.getBounds(anchor); var popupRect = goog.style.getBounds(popup); var parentRect = goog.style.getBounds(anchor.parentNode); assertTrue('Position should have been adjusted so that the left edge of ' + 'the popup is left of the anchor but still within the bounding ' + 'box of the parent container.', anchorRect.left <= popupRect.left <= parentRect.left); } function testPositionAtAnchorWithMargin() { var anchor = document.getElementById('anchor1'); var popup = document.getElementById('popup1'); // Anchor top left to top left. goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT, popup, corner.TOP_LEFT, undefined, new goog.math.Box(1, 2, 3, 4)); var anchorRect = goog.style.getBounds(anchor); var popupRect = goog.style.getBounds(popup); assertRoundedEquals('Left edge of popup should be four pixels from anchor.', anchorRect.left, popupRect.left - 4); assertRoundedEquals('Top edge of popup should be one pixels from anchor.', anchorRect.top, popupRect.top - 1); // Anchor top right to bottom right. goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_RIGHT, popup, corner.TOP_RIGHT, undefined, new goog.math.Box(1, 2, 3, 4)); anchorRect = goog.style.getBounds(anchor); popupRect = goog.style.getBounds(popup); var visibleAnchorRect = goog.positioning.getVisiblePart_(anchor); assertRoundedEquals('Right edge of popup should line up with right edge ' + 'of anchor.', visibleAnchorRect.left + visibleAnchorRect.width, popupRect.left + popupRect.width + 2); assertRoundedEquals('Popup should be positioned just below the anchor.', visibleAnchorRect.top + visibleAnchorRect.height, popupRect.top - 1); } function testPositionAtAnchorRightToLeft() { if (goog.userAgent.IE && goog.userAgent.isVersionOrHigher('6')) { // These tests fails with IE6. // TODO(user): Investigate the reason. return; } var anchor = document.getElementById('anchor2'); var popup = document.getElementById('popup2'); // Anchor top left to top left. goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT, popup, corner.TOP_LEFT); var anchorRect = goog.style.getBounds(anchor); var popupRect = goog.style.getBounds(popup); assertRoundedEquals('Left edge of popup should line up with left edge ' + 'of anchor.', anchorRect.left, popupRect.left); assertRoundedEquals('Popup should have the same y position as the anchor.', anchorRect.top, popupRect.top); // Anchor top start to bottom start. goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_START, popup, corner.TOP_START); anchorRect = goog.style.getBounds(anchor); popupRect = goog.style.getBounds(popup); assertRoundedEquals('Right edge of popup should line up with right edge ' + 'of anchor.', anchorRect.left + anchorRect.width, popupRect.left + popupRect.width); assertRoundedEquals('Popup should be positioned just below the anchor.', anchorRect.top + anchorRect.height, popupRect.top); } function testPositionAtAnchorRightToLeftWithScroll() { if (goog.userAgent.IE && goog.userAgent.isVersionOrHigher('6')) { // These tests fails with IE6. // TODO(user): Investigate the reason. return; } var anchor = document.getElementById('anchor8'); var popup = document.getElementById('popup8'); // Anchor top left to top left. goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT, popup, corner.TOP_LEFT); var anchorRect = goog.style.getBounds(anchor); var popupRect = goog.style.getBounds(popup); assertRoundedEquals('Left edge of popup should line up with left edge ' + 'of anchor.', anchorRect.left, popupRect.left); assertRoundedEquals('Popup should have the same y position as the anchor.', anchorRect.top, popupRect.top); // Anchor top start to bottom start. goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_START, popup, corner.TOP_START); anchorRect = goog.style.getBounds(anchor); popupRect = goog.style.getBounds(popup); var visibleAnchorRect = goog.positioning.getVisiblePart_(anchor); var visibleAnchorBox = visibleAnchorRect.toBox(); assertRoundedEquals('Right edge of popup should line up with right edge ' + 'of anchor.', anchorRect.left + anchorRect.width, popupRect.left + popupRect.width); assertRoundedEquals('Popup should be positioned just below the anchor.', visibleAnchorBox.bottom, popupRect.top); } function testPositionAtAnchorBodyViewport() { var anchor = document.getElementById('anchor1'); var popup = document.getElementById('popup3'); // Anchor top left to top left. goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT, popup, corner.TOP_LEFT); var anchorRect = goog.style.getBounds(anchor); var popupRect = goog.style.getBounds(popup); assertEquals('Left edge of popup should line up with left edge of anchor.', anchorRect.left, popupRect.left); assertRoughlyEquals('Popup should have the same y position as the anchor.', anchorRect.top, popupRect.top, 1); // Anchor top start to bottom right. goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_RIGHT, popup, corner.TOP_RIGHT); anchorRect = goog.style.getBounds(anchor); popupRect = goog.style.getBounds(popup); assertEquals('Right edge of popup should line up with right edge of anchor.', anchorRect.left + anchorRect.width, popupRect.left + popupRect.width); assertRoughlyEquals('Popup should be positioned just below the anchor.', anchorRect.top + anchorRect.height, popupRect.top, 1); // Anchor top right to top left. goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT, popup, corner.TOP_RIGHT); anchorRect = goog.style.getBounds(anchor); popupRect = goog.style.getBounds(popup); assertEquals('Right edge of popup should line up with left edge of anchor.', anchorRect.left, popupRect.left + popupRect.width); assertRoughlyEquals('Popup should have the same y position as the anchor.', anchorRect.top, popupRect.top, 1); } function testPositionAtAnchorSpecificViewport() { var anchor = document.getElementById('anchor1'); var popup = document.getElementById('popup3'); // Anchor top right to top left within outerbox. var status = goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT, popup, corner.TOP_RIGHT, undefined, undefined, overflow.FAIL_X); anchorRect = goog.style.getBounds(anchor); popupRect = goog.style.getBounds(popup); assertTrue('Positioning operation should have been successful.', (status & goog.positioning.OverflowStatus.FAILED) == 0); assertTrue('X position should not have been adjusted.', (status & goog.positioning.OverflowStatus.ADJUSTED_X) == 0); assertTrue('Y position should not have been adjusted.', (status & goog.positioning.OverflowStatus.ADJUSTED_Y) == 0); assertEquals('Right edge of popup should line up with left edge of anchor.', anchorRect.left, popupRect.left + popupRect.width); assertRoughlyEquals('Popup should have the same y position as the anchor.', anchorRect.top, popupRect.top, 1); // position again within box1. var box = document.getElementById('box1'); var viewport = goog.style.getBounds(box); status = goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT, popup, corner.TOP_RIGHT, undefined, undefined, overflow.FAIL_X, undefined, viewport); assertFalse('Positioning operation should have failed.', (status & goog.positioning.OverflowStatus.FAILED) == 0); // Change overflow strategy to adjust. status = goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT, popup, corner.TOP_RIGHT, undefined, undefined, overflow.ADJUST_X, undefined, viewport); anchorRect = goog.style.getBounds(anchor); popupRect = goog.style.getBounds(popup); assertTrue('Positioning operation should have been successful.', (status & goog.positioning.OverflowStatus.FAILED) == 0); assertFalse('X position should have been adjusted.', (status & goog.positioning.OverflowStatus.ADJUSTED_X) == 0); assertTrue('Y position should not have been adjusted.', (status & goog.positioning.OverflowStatus.ADJUSTED_Y) == 0); assertRoughlyEquals( 'Left edge of popup should line up with left edge of viewport.', viewport.left, popupRect.left, EPSILON); assertRoughlyEquals('Popup should have the same y position as the anchor.', anchorRect.top, popupRect.top, 1); } function testPositionAtAnchorOutsideViewport() { var anchor = document.getElementById('anchor4'); var popup = document.getElementById('popup1'); var status = goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT, popup, corner.TOP_RIGHT); var anchorRect = goog.style.getBounds(anchor); var popupRect = goog.style.getBounds(popup); assertTrue('Positioning operation should have been successful.', (status & goog.positioning.OverflowStatus.FAILED) == 0); assertTrue('X position should not have been adjusted.', (status & goog.positioning.OverflowStatus.ADJUSTED_X) == 0); assertTrue('Y position should not have been adjusted.', (status & goog.positioning.OverflowStatus.ADJUSTED_Y) == 0); assertEquals('Right edge of popup should line up with left edge of anchor.', anchorRect.left, popupRect.left + popupRect.width); // Change overflow strategy to fail. status = goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_RIGHT, popup, corner.TOP_RIGHT, undefined, undefined, overflow.FAIL_X); assertFalse('Positioning operation should have failed.', (status & goog.positioning.OverflowStatus.FAILED) == 0); // Change overflow strategy to adjust. status = goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_RIGHT, popup, corner.TOP_RIGHT, undefined, undefined, overflow.ADJUST_X); anchorRect = goog.style.getBounds(anchor); popupRect = goog.style.getBounds(popup); assertTrue('Positioning operation should have been successful.', (status & goog.positioning.OverflowStatus.FAILED) == 0); assertFalse('X position should have been adjusted.', (status & goog.positioning.OverflowStatus.ADJUSTED_X) == 0); assertTrue('Y position should not have been adjusted.', (status & goog.positioning.OverflowStatus.ADJUSTED_Y) == 0); assertRoughlyEquals( 'Left edge of popup should line up with left edge of viewport.', 0, popupRect.left, EPSILON); assertEquals('Popup should be positioned just below the anchor.', anchorRect.top + anchorRect.height, popupRect.top); } function testAdjustForViewportFailIgnore() { var f = goog.positioning.adjustForViewport_; var viewport = new goog.math.Box(100, 200, 200, 100); var overflow = goog.positioning.Overflow.IGNORE; var pos = newCoord(150, 150); var size = newSize(50, 50); assertEquals('Viewport overflow should be ignored.', goog.positioning.OverflowStatus.NONE, f(pos, size, viewport, overflow)); pos = newCoord(150, 150); size = newSize(100, 50); assertEquals('Viewport overflow should be ignored.', goog.positioning.OverflowStatus.NONE, f(pos, size, viewport, overflow)); pos = newCoord(50, 50); size = newSize(50, 50); assertEquals('Viewport overflow should be ignored.', goog.positioning.OverflowStatus.NONE, f(pos, size, viewport, overflow)); } function testAdjustForViewportFailXY() { var f = goog.positioning.adjustForViewport_; var viewport = new goog.math.Box(100, 200, 200, 100); var overflow = goog.positioning.Overflow.FAIL_X | goog.positioning.Overflow.FAIL_Y; var pos = newCoord(150, 150); var size = newSize(50, 50); assertEquals('Element should not overflow viewport.', goog.positioning.OverflowStatus.NONE, f(pos, size, viewport, overflow)); pos = newCoord(150, 150); size = newSize(100, 50); assertEquals('Element should overflow the right edge of viewport.', goog.positioning.OverflowStatus.FAILED_RIGHT, f(pos, size, viewport, overflow)); pos = newCoord(150, 150); size = newSize(50, 100); assertEquals('Element should overflow the bottom edge of viewport.', goog.positioning.OverflowStatus.FAILED_BOTTOM, f(pos, size, viewport, overflow)); pos = newCoord(50, 150); size = newSize(50, 50); assertEquals('Element should overflow the left edge of viewport.', goog.positioning.OverflowStatus.FAILED_LEFT, f(pos, size, viewport, overflow)); pos = newCoord(150, 50); size = newSize(50, 50); assertEquals('Element should overflow the top edge of viewport.', goog.positioning.OverflowStatus.FAILED_TOP, f(pos, size, viewport, overflow)); pos = newCoord(50, 50); size = newSize(50, 50); assertEquals('Element should overflow the left & top edges of viewport.', goog.positioning.OverflowStatus.FAILED_LEFT | goog.positioning.OverflowStatus.FAILED_TOP, f(pos, size, viewport, overflow)); } function testAdjustForViewportAdjustXFailY() { var f = goog.positioning.adjustForViewport_; var viewport = new goog.math.Box(100, 200, 200, 100); var overflow = goog.positioning.Overflow.ADJUST_X | goog.positioning.Overflow.FAIL_Y; var pos = newCoord(150, 150); var size = newSize(50, 50); assertEquals('Element should not overflow viewport.', goog.positioning.OverflowStatus.NONE, f(pos, size, viewport, overflow)); assertEquals('X Position should not have been changed.', 150, pos.x); assertEquals('Y Position should not have been changed.', 150, pos.y); pos = newCoord(150, 150); size = newSize(100, 50); assertEquals('Element position should be adjusted not to overflow right ' + 'edge of viewport.', goog.positioning.OverflowStatus.ADJUSTED_X, f(pos, size, viewport, overflow)); assertEquals('X Position should be adjusted to 100.', 100, pos.x); assertEquals('Y Position should not have been changed.', 150, pos.y); pos = newCoord(50, 150); size = newSize(100, 50); assertEquals('Element position should be adjusted not to overflow left ' + 'edge of viewport.', goog.positioning.OverflowStatus.ADJUSTED_X, f(pos, size, viewport, overflow)); assertEquals('X Position should be adjusted to 100.', 100, pos.x); assertEquals('Y Position should not have been changed.', 150, pos.y); pos = newCoord(50, 50); size = newSize(100, 50); assertEquals('Element position should be adjusted not to overflow left ' + 'edge of viewport, should overflow bottom edge.', goog.positioning.OverflowStatus.ADJUSTED_X | goog.positioning.OverflowStatus.FAILED_TOP, f(pos, size, viewport, overflow)); assertEquals('X Position should be adjusted to 100.', 100, pos.x); assertEquals('Y Position should not have been changed.', 50, pos.y); } function testAdjustForViewportResizeHeight() { var f = goog.positioning.adjustForViewport_; var viewport = new goog.math.Box(0, 200, 200, 0); var overflow = goog.positioning.Overflow.RESIZE_HEIGHT; var pos = newCoord(150, 150); var size = newSize(25, 100); assertEquals('Viewport height should be resized.', goog.positioning.OverflowStatus.HEIGHT_ADJUSTED, f(pos, size, viewport, overflow)); assertEquals('Height should be resized to 50.', 50, size.height); assertTrue('Output box is within viewport', viewport.contains(new goog.math.Box(pos.y, pos.x + size.width, pos.y + size.height, pos.x))); var pos = newCoord(0, 0); var size = newSize(50, 250); assertEquals('Viewport height should be resized.', goog.positioning.OverflowStatus.HEIGHT_ADJUSTED, f(pos, size, viewport, overflow)); assertEquals('Height should be resized to 200.', 200, size.height); assertTrue('Output box is within viewport', viewport.contains(new goog.math.Box(pos.y, pos.x + size.width, pos.y + size.height, pos.x))); var pos = newCoord(0, -50); var size = newSize(50, 240); assertEquals('Viewport height should be resized.', goog.positioning.OverflowStatus.HEIGHT_ADJUSTED, f(pos, size, viewport, overflow)); assertEquals('Height should be resized to 190.', 190, size.height); assertTrue('Output box is within viewport', viewport.contains(new goog.math.Box(pos.y, pos.x + size.width, pos.y + size.height, pos.x))); var pos = newCoord(0, -50); var size = newSize(50, 300); assertEquals('Viewport height should be resized.', goog.positioning.OverflowStatus.HEIGHT_ADJUSTED, f(pos, size, viewport, overflow)); assertEquals('Height should be resized to 200.', 200, size.height); assertTrue('Output box is within viewport', viewport.contains(new goog.math.Box(pos.y, pos.x + size.width, pos.y + size.height, pos.x))); pos = newCoord(150, 150); size = newSize(50, 50); assertEquals('No Viewport overflow.', goog.positioning.OverflowStatus.NONE, f(pos, size, viewport, overflow)); assertTrue('Output box is within viewport', viewport.contains(new goog.math.Box(pos.y, pos.x + size.width, pos.y + size.height, pos.x))); var offsetViewport = new goog.math.Box(100, 200, 300, 0); var pos = newCoord(0, 50); var size = newSize(50, 240); assertEquals('Viewport height should be resized.', goog.positioning.OverflowStatus.HEIGHT_ADJUSTED, f(pos, size, offsetViewport, overflow)); assertEquals('Height should be resized to 190.', 190, size.height); assertTrue('Output box is within viewport', offsetViewport.contains(new goog.math.Box(pos.y, pos.x + size.width, pos.y + size.height, pos.x))); } function testAdjustForViewportResizeWidth() { var f = goog.positioning.adjustForViewport_; var viewport = new goog.math.Box(0, 200, 200, 0); var overflow = goog.positioning.Overflow.RESIZE_WIDTH; var pos = newCoord(150, 150); var size = newSize(100, 25); assertEquals('Viewport width should be resized.', goog.positioning.OverflowStatus.WIDTH_ADJUSTED, f(pos, size, viewport, overflow)); assertEquals('Width should be resized to 50.', 50, size.width); assertTrue('Output box is within viewport', viewport.contains(new goog.math.Box(pos.y, pos.x + size.width, pos.y + size.height, pos.x))); var pos = newCoord(0, 0); var size = newSize(250, 50); assertEquals('Viewport width should be resized.', goog.positioning.OverflowStatus.WIDTH_ADJUSTED, f(pos, size, viewport, overflow)); assertEquals('Width should be resized to 200.', 200, size.width); assertTrue('Output box is within viewport', viewport.contains(new goog.math.Box(pos.y, pos.x + size.width, pos.y + size.height, pos.x))); var pos = newCoord(-50, 0); var size = newSize(240, 50); assertEquals('Viewport width should be resized.', goog.positioning.OverflowStatus.WIDTH_ADJUSTED, f(pos, size, viewport, overflow)); assertEquals('Width should be resized to 190.', 190, size.width); assertTrue('Output box is within viewport', viewport.contains(new goog.math.Box(pos.y, pos.x + size.width, pos.y + size.height, pos.x))); var pos = newCoord(-50, 0); var size = newSize(300, 50); assertEquals('Viewport width should be resized.', goog.positioning.OverflowStatus.WIDTH_ADJUSTED, f(pos, size, viewport, overflow)); assertEquals('Width should be resized to 200.', 200, size.width); assertTrue('Output box is within viewport', viewport.contains(new goog.math.Box(pos.y, pos.x + size.width, pos.y + size.height, pos.x))); pos = newCoord(150, 150); size = newSize(50, 50); assertEquals('No Viewport overflow.', goog.positioning.OverflowStatus.NONE, f(pos, size, viewport, overflow)); assertTrue('Output box is within viewport', viewport.contains(new goog.math.Box(pos.y, pos.x + size.width, pos.y + size.height, pos.x))); var offsetViewport = new goog.math.Box(0, 300, 200, 100); var pos = newCoord(50, 0); var size = newSize(240, 50); assertEquals('Viewport width should be resized.', goog.positioning.OverflowStatus.WIDTH_ADJUSTED, f(pos, size, offsetViewport, overflow)); assertEquals('Width should be resized to 190.', 190, size.width); assertTrue('Output box is within viewport', offsetViewport.contains(new goog.math.Box(pos.y, pos.x + size.width, pos.y + size.height, pos.x))); } function testPositionAtAnchorWithResizeHeight() { var anchor = document.getElementById('anchor9'); var popup = document.getElementById('popup9'); var box = document.getElementById('box9'); var viewport = goog.style.getBounds(box); var status = goog.positioning.positionAtAnchor( anchor, corner.TOP_START, popup, corner.TOP_START, new goog.math.Coordinate(0, -20), null, goog.positioning.Overflow.RESIZE_HEIGHT, null, viewport.toBox()); assertEquals('Status should be HEIGHT_ADJUSTED.', goog.positioning.OverflowStatus.HEIGHT_ADJUSTED, status); var TOLERANCE = 0.1; // Adjust the viewport to allow some tolerance for subpixel positioning, // this is required for this test to pass on IE10,11 viewport.top -= TOLERANCE; viewport.left -= TOLERANCE; assertTrue('Popup ' + goog.style.getBounds(popup) + ' not is within viewport' + viewport, viewport.contains(goog.style.getBounds(popup))); } function testPositionAtCoordinateResizeHeight() { var f = goog.positioning.positionAtCoordinate; var viewport = new goog.math.Box(0, 50, 50, 0); var overflow = goog.positioning.Overflow.RESIZE_HEIGHT | goog.positioning.Overflow.ADJUST_Y; var popup = document.getElementById('popup1'); var corner = goog.positioning.Corner.BOTTOM_LEFT; var pos = newCoord(100, 100); assertEquals('Viewport height should be resized.', goog.positioning.OverflowStatus.HEIGHT_ADJUSTED | goog.positioning.OverflowStatus.ADJUSTED_Y, f(pos, popup, corner, undefined, viewport, overflow)); var bounds = goog.style.getSize(popup); assertEquals('Height should be resized to the size of the viewport.', 50, bounds.height); } function testGetPositionAtCoordinateResizeHeight() { var f = goog.positioning.getPositionAtCoordinate; var viewport = new goog.math.Box(0, 50, 50, 0); var overflow = goog.positioning.Overflow.RESIZE_HEIGHT | goog.positioning.Overflow.ADJUST_Y; var popup = document.getElementById('popup1'); var corner = goog.positioning.Corner.BOTTOM_LEFT; var pos = newCoord(100, 100); var size = goog.style.getSize(popup); var result = f(pos, size, corner, undefined, viewport, overflow); assertEquals('Viewport height should be resized.', goog.positioning.OverflowStatus.HEIGHT_ADJUSTED | goog.positioning.OverflowStatus.ADJUSTED_Y, result.status); assertEquals('Height should be resized to the size of the viewport.', 50, result.rect.height); } function testGetEffectiveCornerLeftToRight() { var f = goog.positioning.getEffectiveCorner; var el = document.getElementById('ltr'); assertEquals('TOP_LEFT should be unchanged for ltr.', corner.TOP_LEFT, f(el, corner.TOP_LEFT)); assertEquals('TOP_RIGHT should be unchanged for ltr.', corner.TOP_RIGHT, f(el, corner.TOP_RIGHT)); assertEquals('BOTTOM_LEFT should be unchanged for ltr.', corner.BOTTOM_LEFT, f(el, corner.BOTTOM_LEFT)); assertEquals('BOTTOM_RIGHT should be unchanged for ltr.', corner.BOTTOM_RIGHT, f(el, corner.BOTTOM_RIGHT)); assertEquals('TOP_START should be TOP_LEFT for ltr.', corner.TOP_LEFT, f(el, corner.TOP_START)); assertEquals('TOP_END should be TOP_RIGHT for ltr.', corner.TOP_RIGHT, f(el, corner.TOP_END)); assertEquals('BOTTOM_START should be BOTTOM_LEFT for ltr.', corner.BOTTOM_LEFT, f(el, corner.BOTTOM_START)); assertEquals('BOTTOM_END should be BOTTOM_RIGHT for ltr.', corner.BOTTOM_RIGHT, f(el, corner.BOTTOM_END)); } function testGetEffectiveCornerRightToLeft() { var f = goog.positioning.getEffectiveCorner; var el = document.getElementById('rtl'); assertEquals('TOP_LEFT should be unchanged for rtl.', corner.TOP_LEFT, f(el, corner.TOP_LEFT)); assertEquals('TOP_RIGHT should be unchanged for rtl.', corner.TOP_RIGHT, f(el, corner.TOP_RIGHT)); assertEquals('BOTTOM_LEFT should be unchanged for rtl.', corner.BOTTOM_LEFT, f(el, corner.BOTTOM_LEFT)); assertEquals('BOTTOM_RIGHT should be unchanged for rtl.', corner.BOTTOM_RIGHT, f(el, corner.BOTTOM_RIGHT)); assertEquals('TOP_START should be TOP_RIGHT for rtl.', corner.TOP_RIGHT, f(el, corner.TOP_START)); assertEquals('TOP_END should be TOP_LEFT for rtl.', corner.TOP_LEFT, f(el, corner.TOP_END)); assertEquals('BOTTOM_START should be BOTTOM_RIGHT for rtl.', corner.BOTTOM_RIGHT, f(el, corner.BOTTOM_START)); assertEquals('BOTTOM_END should be BOTTOM_LEFT for rtl.', corner.BOTTOM_LEFT, f(el, corner.BOTTOM_END)); } function testFlipCornerHorizontal() { var f = goog.positioning.flipCornerHorizontal; assertEquals('TOP_LEFT should be flipped to TOP_RIGHT.', corner.TOP_RIGHT, f(corner.TOP_LEFT)); assertEquals('TOP_RIGHT should be flipped to TOP_LEFT.', corner.TOP_LEFT, f(corner.TOP_RIGHT)); assertEquals('BOTTOM_LEFT should be flipped to BOTTOM_RIGHT.', corner.BOTTOM_RIGHT, f(corner.BOTTOM_LEFT)); assertEquals('BOTTOM_RIGHT should be flipped to BOTTOM_LEFT.', corner.BOTTOM_LEFT, f(corner.BOTTOM_RIGHT)); assertEquals('TOP_START should be flipped to TOP_END.', corner.TOP_END, f(corner.TOP_START)); assertEquals('TOP_END should be flipped to TOP_START.', corner.TOP_START, f(corner.TOP_END)); assertEquals('BOTTOM_START should be flipped to BOTTOM_END.', corner.BOTTOM_END, f(corner.BOTTOM_START)); assertEquals('BOTTOM_END should be flipped to BOTTOM_START.', corner.BOTTOM_START, f(corner.BOTTOM_END)); } function testFlipCornerVertical() { var f = goog.positioning.flipCornerVertical; assertEquals('TOP_LEFT should be flipped to BOTTOM_LEFT.', corner.BOTTOM_LEFT, f(corner.TOP_LEFT)); assertEquals('TOP_RIGHT should be flipped to BOTTOM_RIGHT.', corner.BOTTOM_RIGHT, f(corner.TOP_RIGHT)); assertEquals('BOTTOM_LEFT should be flipped to TOP_LEFT.', corner.TOP_LEFT, f(corner.BOTTOM_LEFT)); assertEquals('BOTTOM_RIGHT should be flipped to TOP_RIGHT.', corner.TOP_RIGHT, f(corner.BOTTOM_RIGHT)); assertEquals('TOP_START should be flipped to BOTTOM_START.', corner.BOTTOM_START, f(corner.TOP_START)); assertEquals('TOP_END should be flipped to BOTTOM_END.', corner.BOTTOM_END, f(corner.TOP_END)); assertEquals('BOTTOM_START should be flipped to TOP_START.', corner.TOP_START, f(corner.BOTTOM_START)); assertEquals('BOTTOM_END should be flipped to TOP_END.', corner.TOP_END, f(corner.BOTTOM_END)); } function testFlipCorner() { var f = goog.positioning.flipCorner; assertEquals('TOP_LEFT should be flipped to BOTTOM_RIGHT.', corner.BOTTOM_RIGHT, f(corner.TOP_LEFT)); assertEquals('TOP_RIGHT should be flipped to BOTTOM_LEFT.', corner.BOTTOM_LEFT, f(corner.TOP_RIGHT)); assertEquals('BOTTOM_LEFT should be flipped to TOP_RIGHT.', corner.TOP_RIGHT, f(corner.BOTTOM_LEFT)); assertEquals('BOTTOM_RIGHT should be flipped to TOP_LEFT.', corner.TOP_LEFT, f(corner.BOTTOM_RIGHT)); assertEquals('TOP_START should be flipped to BOTTOM_END.', corner.BOTTOM_END, f(corner.TOP_START)); assertEquals('TOP_END should be flipped to BOTTOM_START.', corner.BOTTOM_START, f(corner.TOP_END)); assertEquals('BOTTOM_START should be flipped to TOP_END.', corner.TOP_END, f(corner.BOTTOM_START)); assertEquals('BOTTOM_END should be flipped to TOP_START.', corner.TOP_START, f(corner.BOTTOM_END)); } function testPositionAtAnchorFrameViewportStandard() { var iframe = document.getElementById('iframe-standard'); var iframeDoc = goog.dom.getFrameContentDocument(iframe); assertTrue(new goog.dom.DomHelper(iframeDoc).isCss1CompatMode()); new goog.dom.DomHelper(iframeDoc).getDocumentScrollElement().scrollTop = 100; var anchor = iframeDoc.getElementById('anchor1'); var popup = document.getElementById('popup6'); var status = goog.positioning.positionAtAnchor( anchor, corner.TOP_RIGHT, popup, corner.BOTTOM_RIGHT); var iframeRect = goog.style.getBounds(iframe); var popupRect = goog.style.getBounds(popup); assertEquals('Status should not have any ADJUSTED and FAILED.', goog.positioning.OverflowStatus.NONE, status); assertRoundedEquals('Popup should be positioned just above the iframe, ' + 'not above the anchor element inside the iframe', iframeRect.top, popupRect.top + popupRect.height); } function testPositionAtAnchorFrameViewportQuirk() { var iframe = document.getElementById('iframe-quirk'); var iframeDoc = goog.dom.getFrameContentDocument(iframe); assertFalse(new goog.dom.DomHelper(iframeDoc).isCss1CompatMode()); window.scrollTo(0, 100); new goog.dom.DomHelper(iframeDoc).getDocumentScrollElement().scrollTop = 100; var anchor = iframeDoc.getElementById('anchor1'); var popup = document.getElementById('popup6'); var status = goog.positioning.positionAtAnchor( anchor, corner.TOP_RIGHT, popup, corner.BOTTOM_RIGHT); var iframeRect = goog.style.getBounds(iframe); var popupRect = goog.style.getBounds(popup); assertEquals('Status should not have any ADJUSTED and FAILED.', goog.positioning.OverflowStatus.NONE, status); assertRoundedEquals('Popup should be positioned just above the iframe, ' + 'not above the anchor element inside the iframe', iframeRect.top, popupRect.top + popupRect.height); } function testPositionAtAnchorFrameViewportWithPopupInScroller() { var iframe = document.getElementById('iframe-standard'); var iframeDoc = goog.dom.getFrameContentDocument(iframe); new goog.dom.DomHelper(iframeDoc).getDocumentScrollElement().scrollTop = 100; var anchor = iframeDoc.getElementById('anchor1'); var popup = document.getElementById('popup7'); popup.offsetParent.scrollTop = 50; var status = goog.positioning.positionAtAnchor( anchor, corner.TOP_RIGHT, popup, corner.BOTTOM_RIGHT); var iframeRect = goog.style.getBounds(iframe); var popupRect = goog.style.getBounds(popup); assertEquals('Status should not have any ADJUSTED and FAILED.', goog.positioning.OverflowStatus.NONE, status); assertRoughlyEquals('Popup should be positioned just above the iframe, ' + 'not above the anchor element inside the iframe', iframeRect.top, popupRect.top + popupRect.height, ALLOWED_OFFSET); } function testPositionAtAnchorNestedFrames() { var outerIframe = document.getElementById('nested-outer'); var outerDoc = goog.dom.getFrameContentDocument(outerIframe); var popup = outerDoc.getElementById('popup1'); var innerIframe = outerDoc.getElementById('inner-frame'); var innerDoc = goog.dom.getFrameContentDocument(innerIframe); var anchor = innerDoc.getElementById('anchor1'); var status = goog.positioning.positionAtAnchor( anchor, corner.TOP_LEFT, popup, corner.BOTTOM_LEFT); assertEquals('Status should not have any ADJUSTED and FAILED.', goog.positioning.OverflowStatus.NONE, status); var innerIframeRect = goog.style.getBounds(innerIframe); var popupRect = goog.style.getBounds(popup); assertRoundedEquals('Top of frame should align with bottom of the popup', innerIframeRect.top, popupRect.top + popupRect.height); // The anchor is scrolled up by 10px. // Popup position should be the same as above. goog.dom.getWindow(innerDoc).scrollTo(0, 10); status = goog.positioning.positionAtAnchor( anchor, corner.TOP_LEFT, popup, corner.BOTTOM_LEFT); assertEquals('Status should not have any ADJUSTED and FAILED.', goog.positioning.OverflowStatus.NONE, status); innerIframeRect = goog.style.getBounds(innerIframe); popupRect = goog.style.getBounds(popup); assertRoundedEquals('Top of frame should align with bottom of the popup', innerIframeRect.top, popupRect.top + popupRect.height); } function testPositionAtAnchorOffscreen() { var offset = 0; var anchor = goog.dom.getElement('offscreen-anchor'); var popup = goog.dom.getElement('popup3'); goog.positioning.positionAtAnchor( anchor, corner.TOP_LEFT, popup, corner.TOP_LEFT, null, null, overflow.ADJUST_X | overflow.ADJUST_Y); assertObjectEquals( newCoord(offset, offset), goog.style.getPageOffset(popup)); goog.positioning.positionAtAnchor( anchor, corner.TOP_LEFT, popup, corner.TOP_LEFT, null, null, overflow.ADJUST_X_EXCEPT_OFFSCREEN | overflow.ADJUST_Y); assertObjectEquals( newCoord(-1000, offset), goog.style.getPageOffset(popup)); goog.positioning.positionAtAnchor( anchor, corner.TOP_LEFT, popup, corner.TOP_LEFT, null, null, overflow.ADJUST_X | overflow.ADJUST_Y_EXCEPT_OFFSCREEN); assertObjectEquals( newCoord(offset, -1000), goog.style.getPageOffset(popup)); goog.positioning.positionAtAnchor( anchor, corner.TOP_LEFT, popup, corner.TOP_LEFT, null, null, overflow.ADJUST_X_EXCEPT_OFFSCREEN | overflow.ADJUST_Y_EXCEPT_OFFSCREEN); assertObjectEquals( newCoord(-1000, -1000), goog.style.getPageOffset(popup)); } function testPositionAtAnchorWithOverflowScrollOffsetParent() { var testAreaOffset = goog.style.getPageOffset(testArea); var scrollbarWidth = goog.style.getScrollbarWidth(); window.scrollTo(testAreaOffset.x, testAreaOffset.y); var overflowDiv = goog.dom.createElement('div'); overflowDiv.style.overflow = 'scroll'; overflowDiv.style.position = 'relative'; goog.style.setSize(overflowDiv, 200 /* width */, 100 /* height */); var anchor = goog.dom.createElement('div'); anchor.style.position = 'absolute'; goog.style.setSize(anchor, 50 /* width */, 50 /* height */); goog.style.setPosition(anchor, 300 /* left */, 300 /* top */); var popup = createPopupDiv(75 /* width */, 50 /* height */); goog.dom.append(testArea, overflowDiv, anchor); goog.dom.append(overflowDiv, popup); // Popup should always be positioned within the overflowDiv goog.style.setPosition(overflowDiv, 0 /* left */, 0 /* top */); goog.positioning.positionAtAnchor( anchor, corner.TOP_LEFT, popup, corner.TOP_RIGHT, null, null, overflow.ADJUST_X | overflow.ADJUST_Y); assertObjectRoughlyEquals( new goog.math.Coordinate( testAreaOffset.x + 200 - 75 - scrollbarWidth, testAreaOffset.y + 100 - 50 - scrollbarWidth), goog.style.getPageOffset(popup), 1); goog.style.setPosition(overflowDiv, 400 /* left */, 0 /* top */); goog.positioning.positionAtAnchor( anchor, corner.TOP_RIGHT, popup, corner.TOP_LEFT, null, null, overflow.ADJUST_X | overflow.ADJUST_Y); assertObjectRoughlyEquals( new goog.math.Coordinate( testAreaOffset.x + 400, testAreaOffset.y + 100 - 50 - scrollbarWidth), goog.style.getPageOffset(popup), 1); goog.style.setPosition(overflowDiv, 0 /* left */, 400 /* top */); goog.positioning.positionAtAnchor( anchor, corner.BOTTOM_LEFT, popup, corner.BOTTOM_RIGHT, null, null, overflow.ADJUST_X | overflow.ADJUST_Y); assertObjectRoughlyEquals( new goog.math.Coordinate( testAreaOffset.x + 200 - 75 - scrollbarWidth, testAreaOffset.y + 400), goog.style.getPageOffset(popup), 1); goog.style.setPosition(overflowDiv, 400 /* left */, 400 /* top */); goog.positioning.positionAtAnchor( anchor, corner.BOTTOM_RIGHT, popup, corner.BOTTOM_LEFT, null, null, overflow.ADJUST_X | overflow.ADJUST_Y); assertObjectRoughlyEquals( new goog.math.Coordinate( testAreaOffset.x + 400, testAreaOffset.y + 400), goog.style.getPageOffset(popup), 1); // No overflow. goog.style.setPosition(overflowDiv, 300 - 50 /* left */, 300 /* top */); goog.positioning.positionAtAnchor( anchor, corner.TOP_LEFT, popup, corner.TOP_RIGHT, null, null, overflow.ADJUST_X | overflow.ADJUST_Y); assertObjectRoughlyEquals( new goog.math.Coordinate( testAreaOffset.x + 300 - 50, testAreaOffset.y + 300), goog.style.getPageOffset(popup), 1); } function testPositionAtAnchorWithOverflowHiddenParent() { var testAreaOffset = goog.style.getPageOffset(testArea); window.scrollTo(testAreaOffset.x, testAreaOffset.y); var overflowDiv = goog.dom.createElement('div'); overflowDiv.style.overflow = 'hidden'; overflowDiv.style.position = 'relative'; goog.style.setSize(overflowDiv, 200 /* width */, 100 /* height */); var anchor = goog.dom.createElement('div'); anchor.style.position = 'absolute'; goog.style.setSize(anchor, 50 /* width */, 50 /* height */); goog.style.setPosition(anchor, 300 /* left */, 300 /* top */); var popup = createPopupDiv(75 /* width */, 50 /* height */); goog.dom.append(testArea, overflowDiv, anchor); goog.dom.append(overflowDiv, popup); // Popup should always be positioned within the overflowDiv goog.style.setPosition(overflowDiv, 0 /* left */, 0 /* top */); goog.positioning.positionAtAnchor( anchor, corner.TOP_LEFT, popup, corner.TOP_RIGHT, null, null, overflow.ADJUST_X | overflow.ADJUST_Y); assertObjectRoughlyEquals( new goog.math.Coordinate( testAreaOffset.x + 200 - 75, testAreaOffset.y + 100 - 50), goog.style.getPageOffset(popup), 1); goog.style.setPosition(overflowDiv, 400 /* left */, 0 /* top */); goog.positioning.positionAtAnchor( anchor, corner.TOP_RIGHT, popup, corner.TOP_LEFT, null, null, overflow.ADJUST_X | overflow.ADJUST_Y); assertObjectRoughlyEquals( new goog.math.Coordinate( testAreaOffset.x + 400, testAreaOffset.y + 100 - 50), goog.style.getPageOffset(popup), 1); goog.style.setPosition(overflowDiv, 0 /* left */, 400 /* top */); goog.positioning.positionAtAnchor( anchor, corner.BOTTOM_LEFT, popup, corner.BOTTOM_RIGHT, null, null, overflow.ADJUST_X | overflow.ADJUST_Y); assertObjectRoughlyEquals( new goog.math.Coordinate( testAreaOffset.x + 200 - 75, testAreaOffset.y + 400), goog.style.getPageOffset(popup), 1); goog.style.setPosition(overflowDiv, 400 /* left */, 400 /* top */); goog.positioning.positionAtAnchor( anchor, corner.BOTTOM_RIGHT, popup, corner.BOTTOM_LEFT, null, null, overflow.ADJUST_X | overflow.ADJUST_Y); assertObjectRoughlyEquals( new goog.math.Coordinate( testAreaOffset.x + 400, testAreaOffset.y + 400), goog.style.getPageOffset(popup), 1); // No overflow. goog.style.setPosition(overflowDiv, 300 - 50 /* left */, 300 /* top */); goog.positioning.positionAtAnchor( anchor, corner.TOP_LEFT, popup, corner.TOP_RIGHT, null, null, overflow.ADJUST_X | overflow.ADJUST_Y); assertObjectRoughlyEquals( new goog.math.Coordinate( testAreaOffset.x + 300 - 50, testAreaOffset.y + 300), goog.style.getPageOffset(popup), 1); } function createPopupDiv(width, height) { var popupDiv = goog.dom.createElement('div'); popupDiv.style.position = 'absolute'; goog.style.setSize(popupDiv, width, height); goog.style.setPosition(popupDiv, 0 /* left */, 250 /* top */); return popupDiv; } function newCoord(x, y) { return new goog.math.Coordinate(x, y); } function newSize(w, h) { return new goog.math.Size(w, h); } function newBox(coord, size) { }
// Generated by CoffeeScript 1.6.3 var OPERATOR; OPERATOR = /^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>])\2=?|\?\.|\.{2,3})/;
/** * Created by yangmengyuan on 15/10/20. */ $(function(){ var $body = $('body'), $ftlist = $(".find-teacher-list"); $ftlist.each(function(){ $body.on({ mouseenter:function(){ $(this).find(".find-teacher-hover").stop().animate({"top":0},300); }, mouseleave:function(){ $(this).find(".find-teacher-hover").stop().animate({"top":200},300); }},'.find-teacher-hover-container' ); }); //$body.on("click",'.find-teacher-follow',function(){ // var followId = $(this).closest('.find-teacher-card').attr('id'); // //console.log(followId); // $.ajax({ // url : '/teacher/follow', // type : 'post', // dataType : 'json', // data : { // followId : followId // }, // success : function(msg){ // if(msg.sign == 2){ // window.location.href = ''; // }else if(msg.sign == 1){ // $(this).addClass("find-teacher-have-followed").html("已关注"); // } // } // }) //}); var $ftname = $('.find-teacher-name'); $ftname.each(function(){ var str = $(this).text(), str_char = /[a-zA-Z]/g, str_chin = /[\u4e00-\u9fa5]/g; var str_char_num = str.match(str_char), str_chin_num = str.match(str_chin); if(str_char_num){ var char_maxwidth = 8; if(str_char_num.length>char_maxwidth){ $(this).text(str.substring(0, char_maxwidth)); $(this).html($(this).html() + '...'); } //console.log(str_char_num.length) }else if(str_chin_num){ var chin_maxwidth = 4; if(str_chin_num.length>chin_maxwidth){ $(this).text(str.substring(0,chin_maxwidth)); $(this).html($(this).html()+'...'); } } }); $('.find-teacher-course a').each(function(){ var maxwidth=20; if($(this).text().length>maxwidth){ $(this).text($(this).text().substring(0,maxwidth)); $(this).html($(this).html()+'...'); } }); });