text
stringlengths 2
1.05M
|
|---|
"use strict";
Object.defineProperty(exports, "__esModule", {value: true});
var prefix = "fas";
var iconName = "retweet";
var width = 640;
var height = 512;
var ligatures = [];
var unicode = "f079";
var svgPathData = "M629.657 343.598L528.971 444.284c-9.373 9.372-24.568 9.372-33.941 0L394.343 343.598c-9.373-9.373-9.373-24.569 0-33.941l10.823-10.823c9.562-9.562 25.133-9.34 34.419.492L480 342.118V160H292.451a24.005 24.005 0 0 1-16.971-7.029l-16-16C244.361 121.851 255.069 96 276.451 96H520c13.255 0 24 10.745 24 24v222.118l40.416-42.792c9.285-9.831 24.856-10.054 34.419-.492l10.823 10.823c9.372 9.372 9.372 24.569-.001 33.941zm-265.138 15.431A23.999 23.999 0 0 0 347.548 352H160V169.881l40.416 42.792c9.286 9.831 24.856 10.054 34.419.491l10.822-10.822c9.373-9.373 9.373-24.569 0-33.941L144.971 67.716c-9.373-9.373-24.569-9.373-33.941 0L10.343 168.402c-9.373 9.373-9.373 24.569 0 33.941l10.822 10.822c9.562 9.562 25.133 9.34 34.419-.491L96 169.881V392c0 13.255 10.745 24 24 24h243.549c21.382 0 32.09-25.851 16.971-40.971l-16.001-16z";
exports.definition = {
prefix: prefix,
iconName: iconName,
icon: [
width,
height,
ligatures,
unicode,
svgPathData
]
};
exports.faRetweet = exports.definition;
exports.prefix = prefix;
exports.iconName = iconName;
exports.width = width;
exports.height = height;
exports.ligatures = ligatures;
exports.unicode = unicode;
exports.svgPathData = svgPathData;
|
var game = new Phaser.Game(800, 600, Phaser.AUTO, 'game');
game.state.add('menu', menuState);
game.state.add('platform', platformState);
game.state.add('win', winState);
game.state.add('lose', loseState);
game.state.start('menu');
|
import binarySearch from '../../../algorithms/binary-search';
import BinarySearch from '../../../components/illustrations/binary-search/binary-search';
import computeBinarySearchLayout from '../../../layout/binary-search';
import computeBinarySearchFrame from '../../../frame/binary-search';
import Page from '../../page';
const list = ['bear', 'cat', 'dog', 'lion', 'panda', 'snail'];
export default {
component: Page,
props: {
currentPath: '/binary-search',
algorithm: binarySearch,
illustration: BinarySearch,
computeLayout: computeBinarySearchLayout,
computeFrame: computeBinarySearchFrame,
steps: [
{
bindings: { list },
intro: true
}
],
actions: {
generateSteps: item => {
console.log('generate steps', item);
}
}
}
};
|
/** @jsx jsx */
import { Transforms } from '@robinedman/slate'
import { jsx } from '../../..'
export const run = editor => {
Transforms.delete(editor)
}
export const input = (
<editor>
<block>
wo
<anchor />
rd
</block>
<block>
an
<focus />
other
</block>
</editor>
)
export const output = (
<editor>
<block>
wo
<cursor />
other
</block>
</editor>
)
|
/* eslint-disable */
/**
* TODO: Write custom components that address our needs to directly and deprecate these Bootstrap components.
*/
/*
* angular-ui-bootstrap
* http://angular-ui.github.io/bootstrap/
* Version: 0.12.1 - 2015-02-20
* License: MIT
*/
angular.module('ui.bootstrap', [
'ui.bootstrap.tpls',
'ui.bootstrap.transition',
'ui.bootstrap.collapse',
'ui.bootstrap.alert',
'ui.bootstrap.bindHtml',
'ui.bootstrap.buttons',
'ui.bootstrap.carousel',
'ui.bootstrap.dateparser',
'ui.bootstrap.position',
'ui.bootstrap.datepicker',
'ui.bootstrap.dropdown',
'ui.bootstrap.modal',
'ui.bootstrap.pagination',
'ui.bootstrap.tooltip',
'ui.bootstrap.popover',
'ui.bootstrap.progressbar',
'ui.bootstrap.rating',
'ui.bootstrap.tabs',
'ui.bootstrap.timepicker',
'ui.bootstrap.typeahead'
]);
angular.module('ui.bootstrap.tpls', [
'template/alert/alert.html',
'template/carousel/carousel.html',
'template/carousel/slide.html',
'template/datepicker/datepicker.html',
'template/datepicker/day.html',
'template/datepicker/month.html',
'template/datepicker/popup.html',
'template/datepicker/year.html',
'template/modal/backdrop.html',
'template/modal/window.html',
'template/pagination/pager.html',
'template/pagination/pagination.html',
'template/tooltip/tooltip-html-unsafe-popup.html',
'template/tooltip/tooltip-popup.html',
'template/popover/popover.html',
'template/progressbar/bar.html',
'template/progressbar/progress.html',
'template/progressbar/progressbar.html',
'template/rating/rating.html',
'template/tabs/tab.html',
'template/tabs/tabset.html',
'template/timepicker/timepicker.html',
'template/typeahead/typeahead-match.html',
'template/typeahead/typeahead-popup.html'
]);
import './accordion';
import './alert';
import './bindHtml';
import './buttons';
import './carousel';
import './collapse';
import './dateparser';
import './datepicker';
import './dropdown';
import './modal';
import './pagination';
import './popover';
import './position';
import './progressbar';
import './rating';
import './tabs';
import './timepicker';
import './tooltip';
import './transition';
import './typeahead';
import alert from './alert/alert.html';
angular.module('template/alert/alert.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/alert/alert.html', alert);
}]);
import carousel from './carousel/carousel.html';
angular.module('template/carousel/carousel.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/carousel/carousel.html', carousel);
}]);
import slide from './carousel/slide.html';
angular.module('template/carousel/slide.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/carousel/slide.html', slide);
}]);
import datepicker from './datepicker/datepicker.html';
angular.module('template/datepicker/datepicker.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/datepicker/datepicker.html', datepicker);
}]);
import day from './datepicker/day.html';
angular.module('template/datepicker/day.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/datepicker/day.html', day);
}]);
import month from './datepicker/month.html';
angular.module('template/datepicker/month.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/datepicker/month.html', month);
}]);
import popup from './datepicker/popup.html';
angular.module('template/datepicker/popup.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/datepicker/popup.html', popup);
}]);
import year from './datepicker/year.html';
angular.module('template/datepicker/year.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/datepicker/year.html', year);
}]);
import backdrop from './modal/backdrop.html';
angular.module('template/modal/backdrop.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/modal/backdrop.html', backdrop);
}]);
import modal from './modal/window.html';
angular.module('template/modal/window.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/modal/window.html', modal);
}]);
import pager from './pagination/pager.html';
angular.module('template/pagination/pager.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/pagination/pager.html', pager);
}]);
import pagination from './pagination/pagination.html';
angular.module('template/pagination/pagination.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/pagination/pagination.html', pagination);
}]);
import tooltipUnsafePopup from './tooltip/tooltip-html-unsafe-popup.html';
angular.module('template/tooltip/tooltip-html-unsafe-popup.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/tooltip/tooltip-html-unsafe-popup.html', tooltipUnsafePopup);
}]);
import tooltipPopup from './tooltip/tooltip-popup.html';
angular.module('template/tooltip/tooltip-popup.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/tooltip/tooltip-popup.html', tooltipPopup);
}]);
import popover from './popover/popover.html';
angular.module('template/popover/popover.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/popover/popover.html', popover);
}]);
import bar from './progressbar/bar.html';
angular.module('template/progressbar/bar.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/progressbar/bar.html', bar);
}]);
import progress from './progressbar/progress.html';
angular.module('template/progressbar/progress.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/progressbar/progress.html', progress);
}]);
import progressbar from './progressbar/progressbar.html';
angular.module('template/progressbar/progressbar.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/progressbar/progressbar.html', progressbar);
}]);
import rating from './rating/rating.html';
angular.module('template/rating/rating.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/rating/rating.html', rating);
}]);
import tab from './tabs/tab.html';
angular.module('template/tabs/tab.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/tabs/tab.html', tab);
}]);
import tabset from './tabs/tabset.html';
angular.module('template/tabs/tabset.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/tabs/tabset.html', tabset);
}]);
import timepicker from './timepicker/timepicker.html';
angular.module('template/timepicker/timepicker.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/timepicker/timepicker.html', timepicker);
}]);
import typeaheadMatch from './typeahead/typeahead-match.html';
angular.module('template/typeahead/typeahead-match.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/typeahead/typeahead-match.html', typeaheadMatch);
}]);
import typeaheadPopup from './typeahead/typeahead-popup.html';
angular.module('template/typeahead/typeahead-popup.html', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/typeahead/typeahead-popup.html', typeaheadPopup);
}]);
|
const fs = require('fs');
const path = require('path')
const {ipcMain, dialog, app} = require('electron')
let {initSql} = require('../assets/utils/sqljsUtil')
const paramFileName = 'initProjectParam.json';
let isNeedInit = false;
let db;
// 读取本地参数文件
function readMyData() {
console.log('加载initProject.js');
// 读取文件内容
let data;
try {
data = fs.readFileSync(paramFileName, {encoding: 'utf-8',flag: 'r'});
}catch (e) {
isNeedInit = true
}
// 如果有参数
if (data) {
let paramString = data.toString();
// 判断是否有设置数据库文件的缓存路径
let cachePath = JSON.parse(paramString).cachePath;
// 如果没有设置缓存路径
if (!cachePath) {
// 如果没有本地参数文件, 告知渲染进程是第一次安装该软件, 开始走参数设置流程
isNeedInit = true
}
}else{ // 如果没参数
isNeedInit = true
}
}
function initSQl(dataBasefilePath){
return new Promise(resolve => {
let dataBaseFilebuffer;
if (dataBasefilePath) {
dataBaseFilebuffer = fs.readFileSync(dataBasefilePath);
}
initSql(dataBaseFilebuffer).then(result =>{
db = result;
resolve(result)
});
});
}
readMyData();
ipcMain.on('check_init_project', (event, arg) => {
event.returnValue = isNeedInit
});
ipcMain.on('open_select_database_file_dialog', (event) => {
dialog.showOpenDialog({
title:'选择要导入的数据库文件',
buttonLabel: '选择',
filters:[
{ name: 'SQLITE', extensions: ['sqlite'] }
],
properties: ['openFile']
}).then(result => {
// console.log(result.canceled)
// console.log(result.filePaths)
if (result.filePaths.length > 0){
event.sender.send('selected_database_file', result.filePaths)
}
}).catch(err => {
console.log(err)
})
});
ipcMain.on('load_database_file', (event, arg) => {
initSQl(arg).then(result =>{
console.log(result)
if (result) {
event.returnValue = true
}else{
event.returnValue = false
}
});
});
ipcMain.on('open_select_cache_database_directory_dialog', (event) => {
dialog.showOpenDialog({
title:'选择要缓存数据库文件的路径',
buttonLabel: '选择',
properties: ['openDirectory']
}).then(result => {
console.log('result',result)
if (result.filePaths.length > 0){
event.sender.send('selected_database_cache_file', result.filePaths)
}
}).catch(err => {
console.log(err)
})
});
ipcMain.on('set_cache_path_param_file', (event, arg) => {
if (!arg){
event.returnValue = {
result: false,
msg: '必须选择一个文件夹'
};
return
}
let cacheFilePath = paramFileName;
// 判断是否是在安装目录中
let installDir = app.getPath('exe');
let lastIndex = installDir.lastIndexOf('\\');
installDir = installDir.substring(0, lastIndex);
console.log('cacheFilePath', cacheFilePath);
if (cacheFilePath.indexOf(installDir) !== -1) {
event.returnValue = {
result: false,
msg: '不能选择安装目录'
};
}
// 检查同目录是否有同名文件
// try {
// fs.accessSync(cacheFilePath);
// event.returnValue = {
// result: false,
// msg: '有同名文件,请更换文件夹1'+cacheFilePath
// };
// } catch (err) {
// }
// 打开或创建文件
fs.open(cacheFilePath, 'w+', (err, fd) => {
if (err) {
// if (err.code === 'EEXIST') {
// event.returnValue = {
// result: false,
// msg: '有同名文件,请更换文件夹2'+cacheFilePath
// };
// return;
// }
event.returnValue = {
result: false,
msg: '打开或创建文件失败'
};
throw err;
}
writeData(fd);
});
function writeData(fd) {
let param = {
cachePath: path.join(arg, 'customer.sqlite')
};
try{
// 文件中写入json字符串
fs.writeSync(fd, JSON.stringify(param), 0, 'utf-8')
event.returnValue = {
result: true,
msg: '写入成功'
};
}catch (e) {
}finally {
// 关闭文件
fs.closeSync(fd);
}
}
});
|
/// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.4/15.4.4/15.4.4.20/15.4.4.20-2-2.js
* @description Array.prototype.filter - 'length' is own data property on an Array
*/
function testcase() {
function callbackfn(val, idx, obj) {
return obj.length === 2;
}
var newArr = [12, 11].filter(callbackfn);
return newArr.length === 2;
}
runTestCase(testcase);
|
"use strict";
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;
};
Object.defineProperty(exports, "__esModule", { value: true });
const routing_controllers_1 = require("routing-controllers");
const ReturnModel_1 = require("../viewmodel/ReturnModel");
let BaseController = class BaseController {
returnData(data, msg = 'success') {
if (!data) {
msg = 'error';
}
return new ReturnModel_1.ReturnModel(data || '', msg);
}
returnError(error) {
return new ReturnModel_1.ReturnModel('', 'error', -1, error);
}
returnSuccess(data) {
return new ReturnModel_1.ReturnModel(data);
}
};
BaseController = __decorate([
routing_controllers_1.Controller()
], BaseController);
exports.BaseController = BaseController;
//# sourceMappingURL=BaseController.js.map
|
'use strict';
const test = require('tape');
const minifiers = require('./');
const charset = '@charset "utf-8";';
const utf16Encoding = '\ufeff';
const h1Long = 'h1::before,';
const h1 = 'h1:before{';
const marginOriginal = 'margin: 10px 20px 10px 20px;';
const margin = 'margin:10px 20px;';
const gradientOriginal = 'background: linear-gradient(to bottom, #ffe500 0%, #ffe500 50%, #121 50%, #121 100%);';
const gradient = 'background:linear-gradient(to bottom,#ffe500 0%,#ffe500 50%,#121 50%,#121 100%);';
const gradient0 = 'background:linear-gradient(to bottom,#ffe500 0,#ffe500 50%,#121 50%,#121 100%);';
const gradientDeg = 'background:linear-gradient(180deg,#ffe500,#ffe500 50%,#121 0,#121);';
const bgPostionPercent = 'background-position:100% 100%;';
const bgPositionWords = 'background-position:bottom right;';
const colorOriginal = 'color: #ff0000;';
const colorRed = 'color:red;';
const colorHex = 'color:#f00;';
const originalFontWeight = 'font-weight: 400;';
const fontWeight = 'font-weight:400;';
const originalQuotes = 'quotes: \'«\' "»";';
const quotesNoSpace = 'quotes:\'«\'"»";';
const quotes = 'quotes:"«" "»";';
const minWidth0 = 'min-width:0;';
const minWidthInit = 'min-width:initial;';
const closeQuote = '}';
const cssInput = [
'/* normalize selectors */',
h1Long + ' ' + h1.replace('{', ' {'),
' /* reduce shorthand even further */',
' ' + marginOriginal,
' /* reduce color values */',
' ' + colorOriginal,
' /* remove duplicated properties */',
' ' + originalFontWeight,
' ' + originalFontWeight,
' /* reduce position values */',
' ' + bgPositionWords.replace(':', ': '),
' /* normalize wrapping quotes */',
' ' + originalQuotes,
' /* reduce gradient parameters */',
' ' + gradientOriginal,
' /* replace initial values */',
' ' + minWidthInit.replace(':', ': '),
'}',
'/* correct invalid placement */',
charset
].join('\n');
const outputMap = {
// 186
crass: [
h1,
gradientDeg,
bgPositionWords,
colorRed,
fontWeight,
margin,
minWidthInit,
quotes.replace(';', ''),
closeQuote
],
// 194
'css-nano': [
charset,
h1,
margin,
colorRed,
fontWeight,
bgPostionPercent,
quotes,
gradientDeg,
minWidth0.replace(';', ''),
closeQuote
],
// 209
csso: [
h1Long,
h1,
margin,
colorRed,
fontWeight,
bgPositionWords,
originalQuotes.replace(': ', ':'),
gradient0,
minWidthInit.replace(';', ''),
closeQuote
],
// 211
sqwish: [
h1Long,
h1,
minWidthInit,
gradient,
originalQuotes.replace(': ', ':'),
bgPositionWords,
fontWeight,
colorHex,
margin.replace(';', ''),
closeQuote
],
// 214
csswring: [
h1,
margin,
colorRed,
fontWeight,
bgPositionWords,
originalQuotes.replace(': ', ':'),
gradient0,
minWidthInit.replace(';', ''),
closeQuote,
charset.replace(';', '')
],
// 241
sass: [
utf16Encoding,
h1Long,
h1,
marginOriginal.replace(': ', ':'),
colorRed,
fontWeight,
fontWeight,
bgPositionWords,
quotes,
gradientOriginal.replace(': ', ':'),
minWidthInit.replace(';', ''),
closeQuote
],
// 244
'css-condense': [
charset,
h1Long,
h1,
gradient,
bgPositionWords,
colorHex,
fontWeight,
fontWeight,
margin,
minWidthInit,
originalQuotes.replace(': ', ':').replace(';', ''),
closeQuote
],
// 252
'clean-css': [
charset,
h1Long,
h1,
marginOriginal.replace(': ', ':'),
colorRed,
fontWeight,
fontWeight,
bgPositionWords,
originalQuotes.replace(': ', ':'),
gradient0,
minWidthInit.replace(';', ''),
closeQuote
],
// 252
ncss: [
h1Long,
h1,
marginOriginal.replace(': ', ':'),
colorHex,
fontWeight,
fontWeight,
bgPositionWords,
quotesNoSpace,
gradient0,
minWidthInit.replace(';', ''),
closeQuote,
charset
],
// 253
ycssmin: [
charset,
h1Long,
h1,
marginOriginal.replace(': ', ':'),
colorHex,
fontWeight,
fontWeight,
bgPositionWords,
originalQuotes.replace(': ', ':'),
gradient0,
minWidthInit.replace(';', ''),
closeQuote
]
};
test('integration tests', function (t) {
t.plan(Object.keys(minifiers).length);
Object.keys(minifiers).forEach(function (minifier) {
Promise.resolve(minifiers[minifier](cssInput)).then(function (css) {
t.equal(css, outputMap[minifier].join(''), 'Output length is ' + css.length + ' when using ' + minifier);
}, function (err) {
t.fail('Failure from engine "' + minifier + '": ' + String(err));
});
});
});
test('benchmark tests', function (t) {
t.plan(Object.keys(minifiers).length);
Object.keys(minifiers).forEach(function (m) {
let minifier = minifiers[m];
Promise.resolve(minifier.bench(cssInput)).then(function (time) {
t.ok(time, minifier + ' took ' + time);
}, function (err) {
t.fail('Failure from engine "' + minifier + '": ' + String(err));
});
});
});
test('metadata tests', function (t) {
t.plan(Object.keys(minifiers).length * 2);
Object.keys(minifiers).forEach(function (m) {
let minifier = minifiers[m];
t.ok(minifier.version, minifier + ' version ' + minifier.version);
t.ok('' + minifier, minifier + ' should be cast to string');
});
});
|
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).ZSchema=e()}}(function(){return function a(o,s,l){function u(t,e){if(!s[t]){if(!o[t]){var r="function"==typeof require&&require;if(!e&&r)return r(t,!0);if(f)return f(t,!0);var n=new Error("Cannot find module '"+t+"'");throw n.code="MODULE_NOT_FOUND",n}var i=s[t]={exports:{}};o[t][0].call(i.exports,function(e){return u(o[t][1][e]||e)},i,i.exports,a,o,s,l)}return s[t].exports}for(var f="function"==typeof require&&require,e=0;e<l.length;e++)u(l[e]);return u}({1:[function(e,t,r){e("../../modules/es.array.concat"),e("../../modules/es.object.to-string"),e("../../modules/es.symbol"),e("../../modules/es.symbol.async-iterator"),e("../../modules/es.symbol.description"),e("../../modules/es.symbol.has-instance"),e("../../modules/es.symbol.is-concat-spreadable"),e("../../modules/es.symbol.iterator"),e("../../modules/es.symbol.match"),e("../../modules/es.symbol.match-all"),e("../../modules/es.symbol.replace"),e("../../modules/es.symbol.search"),e("../../modules/es.symbol.species"),e("../../modules/es.symbol.split"),e("../../modules/es.symbol.to-primitive"),e("../../modules/es.symbol.to-string-tag"),e("../../modules/es.symbol.unscopables"),e("../../modules/es.math.to-string-tag"),e("../../modules/es.json.to-string-tag");var n=e("../../internals/path");t.exports=n.Symbol},{"../../internals/path":48,"../../modules/es.array.concat":64,"../../modules/es.json.to-string-tag":65,"../../modules/es.math.to-string-tag":66,"../../modules/es.object.to-string":67,"../../modules/es.symbol":73,"../../modules/es.symbol.async-iterator":68,"../../modules/es.symbol.description":69,"../../modules/es.symbol.has-instance":70,"../../modules/es.symbol.is-concat-spreadable":71,"../../modules/es.symbol.iterator":72,"../../modules/es.symbol.match":75,"../../modules/es.symbol.match-all":74,"../../modules/es.symbol.replace":76,"../../modules/es.symbol.search":77,"../../modules/es.symbol.species":78,"../../modules/es.symbol.split":79,"../../modules/es.symbol.to-primitive":80,"../../modules/es.symbol.to-string-tag":81,"../../modules/es.symbol.unscopables":82}],2:[function(e,t,r){t.exports=function(e){if("function"!=typeof e)throw TypeError(String(e)+" is not a function");return e}},{}],3:[function(e,t,r){var n=e("../internals/is-object");t.exports=function(e){if(!n(e))throw TypeError(String(e)+" is not an object");return e}},{"../internals/is-object":32}],4:[function(e,t,r){var l=e("../internals/to-indexed-object"),u=e("../internals/to-length"),f=e("../internals/to-absolute-index"),n=function(s){return function(e,t,r){var n,i=l(e),a=u(i.length),o=f(r,a);if(s&&t!=t){for(;o<a;)if((n=i[o++])!=n)return!0}else for(;o<a;o++)if((s||o in i)&&i[o]===t)return s||o||0;return!s&&-1}};t.exports={includes:n(!0),indexOf:n(!1)}},{"../internals/to-absolute-index":55,"../internals/to-indexed-object":56,"../internals/to-length":58}],5:[function(e,t,r){var b=e("../internals/bind-context"),E=e("../internals/indexed-object"),S=e("../internals/to-object"),O=e("../internals/to-length"),A=e("../internals/array-species-create"),x=[].push,n=function(p){var h=1==p,m=2==p,y=3==p,g=4==p,v=6==p,_=5==p||v;return function(e,t,r,n){for(var i,a,o=S(e),s=E(o),l=b(t,r,3),u=O(s.length),f=0,c=n||A,d=h?c(e,u):m?c(e,0):void 0;f<u;f++)if((_||f in s)&&(a=l(i=s[f],f,o),p))if(h)d[f]=a;else if(a)switch(p){case 3:return!0;case 5:return i;case 6:return f;case 2:x.call(d,i)}else if(g)return!1;return v?-1:y||g?g:d}};t.exports={forEach:n(0),map:n(1),filter:n(2),some:n(3),every:n(4),find:n(5),findIndex:n(6)}},{"../internals/array-species-create":7,"../internals/bind-context":8,"../internals/indexed-object":28,"../internals/to-length":58,"../internals/to-object":59}],6:[function(e,t,r){var n=e("../internals/fails"),i=e("../internals/well-known-symbol")("species");t.exports=function(t){return!n(function(){var e=[];return(e.constructor={})[i]=function(){return{foo:1}},1!==e[t](Boolean).foo})}},{"../internals/fails":19,"../internals/well-known-symbol":62}],7:[function(e,t,r){var n=e("../internals/is-object"),i=e("../internals/is-array"),a=e("../internals/well-known-symbol")("species");t.exports=function(e,t){var r;return i(e)&&("function"!=typeof(r=e.constructor)||r!==Array&&!i(r.prototype)?n(r)&&null===(r=r[a])&&(r=void 0):r=void 0),new(void 0===r?Array:r)(0===t?0:t)}},{"../internals/is-array":30,"../internals/is-object":32,"../internals/well-known-symbol":62}],8:[function(e,t,r){var a=e("../internals/a-function");t.exports=function(n,i,e){if(a(n),void 0===i)return n;switch(e){case 0:return function(){return n.call(i)};case 1:return function(e){return n.call(i,e)};case 2:return function(e,t){return n.call(i,e,t)};case 3:return function(e,t,r){return n.call(i,e,t,r)}}return function(){return n.apply(i,arguments)}}},{"../internals/a-function":2}],9:[function(e,t,r){var n={}.toString;t.exports=function(e){return n.call(e).slice(8,-1)}},{}],10:[function(e,t,r){var i=e("../internals/classof-raw"),a=e("../internals/well-known-symbol")("toStringTag"),o="Arguments"==i(function(){return arguments}());t.exports=function(e){var t,r,n;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=function(e,t){try{return e[t]}catch(e){}}(t=Object(e),a))?r:o?i(t):"Object"==(n=i(t))&&"function"==typeof t.callee?"Arguments":n}},{"../internals/classof-raw":9,"../internals/well-known-symbol":62}],11:[function(e,t,r){var s=e("../internals/has"),l=e("../internals/own-keys"),u=e("../internals/object-get-own-property-descriptor"),f=e("../internals/object-define-property");t.exports=function(e,t){for(var r=l(t),n=f.f,i=u.f,a=0;a<r.length;a++){var o=r[a];s(e,o)||n(e,o,i(t,o))}}},{"../internals/has":23,"../internals/object-define-property":38,"../internals/object-get-own-property-descriptor":39,"../internals/own-keys":47}],12:[function(e,t,r){t.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},{}],13:[function(e,t,r){"use strict";var i=e("../internals/to-primitive"),a=e("../internals/object-define-property"),o=e("../internals/create-property-descriptor");t.exports=function(e,t,r){var n=i(t);n in e?a.f(e,n,o(0,r)):e[n]=r}},{"../internals/create-property-descriptor":12,"../internals/object-define-property":38,"../internals/to-primitive":60}],14:[function(e,t,r){var n=e("../internals/path"),i=e("../internals/has"),a=e("../internals/wrapped-well-known-symbol"),o=e("../internals/object-define-property").f;t.exports=function(e){var t=n.Symbol||(n.Symbol={});i(t,e)||o(t,e,{value:a.f(e)})}},{"../internals/has":23,"../internals/object-define-property":38,"../internals/path":48,"../internals/wrapped-well-known-symbol":63}],15:[function(e,t,r){var n=e("../internals/fails");t.exports=!n(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},{"../internals/fails":19}],16:[function(e,t,r){var n=e("../internals/global"),i=e("../internals/is-object"),a=n.document,o=i(a)&&i(a.createElement);t.exports=function(e){return o?a.createElement(e):{}}},{"../internals/global":22,"../internals/is-object":32}],17:[function(e,t,r){t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},{}],18:[function(e,t,r){var f=e("../internals/global"),c=e("../internals/object-get-own-property-descriptor").f,d=e("../internals/hide"),p=e("../internals/redefine"),h=e("../internals/set-global"),m=e("../internals/copy-constructor-properties"),y=e("../internals/is-forced");t.exports=function(e,t){var r,n,i,a,o,s=e.target,l=e.global,u=e.stat;if(r=l?f:u?f[s]||h(s,{}):(f[s]||{}).prototype)for(n in t){if(a=t[n],i=e.noTargetGet?(o=c(r,n))&&o.value:r[n],!y(l?n:s+(u?".":"#")+n,e.forced)&&void 0!==i){if(typeof a==typeof i)continue;m(a,i)}(e.sham||i&&i.sham)&&d(a,"sham",!0),p(r,n,a,e)}}},{"../internals/copy-constructor-properties":11,"../internals/global":22,"../internals/hide":25,"../internals/is-forced":31,"../internals/object-get-own-property-descriptor":39,"../internals/redefine":49,"../internals/set-global":51}],19:[function(e,t,r){t.exports=function(e){try{return!!e()}catch(e){return!0}}},{}],20:[function(e,t,r){var n=e("../internals/shared");t.exports=n("native-function-to-string",Function.toString)},{"../internals/shared":54}],21:[function(e,t,r){var n=e("../internals/path"),i=e("../internals/global"),a=function(e){return"function"==typeof e?e:void 0};t.exports=function(e,t){return arguments.length<2?a(n[e])||a(i[e]):n[e]&&n[e][t]||i[e]&&i[e][t]}},{"../internals/global":22,"../internals/path":48}],22:[function(e,n,t){(function(e){var t="object",r=function(e){return e&&e.Math==Math&&e};n.exports=r(typeof globalThis==t&&globalThis)||r(typeof window==t&&window)||r(typeof self==t&&self)||r(typeof e==t&&e)||Function("return this")()}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],23:[function(e,t,r){var n={}.hasOwnProperty;t.exports=function(e,t){return n.call(e,t)}},{}],24:[function(e,t,r){t.exports={}},{}],25:[function(e,t,r){var n=e("../internals/descriptors"),i=e("../internals/object-define-property"),a=e("../internals/create-property-descriptor");t.exports=n?function(e,t,r){return i.f(e,t,a(1,r))}:function(e,t,r){return e[t]=r,e}},{"../internals/create-property-descriptor":12,"../internals/descriptors":15,"../internals/object-define-property":38}],26:[function(e,t,r){var n=e("../internals/get-built-in");t.exports=n("document","documentElement")},{"../internals/get-built-in":21}],27:[function(e,t,r){var n=e("../internals/descriptors"),i=e("../internals/fails"),a=e("../internals/document-create-element");t.exports=!n&&!i(function(){return 7!=Object.defineProperty(a("div"),"a",{get:function(){return 7}}).a})},{"../internals/descriptors":15,"../internals/document-create-element":16,"../internals/fails":19}],28:[function(e,t,r){var n=e("../internals/fails"),i=e("../internals/classof-raw"),a="".split;t.exports=n(function(){return!Object("z").propertyIsEnumerable(0)})?function(e){return"String"==i(e)?a.call(e,""):Object(e)}:Object},{"../internals/classof-raw":9,"../internals/fails":19}],29:[function(e,t,r){var n,i,a,o=e("../internals/native-weak-map"),s=e("../internals/global"),l=e("../internals/is-object"),u=e("../internals/hide"),f=e("../internals/has"),c=e("../internals/shared-key"),d=e("../internals/hidden-keys"),p=s.WeakMap;if(o){var h=new p,m=h.get,y=h.has,g=h.set;n=function(e,t){return g.call(h,e,t),t},i=function(e){return m.call(h,e)||{}},a=function(e){return y.call(h,e)}}else{var v=c("state");d[v]=!0,n=function(e,t){return u(e,v,t),t},i=function(e){return f(e,v)?e[v]:{}},a=function(e){return f(e,v)}}t.exports={set:n,get:i,has:a,enforce:function(e){return a(e)?i(e):n(e,{})},getterFor:function(r){return function(e){var t;if(!l(e)||(t=i(e)).type!==r)throw TypeError("Incompatible receiver, "+r+" required");return t}}}},{"../internals/global":22,"../internals/has":23,"../internals/hidden-keys":24,"../internals/hide":25,"../internals/is-object":32,"../internals/native-weak-map":35,"../internals/shared-key":53}],30:[function(e,t,r){var n=e("../internals/classof-raw");t.exports=Array.isArray||function(e){return"Array"==n(e)}},{"../internals/classof-raw":9}],31:[function(e,t,r){var n=e("../internals/fails"),i=/#|\.prototype\./,a=function(e,t){var r=s[o(e)];return r==u||r!=l&&("function"==typeof t?n(t):!!t)},o=a.normalize=function(e){return String(e).replace(i,".").toLowerCase()},s=a.data={},l=a.NATIVE="N",u=a.POLYFILL="P";t.exports=a},{"../internals/fails":19}],32:[function(e,t,r){t.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},{}],33:[function(e,t,r){t.exports=!1},{}],34:[function(e,t,r){var n=e("../internals/fails");t.exports=!!Object.getOwnPropertySymbols&&!n(function(){return!String(Symbol())})},{"../internals/fails":19}],35:[function(e,t,r){var n=e("../internals/global"),i=e("../internals/function-to-string"),a=n.WeakMap;t.exports="function"==typeof a&&/native code/.test(i.call(a))},{"../internals/function-to-string":20,"../internals/global":22}],36:[function(e,t,r){var n=e("../internals/an-object"),i=e("../internals/object-define-properties"),a=e("../internals/enum-bug-keys"),o=e("../internals/hidden-keys"),s=e("../internals/html"),l=e("../internals/document-create-element"),u=e("../internals/shared-key")("IE_PROTO"),f="prototype",c=function(){},d=function(){var e,t=l("iframe"),r=a.length,n="script";for(t.style.display="none",s.appendChild(t),t.src=String("javascript:"),(e=t.contentWindow.document).open(),e.write("<script>document.F=Object</"+n+">"),e.close(),d=e.F;r--;)delete d[f][a[r]];return d()};t.exports=Object.create||function(e,t){var r;return null!==e?(c[f]=n(e),r=new c,c[f]=null,r[u]=e):r=d(),void 0===t?r:i(r,t)},o[u]=!0},{"../internals/an-object":3,"../internals/document-create-element":16,"../internals/enum-bug-keys":17,"../internals/hidden-keys":24,"../internals/html":26,"../internals/object-define-properties":37,"../internals/shared-key":53}],37:[function(e,t,r){var n=e("../internals/descriptors"),o=e("../internals/object-define-property"),s=e("../internals/an-object"),l=e("../internals/object-keys");t.exports=n?Object.defineProperties:function(e,t){s(e);for(var r,n=l(t),i=n.length,a=0;a<i;)o.f(e,r=n[a++],t[r]);return e}},{"../internals/an-object":3,"../internals/descriptors":15,"../internals/object-define-property":38,"../internals/object-keys":44}],38:[function(e,t,r){var n=e("../internals/descriptors"),i=e("../internals/ie8-dom-define"),a=e("../internals/an-object"),o=e("../internals/to-primitive"),s=Object.defineProperty;r.f=n?s:function(e,t,r){if(a(e),t=o(t,!0),a(r),i)try{return s(e,t,r)}catch(e){}if("get"in r||"set"in r)throw TypeError("Accessors not supported");return"value"in r&&(e[t]=r.value),e}},{"../internals/an-object":3,"../internals/descriptors":15,"../internals/ie8-dom-define":27,"../internals/to-primitive":60}],39:[function(e,t,r){var n=e("../internals/descriptors"),i=e("../internals/object-property-is-enumerable"),a=e("../internals/create-property-descriptor"),o=e("../internals/to-indexed-object"),s=e("../internals/to-primitive"),l=e("../internals/has"),u=e("../internals/ie8-dom-define"),f=Object.getOwnPropertyDescriptor;r.f=n?f:function(e,t){if(e=o(e),t=s(t,!0),u)try{return f(e,t)}catch(e){}if(l(e,t))return a(!i.f.call(e,t),e[t])}},{"../internals/create-property-descriptor":12,"../internals/descriptors":15,"../internals/has":23,"../internals/ie8-dom-define":27,"../internals/object-property-is-enumerable":45,"../internals/to-indexed-object":56,"../internals/to-primitive":60}],40:[function(e,t,r){var n=e("../internals/to-indexed-object"),i=e("../internals/object-get-own-property-names").f,a={}.toString,o="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];t.exports.f=function(e){return o&&"[object Window]"==a.call(e)?function(e){try{return i(e)}catch(e){return o.slice()}}(e):i(n(e))}},{"../internals/object-get-own-property-names":41,"../internals/to-indexed-object":56}],41:[function(e,t,r){var n=e("../internals/object-keys-internal"),i=e("../internals/enum-bug-keys").concat("length","prototype");r.f=Object.getOwnPropertyNames||function(e){return n(e,i)}},{"../internals/enum-bug-keys":17,"../internals/object-keys-internal":43}],42:[function(e,t,r){r.f=Object.getOwnPropertySymbols},{}],43:[function(e,t,r){var o=e("../internals/has"),s=e("../internals/to-indexed-object"),l=e("../internals/array-includes").indexOf,u=e("../internals/hidden-keys");t.exports=function(e,t){var r,n=s(e),i=0,a=[];for(r in n)!o(u,r)&&o(n,r)&&a.push(r);for(;t.length>i;)o(n,r=t[i++])&&(~l(a,r)||a.push(r));return a}},{"../internals/array-includes":4,"../internals/has":23,"../internals/hidden-keys":24,"../internals/to-indexed-object":56}],44:[function(e,t,r){var n=e("../internals/object-keys-internal"),i=e("../internals/enum-bug-keys");t.exports=Object.keys||function(e){return n(e,i)}},{"../internals/enum-bug-keys":17,"../internals/object-keys-internal":43}],45:[function(e,t,r){"use strict";var n={}.propertyIsEnumerable,i=Object.getOwnPropertyDescriptor,a=i&&!n.call({1:2},1);r.f=a?function(e){var t=i(this,e);return!!t&&t.enumerable}:n},{}],46:[function(e,t,r){"use strict";var n=e("../internals/classof"),i={};i[e("../internals/well-known-symbol")("toStringTag")]="z",t.exports="[object z]"!==String(i)?function(){return"[object "+n(this)+"]"}:i.toString},{"../internals/classof":10,"../internals/well-known-symbol":62}],47:[function(e,t,r){var n=e("../internals/get-built-in"),i=e("../internals/object-get-own-property-names"),a=e("../internals/object-get-own-property-symbols"),o=e("../internals/an-object");t.exports=n("Reflect","ownKeys")||function(e){var t=i.f(o(e)),r=a.f;return r?t.concat(r(e)):t}},{"../internals/an-object":3,"../internals/get-built-in":21,"../internals/object-get-own-property-names":41,"../internals/object-get-own-property-symbols":42}],48:[function(e,t,r){t.exports=e("../internals/global")},{"../internals/global":22}],49:[function(e,t,r){var s=e("../internals/global"),n=e("../internals/shared"),l=e("../internals/hide"),u=e("../internals/has"),f=e("../internals/set-global"),i=e("../internals/function-to-string"),a=e("../internals/internal-state"),o=a.get,c=a.enforce,d=String(i).split("toString");n("inspectSource",function(e){return i.call(e)}),(t.exports=function(e,t,r,n){var i=!!n&&!!n.unsafe,a=!!n&&!!n.enumerable,o=!!n&&!!n.noTargetGet;"function"==typeof r&&("string"!=typeof t||u(r,"name")||l(r,"name",t),c(r).source=d.join("string"==typeof t?t:"")),e!==s?(i?!o&&e[t]&&(a=!0):delete e[t],a?e[t]=r:l(e,t,r)):a?e[t]=r:f(t,r)})(Function.prototype,"toString",function(){return"function"==typeof this&&o(this).source||i.call(this)})},{"../internals/function-to-string":20,"../internals/global":22,"../internals/has":23,"../internals/hide":25,"../internals/internal-state":29,"../internals/set-global":51,"../internals/shared":54}],50:[function(e,t,r){t.exports=function(e){if(null==e)throw TypeError("Can't call method on "+e);return e}},{}],51:[function(e,t,r){var n=e("../internals/global"),i=e("../internals/hide");t.exports=function(t,r){try{i(n,t,r)}catch(e){n[t]=r}return r}},{"../internals/global":22,"../internals/hide":25}],52:[function(e,t,r){var n=e("../internals/object-define-property").f,i=e("../internals/has"),a=e("../internals/well-known-symbol")("toStringTag");t.exports=function(e,t,r){e&&!i(e=r?e:e.prototype,a)&&n(e,a,{configurable:!0,value:t})}},{"../internals/has":23,"../internals/object-define-property":38,"../internals/well-known-symbol":62}],53:[function(e,t,r){var n=e("../internals/shared"),i=e("../internals/uid"),a=n("keys");t.exports=function(e){return a[e]||(a[e]=i(e))}},{"../internals/shared":54,"../internals/uid":61}],54:[function(e,t,r){var n=e("../internals/global"),i=e("../internals/set-global"),a=e("../internals/is-pure"),o="__core-js_shared__",s=n[o]||i(o,{});(t.exports=function(e,t){return s[e]||(s[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.2.1",mode:a?"pure":"global",copyright:"© 2019 Denis Pushkarev (zloirock.ru)"})},{"../internals/global":22,"../internals/is-pure":33,"../internals/set-global":51}],55:[function(e,t,r){var n=e("../internals/to-integer"),i=Math.max,a=Math.min;t.exports=function(e,t){var r=n(e);return r<0?i(r+t,0):a(r,t)}},{"../internals/to-integer":57}],56:[function(e,t,r){var n=e("../internals/indexed-object"),i=e("../internals/require-object-coercible");t.exports=function(e){return n(i(e))}},{"../internals/indexed-object":28,"../internals/require-object-coercible":50}],57:[function(e,t,r){var n=Math.ceil,i=Math.floor;t.exports=function(e){return isNaN(e=+e)?0:(0<e?i:n)(e)}},{}],58:[function(e,t,r){var n=e("../internals/to-integer"),i=Math.min;t.exports=function(e){return 0<e?i(n(e),9007199254740991):0}},{"../internals/to-integer":57}],59:[function(e,t,r){var n=e("../internals/require-object-coercible");t.exports=function(e){return Object(n(e))}},{"../internals/require-object-coercible":50}],60:[function(e,t,r){var i=e("../internals/is-object");t.exports=function(e,t){if(!i(e))return e;var r,n;if(t&&"function"==typeof(r=e.toString)&&!i(n=r.call(e)))return n;if("function"==typeof(r=e.valueOf)&&!i(n=r.call(e)))return n;if(!t&&"function"==typeof(r=e.toString)&&!i(n=r.call(e)))return n;throw TypeError("Can't convert object to primitive value")}},{"../internals/is-object":32}],61:[function(e,t,r){var n=0,i=Math.random();t.exports=function(e){return"Symbol("+String(void 0===e?"":e)+")_"+(++n+i).toString(36)}},{}],62:[function(e,t,r){var n=e("../internals/global"),i=e("../internals/shared"),a=e("../internals/uid"),o=e("../internals/native-symbol"),s=n.Symbol,l=i("wks");t.exports=function(e){return l[e]||(l[e]=o&&s[e]||(o?s:a)("Symbol."+e))}},{"../internals/global":22,"../internals/native-symbol":34,"../internals/shared":54,"../internals/uid":61}],63:[function(e,t,r){r.f=e("../internals/well-known-symbol")},{"../internals/well-known-symbol":62}],64:[function(e,t,r){"use strict";var n=e("../internals/export"),i=e("../internals/fails"),a=e("../internals/is-array"),o=e("../internals/is-object"),u=e("../internals/to-object"),f=e("../internals/to-length"),c=e("../internals/create-property"),d=e("../internals/array-species-create"),s=e("../internals/array-method-has-species-support"),l=e("../internals/well-known-symbol")("isConcatSpreadable"),p=9007199254740991,h="Maximum allowed index exceeded",m=!i(function(){var e=[];return e[l]=!1,e.concat()[0]!==e}),y=s("concat"),g=function(e){if(!o(e))return!1;var t=e[l];return void 0!==t?!!t:a(e)};n({target:"Array",proto:!0,forced:!m||!y},{concat:function(e){var t,r,n,i,a,o=u(this),s=d(o,0),l=0;for(t=-1,n=arguments.length;t<n;t++)if(a=-1===t?o:arguments[t],g(a)){if(i=f(a.length),p<l+i)throw TypeError(h);for(r=0;r<i;r++,l++)r in a&&c(s,l,a[r])}else{if(p<=l)throw TypeError(h);c(s,l++,a)}return s.length=l,s}})},{"../internals/array-method-has-species-support":6,"../internals/array-species-create":7,"../internals/create-property":13,"../internals/export":18,"../internals/fails":19,"../internals/is-array":30,"../internals/is-object":32,"../internals/to-length":58,"../internals/to-object":59,"../internals/well-known-symbol":62}],65:[function(e,t,r){var n=e("../internals/global");e("../internals/set-to-string-tag")(n.JSON,"JSON",!0)},{"../internals/global":22,"../internals/set-to-string-tag":52}],66:[function(e,t,r){e("../internals/set-to-string-tag")(Math,"Math",!0)},{"../internals/set-to-string-tag":52}],67:[function(e,t,r){var n=e("../internals/redefine"),i=e("../internals/object-to-string"),a=Object.prototype;i!==a.toString&&n(a,"toString",i,{unsafe:!0})},{"../internals/object-to-string":46,"../internals/redefine":49}],68:[function(e,t,r){e("../internals/define-well-known-symbol")("asyncIterator")},{"../internals/define-well-known-symbol":14}],69:[function(e,t,r){"use strict";var n=e("../internals/export"),i=e("../internals/descriptors"),a=e("../internals/global"),o=e("../internals/has"),s=e("../internals/is-object"),l=e("../internals/object-define-property").f,u=e("../internals/copy-constructor-properties"),f=a.Symbol;if(i&&"function"==typeof f&&(!("description"in f.prototype)||void 0!==f().description)){var c={},d=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:String(arguments[0]),t=this instanceof d?new f(e):void 0===e?f():f(e);return""===e&&(c[t]=!0),t};u(d,f);var p=d.prototype=f.prototype;p.constructor=d;var h=p.toString,m="Symbol(test)"==String(f("test")),y=/^Symbol\((.*)\)[^)]+$/;l(p,"description",{configurable:!0,get:function(){var e=s(this)?this.valueOf():this,t=h.call(e);if(o(c,e))return"";var r=m?t.slice(7,-1):t.replace(y,"$1");return""===r?void 0:r}}),n({global:!0,forced:!0},{Symbol:d})}},{"../internals/copy-constructor-properties":11,"../internals/descriptors":15,"../internals/export":18,"../internals/global":22,"../internals/has":23,"../internals/is-object":32,"../internals/object-define-property":38}],70:[function(e,t,r){e("../internals/define-well-known-symbol")("hasInstance")},{"../internals/define-well-known-symbol":14}],71:[function(e,t,r){e("../internals/define-well-known-symbol")("isConcatSpreadable")},{"../internals/define-well-known-symbol":14}],72:[function(e,t,r){e("../internals/define-well-known-symbol")("iterator")},{"../internals/define-well-known-symbol":14}],73:[function(e,t,r){"use strict";var n=e("../internals/export"),i=e("../internals/global"),a=e("../internals/is-pure"),o=e("../internals/descriptors"),s=e("../internals/native-symbol"),l=e("../internals/fails"),u=e("../internals/has"),f=e("../internals/is-array"),c=e("../internals/is-object"),d=e("../internals/an-object"),p=e("../internals/to-object"),h=e("../internals/to-indexed-object"),m=e("../internals/to-primitive"),y=e("../internals/create-property-descriptor"),g=e("../internals/object-create"),v=e("../internals/object-keys"),_=e("../internals/object-get-own-property-names"),b=e("../internals/object-get-own-property-names-external"),E=e("../internals/object-get-own-property-symbols"),S=e("../internals/object-get-own-property-descriptor"),O=e("../internals/object-define-property"),A=e("../internals/object-property-is-enumerable"),x=e("../internals/hide"),M=e("../internals/redefine"),w=e("../internals/shared"),R=e("../internals/shared-key"),P=e("../internals/hidden-keys"),j=e("../internals/uid"),I=e("../internals/well-known-symbol"),T=e("../internals/wrapped-well-known-symbol"),$=e("../internals/define-well-known-symbol"),D=e("../internals/set-to-string-tag"),N=e("../internals/internal-state"),C=e("../internals/array-iteration").forEach,F=R("hidden"),L="Symbol",U="prototype",k=I("toPrimitive"),Y=N.set,B=N.getterFor(L),K=Object[U],W=i.Symbol,G=i.JSON,Z=G&&G.stringify,V=S.f,H=O.f,q=b.f,z=A.f,X=w("symbols"),J=w("op-symbols"),Q=w("string-to-symbol-registry"),ee=w("symbol-to-string-registry"),te=w("wks"),re=i.QObject,ne=!re||!re[U]||!re[U].findChild,ie=o&&l(function(){return 7!=g(H({},"a",{get:function(){return H(this,"a",{value:7}).a}})).a})?function(e,t,r){var n=V(K,t);n&&delete K[t],H(e,t,r),n&&e!==K&&H(K,t,n)}:H,ae=function(e,t){var r=X[e]=g(W[U]);return Y(r,{type:L,tag:e,description:t}),o||(r.description=t),r},oe=s&&"symbol"==typeof W.iterator?function(e){return"symbol"==typeof e}:function(e){return Object(e)instanceof W},se=function(e,t,r){e===K&&se(J,t,r),d(e);var n=m(t,!0);return d(r),u(X,n)?(r.enumerable?(u(e,F)&&e[F][n]&&(e[F][n]=!1),r=g(r,{enumerable:y(0,!1)})):(u(e,F)||H(e,F,y(1,{})),e[F][n]=!0),ie(e,n,r)):H(e,n,r)},le=function(t,e){d(t);var r=h(e),n=v(r).concat(de(r));return C(n,function(e){o&&!ue.call(r,e)||se(t,e,r[e])}),t},ue=function(e){var t=m(e,!0),r=z.call(this,t);return!(this===K&&u(X,t)&&!u(J,t))&&(!(r||!u(this,t)||!u(X,t)||u(this,F)&&this[F][t])||r)},fe=function(e,t){var r=h(e),n=m(t,!0);if(r!==K||!u(X,n)||u(J,n)){var i=V(r,n);return!i||!u(X,n)||u(r,F)&&r[F][n]||(i.enumerable=!0),i}},ce=function(e){var t=q(h(e)),r=[];return C(t,function(e){u(X,e)||u(P,e)||r.push(e)}),r},de=function(e){var t=e===K,r=q(t?J:h(e)),n=[];return C(r,function(e){!u(X,e)||t&&!u(K,e)||n.push(X[e])}),n};s||(M((W=function(){if(this instanceof W)throw TypeError("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?String(arguments[0]):void 0,t=j(e),r=function(e){this===K&&r.call(J,e),u(this,F)&&u(this[F],t)&&(this[F][t]=!1),ie(this,t,y(1,e))};return o&&ne&&ie(K,t,{configurable:!0,set:r}),ae(t,e)})[U],"toString",function(){return B(this).tag}),A.f=ue,O.f=se,S.f=fe,_.f=b.f=ce,E.f=de,o&&(H(W[U],"description",{configurable:!0,get:function(){return B(this).description}}),a||M(K,"propertyIsEnumerable",ue,{unsafe:!0})),T.f=function(e){return ae(I(e),e)}),n({global:!0,wrap:!0,forced:!s,sham:!s},{Symbol:W}),C(v(te),function(e){$(e)}),n({target:L,stat:!0,forced:!s},{for:function(e){var t=String(e);if(u(Q,t))return Q[t];var r=W(t);return Q[t]=r,ee[r]=t,r},keyFor:function(e){if(!oe(e))throw TypeError(e+" is not a symbol");if(u(ee,e))return ee[e]},useSetter:function(){ne=!0},useSimple:function(){ne=!1}}),n({target:"Object",stat:!0,forced:!s,sham:!o},{create:function(e,t){return void 0===t?g(e):le(g(e),t)},defineProperty:se,defineProperties:le,getOwnPropertyDescriptor:fe}),n({target:"Object",stat:!0,forced:!s},{getOwnPropertyNames:ce,getOwnPropertySymbols:de}),n({target:"Object",stat:!0,forced:l(function(){E.f(1)})},{getOwnPropertySymbols:function(e){return E.f(p(e))}}),G&&n({target:"JSON",stat:!0,forced:!s||l(function(){var e=W();return"[null]"!=Z([e])||"{}"!=Z({a:e})||"{}"!=Z(Object(e))})},{stringify:function(e){for(var t,r,n=[e],i=1;arguments.length>i;)n.push(arguments[i++]);if(r=t=n[1],(c(t)||void 0!==e)&&!oe(e))return f(t)||(t=function(e,t){if("function"==typeof r&&(t=r.call(this,e,t)),!oe(t))return t}),n[1]=t,Z.apply(G,n)}}),W[U][k]||x(W[U],k,W[U].valueOf),D(W,L),P[F]=!0},{"../internals/an-object":3,"../internals/array-iteration":5,"../internals/create-property-descriptor":12,"../internals/define-well-known-symbol":14,"../internals/descriptors":15,"../internals/export":18,"../internals/fails":19,"../internals/global":22,"../internals/has":23,"../internals/hidden-keys":24,"../internals/hide":25,"../internals/internal-state":29,"../internals/is-array":30,"../internals/is-object":32,"../internals/is-pure":33,"../internals/native-symbol":34,"../internals/object-create":36,"../internals/object-define-property":38,"../internals/object-get-own-property-descriptor":39,"../internals/object-get-own-property-names":41,"../internals/object-get-own-property-names-external":40,"../internals/object-get-own-property-symbols":42,"../internals/object-keys":44,"../internals/object-property-is-enumerable":45,"../internals/redefine":49,"../internals/set-to-string-tag":52,"../internals/shared":54,"../internals/shared-key":53,"../internals/to-indexed-object":56,"../internals/to-object":59,"../internals/to-primitive":60,"../internals/uid":61,"../internals/well-known-symbol":62,"../internals/wrapped-well-known-symbol":63}],74:[function(e,t,r){e("../internals/define-well-known-symbol")("matchAll")},{"../internals/define-well-known-symbol":14}],75:[function(e,t,r){e("../internals/define-well-known-symbol")("match")},{"../internals/define-well-known-symbol":14}],76:[function(e,t,r){e("../internals/define-well-known-symbol")("replace")},{"../internals/define-well-known-symbol":14}],77:[function(e,t,r){e("../internals/define-well-known-symbol")("search")},{"../internals/define-well-known-symbol":14}],78:[function(e,t,r){e("../internals/define-well-known-symbol")("species")},{"../internals/define-well-known-symbol":14}],79:[function(e,t,r){e("../internals/define-well-known-symbol")("split")},{"../internals/define-well-known-symbol":14}],80:[function(e,t,r){e("../internals/define-well-known-symbol")("toPrimitive")},{"../internals/define-well-known-symbol":14}],81:[function(e,t,r){e("../internals/define-well-known-symbol")("toStringTag")},{"../internals/define-well-known-symbol":14}],82:[function(e,t,r){e("../internals/define-well-known-symbol")("unscopables")},{"../internals/define-well-known-symbol":14}],83:[function(e,Z,t){(function(e){var t="Expected a function",n="__lodash_hash_undefined__",r=1/0,i="[object Function]",a="[object GeneratorFunction]",o="[object Symbol]",s=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,l=/^\w*$/,u=/^\./,f=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,c=/\\(\\)?/g,d=/^\[object .+?Constructor\]$/,p="object"==typeof e&&e&&e.Object===Object&&e,h="object"==typeof self&&self&&self.Object===Object&&self,m=p||h||Function("return this")();var y,g=Array.prototype,v=Function.prototype,_=Object.prototype,b=m["__core-js_shared__"],E=(y=/[^.]+$/.exec(b&&b.keys&&b.keys.IE_PROTO||""))?"Symbol(src)_1."+y:"",S=v.toString,O=_.hasOwnProperty,A=_.toString,x=RegExp("^"+S.call(O).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),M=m.Symbol,w=g.splice,R=U(m,"Map"),P=U(Object,"create"),j=M?M.prototype:void 0,I=j?j.toString:void 0;function T(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function $(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function D(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function N(e,t){for(var r,n,i=e.length;i--;)if((r=e[i][0])===(n=t)||r!=r&&n!=n)return i;return-1}function C(e,t){for(var r,n=0,i=(t=function(e,t){if(K(e))return!1;var r=typeof e;if("number"==r||"symbol"==r||"boolean"==r||null==e||G(e))return!0;return l.test(e)||!s.test(e)||null!=t&&e in Object(t)}(t,e)?[t]:K(r=t)?r:k(r)).length;null!=e&&n<i;)e=e[Y(t[n++])];return n&&n==i?e:void 0}function F(e){return!(!W(e)||(t=e,E&&E in t))&&((n=W(r=e)?A.call(r):"")==i||n==a||function(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}(e)?x:d).test(function(e){if(null!=e){try{return S.call(e)}catch(e){}try{return e+""}catch(e){}}return""}(e));var t,r,n}function L(e,t){var r,n,i=e.__data__;return("string"==(n=typeof(r=t))||"number"==n||"symbol"==n||"boolean"==n?"__proto__"!==r:null===r)?i["string"==typeof t?"string":"hash"]:i.map}function U(e,t){var r,n,i=(n=t,null==(r=e)?void 0:r[n]);return F(i)?i:void 0}T.prototype.clear=function(){this.__data__=P?P(null):{}},T.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},T.prototype.get=function(e){var t=this.__data__;if(P){var r=t[e];return r===n?void 0:r}return O.call(t,e)?t[e]:void 0},T.prototype.has=function(e){var t=this.__data__;return P?void 0!==t[e]:O.call(t,e)},T.prototype.set=function(e,t){return this.__data__[e]=P&&void 0===t?n:t,this},$.prototype.clear=function(){this.__data__=[]},$.prototype.delete=function(e){var t=this.__data__,r=N(t,e);return!(r<0||(r==t.length-1?t.pop():w.call(t,r,1),0))},$.prototype.get=function(e){var t=this.__data__,r=N(t,e);return r<0?void 0:t[r][1]},$.prototype.has=function(e){return-1<N(this.__data__,e)},$.prototype.set=function(e,t){var r=this.__data__,n=N(r,e);return n<0?r.push([e,t]):r[n][1]=t,this},D.prototype.clear=function(){this.__data__={hash:new T,map:new(R||$),string:new T}},D.prototype.delete=function(e){return L(this,e).delete(e)},D.prototype.get=function(e){return L(this,e).get(e)},D.prototype.has=function(e){return L(this,e).has(e)},D.prototype.set=function(e,t){return L(this,e).set(e,t),this};var k=B(function(e){var t;e=null==(t=e)?"":function(e){if("string"==typeof e)return e;if(G(e))return I?I.call(e):"";var t=e+"";return"0"==t&&1/e==-r?"-0":t}(t);var i=[];return u.test(e)&&i.push(""),e.replace(f,function(e,t,r,n){i.push(r?n.replace(c,"$1"):t||e)}),i});function Y(e){if("string"==typeof e||G(e))return e;var t=e+"";return"0"==t&&1/e==-r?"-0":t}function B(i,a){if("function"!=typeof i||a&&"function"!=typeof a)throw new TypeError(t);var o=function(){var e=arguments,t=a?a.apply(this,e):e[0],r=o.cache;if(r.has(t))return r.get(t);var n=i.apply(this,e);return o.cache=r.set(t,n),n};return o.cache=new(B.Cache||D),o}B.Cache=D;var K=Array.isArray;function W(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function G(e){return"symbol"==typeof e||!!(t=e)&&"object"==typeof t&&A.call(e)==o;var t}Z.exports=function(e,t,r){var n=null==e?void 0:C(e,t);return void 0===n?r:n}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],84:[function(e,Qe,et){(function(e){var n="__lodash_hash_undefined__",b=1,g=2,r=9007199254740991,v="[object Arguments]",_="[object Array]",i="[object AsyncFunction]",E="[object Boolean]",S="[object Date]",O="[object Error]",a="[object Function]",o="[object GeneratorFunction]",A="[object Map]",x="[object Number]",s="[object Null]",M="[object Object]",l="[object Promise]",u="[object Proxy]",w="[object RegExp]",R="[object Set]",P="[object String]",j="[object Symbol]",f="[object Undefined]",c="[object WeakMap]",I="[object ArrayBuffer]",T="[object DataView]",d=/^\[object .+?Constructor\]$/,p=/^(?:0|[1-9]\d*)$/,t={};t["[object Float32Array]"]=t["[object Float64Array]"]=t["[object Int8Array]"]=t["[object Int16Array]"]=t["[object Int32Array]"]=t["[object Uint8Array]"]=t["[object Uint8ClampedArray]"]=t["[object Uint16Array]"]=t["[object Uint32Array]"]=!0,t[v]=t[_]=t[I]=t[E]=t[T]=t[S]=t[O]=t[a]=t[A]=t[x]=t[M]=t[w]=t[R]=t[P]=t[c]=!1;var h="object"==typeof e&&e&&e.Object===Object&&e,m="object"==typeof self&&self&&self.Object===Object&&self,y=h||m||Function("return this")(),$="object"==typeof et&&et&&!et.nodeType&&et,D=$&&"object"==typeof Qe&&Qe&&!Qe.nodeType&&Qe,N=D&&D.exports===$,C=N&&h.process,F=function(){try{return C&&C.binding&&C.binding("util")}catch(e){}}(),L=F&&F.isTypedArray;function U(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}function k(e){var r=-1,n=Array(e.size);return e.forEach(function(e,t){n[++r]=[t,e]}),n}function Y(e){var t=-1,r=Array(e.size);return e.forEach(function(e){r[++t]=e}),r}var B,K,W,G=Array.prototype,Z=Function.prototype,V=Object.prototype,H=y["__core-js_shared__"],q=Z.toString,z=V.hasOwnProperty,X=(B=/[^.]+$/.exec(H&&H.keys&&H.keys.IE_PROTO||""))?"Symbol(src)_1."+B:"",J=V.toString,Q=RegExp("^"+q.call(z).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ee=N?y.Buffer:void 0,te=y.Symbol,re=y.Uint8Array,ne=V.propertyIsEnumerable,ie=G.splice,ae=te?te.toStringTag:void 0,oe=Object.getOwnPropertySymbols,se=ee?ee.isBuffer:void 0,le=(K=Object.keys,W=Object,function(e){return K(W(e))}),ue=Fe(y,"DataView"),fe=Fe(y,"Map"),ce=Fe(y,"Promise"),de=Fe(y,"Set"),pe=Fe(y,"WeakMap"),he=Fe(Object,"create"),me=Ye(ue),ye=Ye(fe),ge=Ye(ce),ve=Ye(de),_e=Ye(pe),be=te?te.prototype:void 0,Ee=be?be.valueOf:void 0;function Se(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Oe(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Ae(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function xe(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new Ae;++t<r;)this.add(e[t])}function Me(e){var t=this.__data__=new Oe(e);this.size=t.size}function we(e,t){var r=We(e),n=!r&&Ke(e),i=!r&&!n&&Ge(e),a=!r&&!n&&!i&&Xe(e),o=r||n||i||a,s=o?function(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}(e.length,String):[],l=s.length;for(var u in e)!t&&!z.call(e,u)||o&&("length"==u||i&&("offset"==u||"parent"==u)||a&&("buffer"==u||"byteLength"==u||"byteOffset"==u)||ke(u,l))||s.push(u);return s}function Re(e,t){for(var r=e.length;r--;)if(Be(e[r][0],t))return r;return-1}function Pe(e){return null==e?void 0===e?f:s:ae&&ae in Object(e)?function(e){var t=z.call(e,ae),r=e[ae];try{var n=!(e[ae]=void 0)}catch(e){}var i=J.call(e);n&&(t?e[ae]=r:delete e[ae]);return i}(e):(t=e,J.call(t));var t}function je(e){return qe(e)&&Pe(e)==v}function Ie(e,t,r,n,i){return e===t||(null==e||null==t||!qe(e)&&!qe(t)?e!=e&&t!=t:function(e,t,r,n,i,a){var o=We(e),s=We(t),l=o?_:Ue(e),u=s?_:Ue(t),f=(l=l==v?M:l)==M,c=(u=u==v?M:u)==M,d=l==u;if(d&&Ge(e)){if(!Ge(t))return!1;f=!(o=!0)}if(d&&!f)return a||(a=new Me),o||Xe(e)?De(e,t,r,n,i,a):function(e,t,r,n,i,a,o){switch(r){case T:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case I:return!(e.byteLength!=t.byteLength||!a(new re(e),new re(t)));case E:case S:case x:return Be(+e,+t);case O:return e.name==t.name&&e.message==t.message;case w:case P:return e==t+"";case A:var s=k;case R:var l=n&b;if(s||(s=Y),e.size!=t.size&&!l)return!1;var u=o.get(e);if(u)return u==t;n|=g,o.set(e,t);var f=De(s(e),s(t),n,i,a,o);return o.delete(e),f;case j:if(Ee)return Ee.call(e)==Ee.call(t)}return!1}(e,t,l,r,n,i,a);if(!(r&b)){var p=f&&z.call(e,"__wrapped__"),h=c&&z.call(t,"__wrapped__");if(p||h){var m=p?e.value():e,y=h?t.value():t;return a||(a=new Me),i(m,y,r,n,a)}}return!!d&&(a||(a=new Me),function(e,t,r,n,i,a){var o=r&b,s=Ne(e),l=s.length,u=Ne(t).length;if(l!=u&&!o)return!1;for(var f=l;f--;){var c=s[f];if(!(o?c in t:z.call(t,c)))return!1}var d=a.get(e);if(d&&a.get(t))return d==t;var p=!0;a.set(e,t),a.set(t,e);for(var h=o;++f<l;){c=s[f];var m=e[c],y=t[c];if(n)var g=o?n(y,m,c,t,e,a):n(m,y,c,e,t,a);if(!(void 0===g?m===y||i(m,y,r,n,a):g)){p=!1;break}h||(h="constructor"==c)}if(p&&!h){var v=e.constructor,_=t.constructor;v!=_&&"constructor"in e&&"constructor"in t&&!("function"==typeof v&&v instanceof v&&"function"==typeof _&&_ instanceof _)&&(p=!1)}return a.delete(e),a.delete(t),p}(e,t,r,n,i,a))}(e,t,r,n,Ie,i))}function Te(e){return!(!He(e)||(t=e,X&&X in t))&&(Ze(e)?Q:d).test(Ye(e));var t}function $e(e){if(r=(t=e)&&t.constructor,n="function"==typeof r&&r.prototype||V,t!==n)return le(e);var t,r,n,i=[];for(var a in Object(e))z.call(e,a)&&"constructor"!=a&&i.push(a);return i}function De(e,t,n,i,a,o){var r=n&b,s=e.length,l=t.length;if(s!=l&&!(r&&s<l))return!1;var u=o.get(e);if(u&&o.get(t))return u==t;var f=-1,c=!0,d=n&g?new xe:void 0;for(o.set(e,t),o.set(t,e);++f<s;){var p=e[f],h=t[f];if(i)var m=r?i(h,p,f,t,e,o):i(p,h,f,e,t,o);if(void 0!==m){if(m)continue;c=!1;break}if(d){if(!U(t,function(e,t){if(r=t,!d.has(r)&&(p===e||a(p,e,n,i,o)))return d.push(t);var r})){c=!1;break}}else if(p!==h&&!a(p,h,n,i,o)){c=!1;break}}return o.delete(e),o.delete(t),c}function Ne(e){return r=Le,n=Je(t=e),We(t)?n:function(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}(n,r(t));var t,r,n}function Ce(e,t){var r,n,i=e.__data__;return("string"==(n=typeof(r=t))||"number"==n||"symbol"==n||"boolean"==n?"__proto__"!==r:null===r)?i["string"==typeof t?"string":"hash"]:i.map}function Fe(e,t){var r,n,i=(n=t,null==(r=e)?void 0:r[n]);return Te(i)?i:void 0}Se.prototype.clear=function(){this.__data__=he?he(null):{},this.size=0},Se.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},Se.prototype.get=function(e){var t=this.__data__;if(he){var r=t[e];return r===n?void 0:r}return z.call(t,e)?t[e]:void 0},Se.prototype.has=function(e){var t=this.__data__;return he?void 0!==t[e]:z.call(t,e)},Se.prototype.set=function(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=he&&void 0===t?n:t,this},Oe.prototype.clear=function(){this.__data__=[],this.size=0},Oe.prototype.delete=function(e){var t=this.__data__,r=Re(t,e);return!(r<0||(r==t.length-1?t.pop():ie.call(t,r,1),--this.size,0))},Oe.prototype.get=function(e){var t=this.__data__,r=Re(t,e);return r<0?void 0:t[r][1]},Oe.prototype.has=function(e){return-1<Re(this.__data__,e)},Oe.prototype.set=function(e,t){var r=this.__data__,n=Re(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this},Ae.prototype.clear=function(){this.size=0,this.__data__={hash:new Se,map:new(fe||Oe),string:new Se}},Ae.prototype.delete=function(e){var t=Ce(this,e).delete(e);return this.size-=t?1:0,t},Ae.prototype.get=function(e){return Ce(this,e).get(e)},Ae.prototype.has=function(e){return Ce(this,e).has(e)},Ae.prototype.set=function(e,t){var r=Ce(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this},xe.prototype.add=xe.prototype.push=function(e){return this.__data__.set(e,n),this},xe.prototype.has=function(e){return this.__data__.has(e)},Me.prototype.clear=function(){this.__data__=new Oe,this.size=0},Me.prototype.delete=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r},Me.prototype.get=function(e){return this.__data__.get(e)},Me.prototype.has=function(e){return this.__data__.has(e)},Me.prototype.set=function(e,t){var r=this.__data__;if(r instanceof Oe){var n=r.__data__;if(!fe||n.length<199)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new Ae(n)}return r.set(e,t),this.size=r.size,this};var Le=oe?function(t){return null==t?[]:(t=Object(t),function(e,t){for(var r=-1,n=null==e?0:e.length,i=0,a=[];++r<n;){var o=e[r];t(o,r,e)&&(a[i++]=o)}return a}(oe(t),function(e){return ne.call(t,e)}))}:function(){return[]},Ue=Pe;function ke(e,t){return!!(t=null==t?r:t)&&("number"==typeof e||p.test(e))&&-1<e&&e%1==0&&e<t}function Ye(e){if(null!=e){try{return q.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Be(e,t){return e===t||e!=e&&t!=t}(ue&&Ue(new ue(new ArrayBuffer(1)))!=T||fe&&Ue(new fe)!=A||ce&&Ue(ce.resolve())!=l||de&&Ue(new de)!=R||pe&&Ue(new pe)!=c)&&(Ue=function(e){var t=Pe(e),r=t==M?e.constructor:void 0,n=r?Ye(r):"";if(n)switch(n){case me:return T;case ye:return A;case ge:return l;case ve:return R;case _e:return c}return t});var Ke=je(function(){return arguments}())?je:function(e){return qe(e)&&z.call(e,"callee")&&!ne.call(e,"callee")},We=Array.isArray;var Ge=se||function(){return!1};function Ze(e){if(!He(e))return!1;var t=Pe(e);return t==a||t==o||t==i||t==u}function Ve(e){return"number"==typeof e&&-1<e&&e%1==0&&e<=r}function He(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function qe(e){return null!=e&&"object"==typeof e}var ze,Xe=L?(ze=L,function(e){return ze(e)}):function(e){return qe(e)&&Ve(e.length)&&!!t[Pe(e)]};function Je(e){return null!=(t=e)&&Ve(t.length)&&!Ze(t)?we(e):$e(e);var t}Qe.exports=function(e,t){return Ie(e,t)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],85:[function(e,t,r){var n,i,a=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function l(t){if(n===setTimeout)return setTimeout(t,0);if((n===o||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:o}catch(e){n=o}try{i="function"==typeof clearTimeout?clearTimeout:s}catch(e){i=s}}();var u,f=[],c=!1,d=-1;function p(){c&&u&&(c=!1,u.length?f=u.concat(f):d=-1,f.length&&h())}function h(){if(!c){var e=l(p);c=!0;for(var t=f.length;t;){for(u=f,f=[];++d<t;)u&&u[d].run();d=-1,t=f.length}u=null,c=!1,function(t){if(i===clearTimeout)return clearTimeout(t);if((i===s||!i)&&clearTimeout)return i=clearTimeout,clearTimeout(t);try{i(t)}catch(e){try{return i.call(null,t)}catch(e){return i.call(this,t)}}}(e)}}function m(e,t){this.fun=e,this.array=t}function y(){}a.nextTick=function(e){var t=new Array(arguments.length-1);if(1<arguments.length)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];f.push(new m(e,t)),1!==f.length||c||l(h)},m.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=y,a.addListener=y,a.once=y,a.off=y,a.removeListener=y,a.removeAllListeners=y,a.emit=y,a.prependListener=y,a.prependOnceListener=y,a.listeners=function(e){return[]},a.binding=function(e){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(e){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},{}],86:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n=Oe(e("./lib/toDate")),i=Oe(e("./lib/toFloat")),a=Oe(e("./lib/toInt")),o=Oe(e("./lib/toBoolean")),s=Oe(e("./lib/equals")),l=Oe(e("./lib/contains")),u=Oe(e("./lib/matches")),f=Oe(e("./lib/isEmail")),c=Oe(e("./lib/isURL")),d=Oe(e("./lib/isMACAddress")),p=Oe(e("./lib/isIP")),h=Oe(e("./lib/isIPRange")),m=Oe(e("./lib/isFQDN")),y=Oe(e("./lib/isBoolean")),g=Se(e("./lib/isAlpha")),v=Se(e("./lib/isAlphanumeric")),_=Oe(e("./lib/isNumeric")),b=Oe(e("./lib/isPort")),E=Oe(e("./lib/isLowercase")),S=Oe(e("./lib/isUppercase")),O=Oe(e("./lib/isAscii")),A=Oe(e("./lib/isFullWidth")),x=Oe(e("./lib/isHalfWidth")),M=Oe(e("./lib/isVariableWidth")),w=Oe(e("./lib/isMultibyte")),R=Oe(e("./lib/isSurrogatePair")),P=Oe(e("./lib/isInt")),j=Se(e("./lib/isFloat")),I=Oe(e("./lib/isDecimal")),T=Oe(e("./lib/isHexadecimal")),$=Oe(e("./lib/isDivisibleBy")),D=Oe(e("./lib/isHexColor")),N=Oe(e("./lib/isISRC")),C=Oe(e("./lib/isMD5")),F=Oe(e("./lib/isHash")),L=Oe(e("./lib/isJWT")),U=Oe(e("./lib/isJSON")),k=Oe(e("./lib/isEmpty")),Y=Oe(e("./lib/isLength")),B=Oe(e("./lib/isByteLength")),K=Oe(e("./lib/isUUID")),W=Oe(e("./lib/isMongoId")),G=Oe(e("./lib/isAfter")),Z=Oe(e("./lib/isBefore")),V=Oe(e("./lib/isIn")),H=Oe(e("./lib/isCreditCard")),q=Oe(e("./lib/isIdentityCard")),z=Oe(e("./lib/isISIN")),X=Oe(e("./lib/isISBN")),J=Oe(e("./lib/isISSN")),Q=Se(e("./lib/isMobilePhone")),ee=Oe(e("./lib/isCurrency")),te=Oe(e("./lib/isISO8601")),re=Oe(e("./lib/isRFC3339")),ne=Oe(e("./lib/isISO31661Alpha2")),ie=Oe(e("./lib/isISO31661Alpha3")),ae=Oe(e("./lib/isBase32")),oe=Oe(e("./lib/isBase64")),se=Oe(e("./lib/isDataURI")),le=Oe(e("./lib/isMagnetURI")),ue=Oe(e("./lib/isMimeType")),fe=Oe(e("./lib/isLatLong")),ce=Se(e("./lib/isPostalCode")),de=Oe(e("./lib/ltrim")),pe=Oe(e("./lib/rtrim")),he=Oe(e("./lib/trim")),me=Oe(e("./lib/escape")),ye=Oe(e("./lib/unescape")),ge=Oe(e("./lib/stripLow")),ve=Oe(e("./lib/whitelist")),_e=Oe(e("./lib/blacklist")),be=Oe(e("./lib/isWhitelisted")),Ee=Oe(e("./lib/normalizeEmail"));function Se(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)){var n=Object.defineProperty&&Object.getOwnPropertyDescriptor?Object.getOwnPropertyDescriptor(e,r):{};n.get||n.set?Object.defineProperty(t,r,n):t[r]=e[r]}return t.default=e,t}function Oe(e){return e&&e.__esModule?e:{default:e}}var Ae={version:"11.1.0",toDate:n.default,toFloat:i.default,toInt:a.default,toBoolean:o.default,equals:s.default,contains:l.default,matches:u.default,isEmail:f.default,isURL:c.default,isMACAddress:d.default,isIP:p.default,isIPRange:h.default,isFQDN:m.default,isBoolean:y.default,isAlpha:g.default,isAlphaLocales:g.locales,isAlphanumeric:v.default,isAlphanumericLocales:v.locales,isNumeric:_.default,isPort:b.default,isLowercase:E.default,isUppercase:S.default,isAscii:O.default,isFullWidth:A.default,isHalfWidth:x.default,isVariableWidth:M.default,isMultibyte:w.default,isSurrogatePair:R.default,isInt:P.default,isFloat:j.default,isFloatLocales:j.locales,isDecimal:I.default,isHexadecimal:T.default,isDivisibleBy:$.default,isHexColor:D.default,isISRC:N.default,isMD5:C.default,isHash:F.default,isJWT:L.default,isJSON:U.default,isEmpty:k.default,isLength:Y.default,isByteLength:B.default,isUUID:K.default,isMongoId:W.default,isAfter:G.default,isBefore:Z.default,isIn:V.default,isCreditCard:H.default,isIdentityCard:q.default,isISIN:z.default,isISBN:X.default,isISSN:J.default,isMobilePhone:Q.default,isMobilePhoneLocales:Q.locales,isPostalCode:ce.default,isPostalCodeLocales:ce.locales,isCurrency:ee.default,isISO8601:te.default,isRFC3339:re.default,isISO31661Alpha2:ne.default,isISO31661Alpha3:ie.default,isBase32:ae.default,isBase64:oe.default,isDataURI:se.default,isMagnetURI:le.default,isMimeType:ue.default,isLatLong:fe.default,ltrim:de.default,rtrim:pe.default,trim:he.default,escape:me.default,unescape:ye.default,stripLow:ge.default,whitelist:ve.default,blacklist:_e.default,isWhitelisted:be.default,normalizeEmail:Ee.default,toString:toString};r.default=Ae,t.exports=r.default,t.exports.default=r.default},{"./lib/blacklist":88,"./lib/contains":89,"./lib/equals":90,"./lib/escape":91,"./lib/isAfter":92,"./lib/isAlpha":93,"./lib/isAlphanumeric":94,"./lib/isAscii":95,"./lib/isBase32":96,"./lib/isBase64":97,"./lib/isBefore":98,"./lib/isBoolean":99,"./lib/isByteLength":100,"./lib/isCreditCard":101,"./lib/isCurrency":102,"./lib/isDataURI":103,"./lib/isDecimal":104,"./lib/isDivisibleBy":105,"./lib/isEmail":106,"./lib/isEmpty":107,"./lib/isFQDN":108,"./lib/isFloat":109,"./lib/isFullWidth":110,"./lib/isHalfWidth":111,"./lib/isHash":112,"./lib/isHexColor":113,"./lib/isHexadecimal":114,"./lib/isIP":115,"./lib/isIPRange":116,"./lib/isISBN":117,"./lib/isISIN":118,"./lib/isISO31661Alpha2":119,"./lib/isISO31661Alpha3":120,"./lib/isISO8601":121,"./lib/isISRC":122,"./lib/isISSN":123,"./lib/isIdentityCard":124,"./lib/isIn":125,"./lib/isInt":126,"./lib/isJSON":127,"./lib/isJWT":128,"./lib/isLatLong":129,"./lib/isLength":130,"./lib/isLowercase":131,"./lib/isMACAddress":132,"./lib/isMD5":133,"./lib/isMagnetURI":134,"./lib/isMimeType":135,"./lib/isMobilePhone":136,"./lib/isMongoId":137,"./lib/isMultibyte":138,"./lib/isNumeric":139,"./lib/isPort":140,"./lib/isPostalCode":141,"./lib/isRFC3339":142,"./lib/isSurrogatePair":143,"./lib/isURL":144,"./lib/isUUID":145,"./lib/isUppercase":146,"./lib/isVariableWidth":147,"./lib/isWhitelisted":148,"./lib/ltrim":149,"./lib/matches":150,"./lib/normalizeEmail":151,"./lib/rtrim":152,"./lib/stripLow":153,"./lib/toBoolean":154,"./lib/toDate":155,"./lib/toFloat":156,"./lib/toInt":157,"./lib/trim":158,"./lib/unescape":159,"./lib/whitelist":164}],87:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.commaDecimal=r.dotDecimal=r.arabicLocales=r.englishLocales=r.decimal=r.alphanumeric=r.alpha=void 0;var n={"en-US":/^[A-Z]+$/i,"bg-BG":/^[А-Я]+$/i,"cs-CZ":/^[A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i,"da-DK":/^[A-ZÆØÅ]+$/i,"de-DE":/^[A-ZÄÖÜß]+$/i,"el-GR":/^[Α-ω]+$/i,"es-ES":/^[A-ZÁÉÍÑÓÚÜ]+$/i,"fr-FR":/^[A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i,"it-IT":/^[A-ZÀÉÈÌÎÓÒÙ]+$/i,"nb-NO":/^[A-ZÆØÅ]+$/i,"nl-NL":/^[A-ZÁÉËÏÓÖÜÚ]+$/i,"nn-NO":/^[A-ZÆØÅ]+$/i,"hu-HU":/^[A-ZÁÉÍÓÖŐÚÜŰ]+$/i,"pl-PL":/^[A-ZĄĆĘŚŁŃÓŻŹ]+$/i,"pt-PT":/^[A-ZÃÁÀÂÇÉÊÍÕÓÔÚÜ]+$/i,"ru-RU":/^[А-ЯЁ]+$/i,"sl-SI":/^[A-ZČĆĐŠŽ]+$/i,"sk-SK":/^[A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i,"sr-RS@latin":/^[A-ZČĆŽŠĐ]+$/i,"sr-RS":/^[А-ЯЂЈЉЊЋЏ]+$/i,"sv-SE":/^[A-ZÅÄÖ]+$/i,"tr-TR":/^[A-ZÇĞİıÖŞÜ]+$/i,"uk-UA":/^[А-ЩЬЮЯЄIЇҐі]+$/i,"ku-IQ":/^[ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$/i,ar:/^[ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/};r.alpha=n;var i={"en-US":/^[0-9A-Z]+$/i,"bg-BG":/^[0-9А-Я]+$/i,"cs-CZ":/^[0-9A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i,"da-DK":/^[0-9A-ZÆØÅ]+$/i,"de-DE":/^[0-9A-ZÄÖÜß]+$/i,"el-GR":/^[0-9Α-ω]+$/i,"es-ES":/^[0-9A-ZÁÉÍÑÓÚÜ]+$/i,"fr-FR":/^[0-9A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i,"it-IT":/^[0-9A-ZÀÉÈÌÎÓÒÙ]+$/i,"hu-HU":/^[0-9A-ZÁÉÍÓÖŐÚÜŰ]+$/i,"nb-NO":/^[0-9A-ZÆØÅ]+$/i,"nl-NL":/^[0-9A-ZÁÉËÏÓÖÜÚ]+$/i,"nn-NO":/^[0-9A-ZÆØÅ]+$/i,"pl-PL":/^[0-9A-ZĄĆĘŚŁŃÓŻŹ]+$/i,"pt-PT":/^[0-9A-ZÃÁÀÂÇÉÊÍÕÓÔÚÜ]+$/i,"ru-RU":/^[0-9А-ЯЁ]+$/i,"sl-SI":/^[0-9A-ZČĆĐŠŽ]+$/i,"sk-SK":/^[0-9A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i,"sr-RS@latin":/^[0-9A-ZČĆŽŠĐ]+$/i,"sr-RS":/^[0-9А-ЯЂЈЉЊЋЏ]+$/i,"sv-SE":/^[0-9A-ZÅÄÖ]+$/i,"tr-TR":/^[0-9A-ZÇĞİıÖŞÜ]+$/i,"uk-UA":/^[0-9А-ЩЬЮЯЄIЇҐі]+$/i,"ku-IQ":/^[٠١٢٣٤٥٦٧٨٩0-9ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$/i,ar:/^[٠١٢٣٤٥٦٧٨٩0-9ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/};r.alphanumeric=i;var a={"en-US":".",ar:"٫"};r.decimal=a;var o=["AU","GB","HK","IN","NZ","ZA","ZM"];r.englishLocales=o;for(var s,l=0;l<o.length;l++)n[s="en-".concat(o[l])]=n["en-US"],i[s]=i["en-US"],a[s]=a["en-US"];var u=["AE","BH","DZ","EG","IQ","JO","KW","LB","LY","MA","QM","QA","SA","SD","SY","TN","YE"];r.arabicLocales=u;for(var f,c=0;c<u.length;c++)n[f="ar-".concat(u[c])]=n.ar,i[f]=i.ar,a[f]=a.ar;var d=["ar-EG","ar-LB","ar-LY"];r.dotDecimal=d;var p=["bg-BG","cs-CZ","da-DK","de-DE","el-GR","en-ZM","es-ES","fr-FR","it-IT","ku-IQ","hu-HU","nb-NO","nn-NO","nl-NL","pl-PL","pt-PT","ru-RU","sl-SI","sr-RS@latin","sr-RS","sv-SE","tr-TR","uk-UA"];r.commaDecimal=p;for(var h=0;h<d.length;h++)a[d[h]]=a["en-US"];for(var m=0;m<p.length;m++)a[p[m]]=",";n["pt-BR"]=n["pt-PT"],i["pt-BR"]=i["pt-PT"],a["pt-BR"]=a["pt-PT"],n["pl-Pl"]=n["pl-PL"],i["pl-Pl"]=i["pl-PL"],a["pl-Pl"]=a["pl-PL"]},{}],88:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){return(0,i.default)(e),e.replace(new RegExp("[".concat(t,"]+"),"g"),"")};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],89:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){return(0,n.default)(e),0<=e.indexOf((0,i.default)(t))};var n=a(e("./util/assertString")),i=a(e("./util/toString"));function a(e){return e&&e.__esModule?e:{default:e}}t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160,"./util/toString":163}],90:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){return(0,i.default)(e),e===t};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],91:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/\//g,"/").replace(/\\/g,"\").replace(/`/g,"`")};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],92:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:String(new Date);(0,i.default)(e);var r=(0,a.default)(t),n=(0,a.default)(e);return!!(n&&r&&r<n)};var i=n(e("./util/assertString")),a=n(e("./toDate"));function n(e){return e&&e.__esModule?e:{default:e}}t.exports=r.default,t.exports.default=r.default},{"./toDate":155,"./util/assertString":160}],93:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:"en-US";if((0,i.default)(e),t in a.alpha)return a.alpha[t].test(e);throw new Error("Invalid locale '".concat(t,"'"))},r.locales=void 0;var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n},a=e("./alpha");var o=Object.keys(a.alpha);r.locales=o},{"./alpha":87,"./util/assertString":160}],94:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:"en-US";if((0,i.default)(e),t in a.alphanumeric)return a.alphanumeric[t].test(e);throw new Error("Invalid locale '".concat(t,"'"))},r.locales=void 0;var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n},a=e("./alpha");var o=Object.keys(a.alphanumeric);r.locales=o},{"./alpha":87,"./util/assertString":160}],95:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),a.test(e)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/^[\x00-\x7F]+$/;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],96:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){(0,i.default)(e);var t=e.length;if(0<t&&t%8==0&&a.test(e))return!0;return!1};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/^[A-Z2-7]+=*$/;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],97:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){(0,i.default)(e);var t=e.length;if(!t||t%4!=0||a.test(e))return!1;var r=e.indexOf("=");return-1===r||r===t-1||r===t-2&&"="===e[t-1]};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/[^A-Z0-9+\/=]/i;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],98:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:String(new Date);(0,i.default)(e);var r=(0,a.default)(t),n=(0,a.default)(e);return!!(n&&r&&n<r)};var i=n(e("./util/assertString")),a=n(e("./toDate"));function n(e){return e&&e.__esModule?e:{default:e}}t.exports=r.default,t.exports.default=r.default},{"./toDate":155,"./util/assertString":160}],99:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),0<=["true","false","1","0"].indexOf(e)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],100:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){var r,n;(0,a.default)(e),n="object"===o(t)?(r=t.min||0,t.max):(r=arguments[1],arguments[2]);var i=encodeURI(e).split(/%..|./).length-1;return r<=i&&(void 0===n||i<=n)};var n,a=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],101:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){(0,s.default)(e);var t=e.replace(/[- ]+/g,"");if(!l.test(t))return!1;for(var r,n,i,a=0,o=t.length-1;0<=o;o--)r=t.substring(o,o+1),n=parseInt(r,10),a+=i&&10<=(n*=2)?n%10+1:n,i=!i;return!(a%10!=0||!t)};var n,s=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var l=/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14})$/;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],102:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){return(0,i.default)(e),function(e){var r="\\d{".concat(e.digits_after_decimal[0],"}");e.digits_after_decimal.forEach(function(e,t){0!==t&&(r="".concat(r,"|\\d{").concat(e,"}"))});var t="(\\".concat(e.symbol.replace(/\./g,"\\."),")").concat(e.require_symbol?"":"?"),n="[1-9]\\d{0,2}(\\".concat(e.thousands_separator,"\\d{3})*"),i="(".concat(["0","[1-9]\\d*",n].join("|"),")?"),a="(\\".concat(e.decimal_separator,"(").concat(r,"))").concat(e.require_decimal?"":"?"),o=i+(e.allow_decimal||e.require_decimal?a:"");return e.allow_negatives&&!e.parens_for_negatives&&(e.negative_sign_after_digits?o+="-?":e.negative_sign_before_digits&&(o="-?"+o)),e.allow_negative_sign_placeholder?o="( (?!\\-))?".concat(o):e.allow_space_after_symbol?o=" ?".concat(o):e.allow_space_after_digits&&(o+="( (?!$))?"),e.symbol_after_digits?o+=t:o=t+o,e.allow_negatives&&(e.parens_for_negatives?o="(\\(".concat(o,"\\)|").concat(o,")"):e.negative_sign_before_digits||e.negative_sign_after_digits||(o="-?"+o)),new RegExp("^(?!-? )(?=.*\\d)".concat(o,"$"))}(t=(0,n.default)(t,o)).test(e)};var n=a(e("./util/merge")),i=a(e("./util/assertString"));function a(e){return e&&e.__esModule?e:{default:e}}var o={symbol:"$",require_symbol:!1,allow_space_after_symbol:!1,symbol_after_digits:!1,allow_negatives:!0,parens_for_negatives:!1,negative_sign_before_digits:!1,negative_sign_after_digits:!1,allow_negative_sign_placeholder:!1,thousands_separator:",",decimal_separator:".",allow_decimal:!0,require_decimal:!1,digits_after_decimal:[2],allow_space_after_digits:!1};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160,"./util/merge":162}],103:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){(0,s.default)(e);var t=e.split(",");if(t.length<2)return!1;var r=t.shift().trim().split(";"),n=r.shift();if("data:"!==n.substr(0,5))return!1;var i=n.substr(5);if(""!==i&&!l.test(i))return!1;for(var a=0;a<r.length;a++)if(a===r.length-1&&"base64"===r[a].toLowerCase());else if(!u.test(r[a]))return!1;for(var o=0;o<t.length;o++)if(!f.test(t[o]))return!1;return!0};var n,s=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var l=/^[a-z]+\/[a-z0-9\-\+]+$/i,u=/^[a-z\-]+=[a-z0-9\-]+$/i,f=/^[a-z0-9!\$&'\(\)\*\+,;=\-\._~:@\/\?%\s]*$/i;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],104:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){if((0,i.default)(e),(t=(0,n.default)(t,l)).locale in o.decimal)return!(0,a.default)(u,e.replace(/ /g,""))&&(r=t,new RegExp("^[-+]?([0-9]+)?(\\".concat(o.decimal[r.locale],"[0-9]{").concat(r.decimal_digits,"})").concat(r.force_decimal?"":"?","$"))).test(e);var r;throw new Error("Invalid locale '".concat(t.locale,"'"))};var n=s(e("./util/merge")),i=s(e("./util/assertString")),a=s(e("./util/includes")),o=e("./alpha");function s(e){return e&&e.__esModule?e:{default:e}}var l={force_decimal:!1,decimal_digits:"1,",locale:"en-US"},u=["","-","+"];t.exports=r.default,t.exports.default=r.default},{"./alpha":87,"./util/assertString":160,"./util/includes":161,"./util/merge":162}],105:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){return(0,n.default)(e),(0,i.default)(e)%parseInt(t,10)==0};var n=a(e("./util/assertString")),i=a(e("./toFloat"));function a(e){return e&&e.__esModule?e:{default:e}}t.exports=r.default,t.exports.default=r.default},{"./toFloat":156,"./util/assertString":160}],106:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){if((0,v.default)(e),(t=(0,_.default)(t,O)).require_display_name||t.allow_display_name){var r=e.match(A);if(r){var n,i=(o=3,function(e){if(Array.isArray(e))return e}(a=r)||function(e,t){var r=[],n=!0,i=!1,a=void 0;try{for(var o,s=e[Symbol.iterator]();!(n=(o=s.next()).done)&&(r.push(o.value),!t||r.length!==t);n=!0);}catch(e){i=!0,a=e}finally{try{n||null==s.return||s.return()}finally{if(i)throw a}}return r}(a,o)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}());if(n=i[1],e=i[2],n.endsWith(" ")&&(n=n.substr(0,n.length-1)),!function(e){var t=e.match(/^"(.+)"$/i),r=t?t[1]:e;if(!r.trim())return!1;if(/[\.";<>]/.test(r)){if(!t)return!1;var n=r.split('"').length===r.split('\\"').length;if(!n)return!1}return!0}(n))return!1}else if(t.require_display_name)return!1}var a,o;if(!t.ignore_max_length&&e.length>j)return!1;var s=e.split("@"),l=s.pop(),u=s.join("@"),f=l.toLowerCase();if(t.domain_specific_validation&&("gmail.com"===f||"googlemail.com"===f)){var c=(u=u.toLowerCase()).split("+")[0];if(!(0,b.default)(c.replace(".",""),{min:6,max:30}))return!1;for(var d=c.split("."),p=0;p<d.length;p++)if(!M.test(d[p]))return!1}if(!(0,b.default)(u,{max:64})||!(0,b.default)(l,{max:254}))return!1;if(!(0,E.default)(l,{require_tld:t.require_tld})){if(!t.allow_ip_domain)return!1;if(!(0,S.default)(l)){if(!l.startsWith("[")||!l.endsWith("]"))return!1;var h=l.substr(1,l.length-2);if(0===h.length||!(0,S.default)(h))return!1}}if('"'===u[0])return u=u.slice(1,u.length-1),t.allow_utf8_local_part?P.test(u):w.test(u);for(var m=t.allow_utf8_local_part?R:x,y=u.split("."),g=0;g<y.length;g++)if(!m.test(y[g]))return!1;return!0};var v=n(e("./util/assertString")),_=n(e("./util/merge")),b=n(e("./isByteLength")),E=n(e("./isFQDN")),S=n(e("./isIP"));function n(e){return e&&e.__esModule?e:{default:e}}var O={allow_display_name:!1,require_display_name:!1,allow_utf8_local_part:!0,require_tld:!0},A=/^([^\x00-\x1F\x7F-\x9F\cX]+)<(.+)>$/i,x=/^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~]+$/i,M=/^[a-z\d]+$/,w=/^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f]))*$/i,R=/^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+$/i,P=/^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*$/i,j=254;t.exports=r.default,t.exports.default=r.default},{"./isByteLength":100,"./isFQDN":108,"./isIP":115,"./util/assertString":160,"./util/merge":162}],107:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){return(0,n.default)(e),0===((t=(0,i.default)(t,o)).ignore_whitespace?e.trim().length:e.length)};var n=a(e("./util/assertString")),i=a(e("./util/merge"));function a(e){return e&&e.__esModule?e:{default:e}}var o={ignore_whitespace:!1};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160,"./util/merge":162}],108:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){(0,s.default)(e),(t=(0,l.default)(t,u)).allow_trailing_dot&&"."===e[e.length-1]&&(e=e.substring(0,e.length-1));for(var r=e.split("."),n=0;n<r.length;n++)if(63<r[n].length)return!1;if(t.require_tld){var i=r.pop();if(!r.length||!/^([a-z\u00a1-\uffff]{2,}|xn[a-z0-9-]{2,})$/i.test(i))return!1;if(/[\s\u2002-\u200B\u202F\u205F\u3000\uFEFF\uDB40\uDC20]/.test(i))return!1}for(var a,o=0;o<r.length;o++){if(a=r[o],t.allow_underscores&&(a=a.replace(/_/g,"")),!/^[a-z\u00a1-\uffff0-9-]+$/i.test(a))return!1;if(/[\uff01-\uff5e]/.test(a))return!1;if("-"===a[0]||"-"===a[a.length-1])return!1}return!0};var s=n(e("./util/assertString")),l=n(e("./util/merge"));function n(e){return e&&e.__esModule?e:{default:e}}var u={require_tld:!0,allow_underscores:!1,allow_trailing_dot:!1};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160,"./util/merge":162}],109:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){(0,i.default)(e),t=t||{};var r=new RegExp("^(?:[-+])?(?:[0-9]+)?(?:\\".concat(t.locale?a.decimal[t.locale]:".","[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$"));if(""===e||"."===e||"-"===e||"+"===e)return!1;var n=parseFloat(e.replace(",","."));return r.test(e)&&(!t.hasOwnProperty("min")||n>=t.min)&&(!t.hasOwnProperty("max")||n<=t.max)&&(!t.hasOwnProperty("lt")||n<t.lt)&&(!t.hasOwnProperty("gt")||n>t.gt)},r.locales=void 0;var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n},a=e("./alpha");var o=Object.keys(a.decimal);r.locales=o},{"./alpha":87,"./util/assertString":160}],110:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),a.test(e)},r.fullWidth=void 0;var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/;r.fullWidth=a},{"./util/assertString":160}],111:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),a.test(e)},r.halfWidth=void 0;var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/;r.halfWidth=a},{"./util/assertString":160}],112:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){return(0,i.default)(e),new RegExp("^[a-f0-9]{".concat(a[t],"}$")).test(e)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a={md5:32,md4:32,sha1:40,sha256:64,sha384:96,sha512:128,ripemd128:32,ripemd160:40,tiger128:32,tiger160:40,tiger192:48,crc32:8,crc32b:8};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],113:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),a.test(e)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],114:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),a.test(e)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/^[0-9A-F]+$/i;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],115:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function e(t){var r=1<arguments.length&&void 0!==arguments[1]?arguments[1]:"";(0,u.default)(t);r=String(r);{if(!r)return e(t,4)||e(t,6);if("4"===r){if(!f.test(t))return!1;var n=t.split(".").sort(function(e,t){return e-t});return n[3]<=255}if("6"===r){var i=t.split(":"),a=!1,o=e(i[i.length-1],4),s=o?7:8;if(i.length>s)return!1;if("::"===t)return!0;"::"===t.substr(0,2)?(i.shift(),i.shift(),a=!0):"::"===t.substr(t.length-2)&&(i.pop(),i.pop(),a=!0);for(var l=0;l<i.length;++l)if(""===i[l]&&0<l&&l<i.length-1){if(a)return!1;a=!0}else if(o&&l===i.length-1);else if(!c.test(i[l]))return!1;return a?1<=i.length:i.length===s}}return!1};var n,u=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var f=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/,c=/^[0-9A-F]{1,4}$/i;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],116:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){(0,n.default)(e);var t=e.split("/");if(2!==t.length)return!1;if(!o.test(t[1]))return!1;if(1<t[1].length&&t[1].startsWith("0"))return!1;return(0,i.default)(t[0],4)&&t[1]<=32&&0<=t[1]};var n=a(e("./util/assertString")),i=a(e("./isIP"));function a(e){return e&&e.__esModule?e:{default:e}}var o=/^\d{1,2}$/;t.exports=r.default,t.exports.default=r.default},{"./isIP":115,"./util/assertString":160}],117:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function e(t){var r=1<arguments.length&&void 0!==arguments[1]?arguments[1]:"";(0,o.default)(t);r=String(r);if(!r)return e(t,10)||e(t,13);var n=t.replace(/[\s-]+/g,"");var i=0;var a;if("10"===r){if(!s.test(n))return!1;for(a=0;a<9;a++)i+=(a+1)*n.charAt(a);if("X"===n.charAt(9)?i+=100:i+=10*n.charAt(9),i%11==0)return!!n}else if("13"===r){if(!l.test(n))return!1;for(a=0;a<12;a++)i+=u[a%2]*n.charAt(a);if(n.charAt(12)-(10-i%10)%10==0)return!!n}return!1};var n,o=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var s=/^(?:[0-9]{9}X|[0-9]{10})$/,l=/^(?:[0-9]{13})$/,u=[1,3];t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],118:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){if((0,s.default)(e),!l.test(e))return!1;for(var t,r,n=e.replace(/[A-Z]/g,function(e){return parseInt(e,36)}),i=0,a=!0,o=n.length-2;0<=o;o--)t=n.substring(o,o+1),r=parseInt(t,10),i+=a&&10<=(r*=2)?r+1:r,a=!a;return parseInt(e.substr(e.length-1),10)===(1e4-i)%10};var n,s=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var l=/^[A-Z]{2}[0-9A-Z]{9}[0-9]$/;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],119:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,n.default)(e),(0,i.default)(o,e.toUpperCase())};var n=a(e("./util/assertString")),i=a(e("./util/includes"));function a(e){return e&&e.__esModule?e:{default:e}}var o=["AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AS","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CW","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IR","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","YE","YT","ZA","ZM","ZW"];t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160,"./util/includes":161}],120:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,n.default)(e),(0,i.default)(o,e.toUpperCase())};var n=a(e("./util/assertString")),i=a(e("./util/includes"));function a(e){return e&&e.__esModule?e:{default:e}}var o=["AFG","ALA","ALB","DZA","ASM","AND","AGO","AIA","ATA","ATG","ARG","ARM","ABW","AUS","AUT","AZE","BHS","BHR","BGD","BRB","BLR","BEL","BLZ","BEN","BMU","BTN","BOL","BES","BIH","BWA","BVT","BRA","IOT","BRN","BGR","BFA","BDI","KHM","CMR","CAN","CPV","CYM","CAF","TCD","CHL","CHN","CXR","CCK","COL","COM","COG","COD","COK","CRI","CIV","HRV","CUB","CUW","CYP","CZE","DNK","DJI","DMA","DOM","ECU","EGY","SLV","GNQ","ERI","EST","ETH","FLK","FRO","FJI","FIN","FRA","GUF","PYF","ATF","GAB","GMB","GEO","DEU","GHA","GIB","GRC","GRL","GRD","GLP","GUM","GTM","GGY","GIN","GNB","GUY","HTI","HMD","VAT","HND","HKG","HUN","ISL","IND","IDN","IRN","IRQ","IRL","IMN","ISR","ITA","JAM","JPN","JEY","JOR","KAZ","KEN","KIR","PRK","KOR","KWT","KGZ","LAO","LVA","LBN","LSO","LBR","LBY","LIE","LTU","LUX","MAC","MKD","MDG","MWI","MYS","MDV","MLI","MLT","MHL","MTQ","MRT","MUS","MYT","MEX","FSM","MDA","MCO","MNG","MNE","MSR","MAR","MOZ","MMR","NAM","NRU","NPL","NLD","NCL","NZL","NIC","NER","NGA","NIU","NFK","MNP","NOR","OMN","PAK","PLW","PSE","PAN","PNG","PRY","PER","PHL","PCN","POL","PRT","PRI","QAT","REU","ROU","RUS","RWA","BLM","SHN","KNA","LCA","MAF","SPM","VCT","WSM","SMR","STP","SAU","SEN","SRB","SYC","SLE","SGP","SXM","SVK","SVN","SLB","SOM","ZAF","SGS","SSD","ESP","LKA","SDN","SUR","SJM","SWZ","SWE","CHE","SYR","TWN","TJK","TZA","THA","TLS","TGO","TKL","TON","TTO","TUN","TUR","TKM","TCA","TUV","UGA","UKR","ARE","GBR","USA","UMI","URY","UZB","VUT","VEN","VNM","VGB","VIR","WLF","ESH","YEM","ZMB","ZWE"];t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160,"./util/includes":161}],121:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){(0,i.default)(e);var r=a.test(e);return t&&r&&t.strict?o(e):r};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/,o=function(e){var t=e.match(/^(\d{4})-?(\d{3})([ T]{1}\.*|$)/);if(t){var r=Number(t[1]),n=Number(t[2]);return r%4==0&&r%100!=0||r%400==0?n<=366:n<=365}var i=e.match(/(\d{4})-?(\d{0,2})-?(\d*)/).map(Number),a=i[1],o=i[2],s=i[3],l=o?"0".concat(o).slice(-2):o,u=s?"0".concat(s).slice(-2):s,f=new Date("".concat(a,"-").concat(l||"01","-").concat(u||"01"));return!o||!s||f.getUTCFullYear()===a&&f.getUTCMonth()+1===o&&f.getUTCDate()===s};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],122:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),a.test(e)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/^[A-Z]{2}[0-9A-Z]{3}\d{2}\d{5}$/;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],123:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};(0,s.default)(e);var r=l;if(r=t.require_hyphen?r.replace("?",""):r,!(r=t.case_sensitive?new RegExp(r):new RegExp(r,"i")).test(e))return!1;for(var n=e.replace("-","").toUpperCase(),i=0,a=0;a<n.length;a++){var o=n[a];i+=("X"===o?10:+o)*(8-a)}return i%11==0};var n,s=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var l="^\\d{4}-?\\d{3}[\\dX]$";t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],124:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){{if((0,i.default)(e),t in a)return a[t](e);if("any"===t){for(var r in a)if(a.hasOwnProperty(r)){var n=a[r];if(n(e))return!0}return!1}}throw new Error("Invalid locale '".concat(t,"'"))};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a={ES:function(e){(0,i.default)(e);var t={X:0,Y:1,Z:2},r=e.trim().toUpperCase();if(!/^[0-9X-Z][0-9]{7}[TRWAGMYFPDXBNJZSQVHLCKE]$/.test(r))return!1;var n=r.slice(0,-1).replace(/[X,Y,Z]/g,function(e){return t[e]});return r.endsWith(["T","R","W","A","G","M","Y","F","P","D","X","B","N","J","Z","S","Q","V","H","L","C","K","E"][n%23])},"he-IL":function(e){var t=e.trim();if(!/^\d{9}$/.test(t))return!1;for(var r,n=t,i=0,a=0;a<n.length;a++)i+=9<(r=Number(n[a])*(a%2+1))?r-9:r;return i%10==0},"zh-TW":function(e){var i={A:10,B:11,C:12,D:13,E:14,F:15,G:16,H:17,I:34,J:18,K:19,L:20,M:21,N:22,O:35,P:23,Q:24,R:25,S:26,T:27,U:28,V:29,W:32,X:30,Y:31,Z:33},t=e.trim().toUpperCase();return!!/^[A-Z][0-9]{9}$/.test(t)&&Array.from(t).reduce(function(e,t,r){if(0!==r)return 9===r?(10-e%10-Number(t))%10==0:e+Number(t)*(9-r);var n=i[t];return n%10*9+Math.floor(n/10)},0)}};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],125:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){var r;{if((0,i.default)(e),"[object Array]"===Object.prototype.toString.call(t)){var n=[];for(r in t)({}).hasOwnProperty.call(t,r)&&(n[r]=(0,a.default)(t[r]));return 0<=n.indexOf(e)}if("object"===o(t))return t.hasOwnProperty(e);if(t&&"function"==typeof t.indexOf)return 0<=t.indexOf(e)}return!1};var i=n(e("./util/assertString")),a=n(e("./util/toString"));function n(e){return e&&e.__esModule?e:{default:e}}function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160,"./util/toString":163}],126:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){(0,s.default)(e);var r=(t=t||{}).hasOwnProperty("allow_leading_zeroes")&&!t.allow_leading_zeroes?l:u,n=!t.hasOwnProperty("min")||e>=t.min,i=!t.hasOwnProperty("max")||e<=t.max,a=!t.hasOwnProperty("lt")||e<t.lt,o=!t.hasOwnProperty("gt")||e>t.gt;return r.test(e)&&n&&i&&a&&o};var n,s=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var l=/^(?:[-+]?(?:0|[1-9][0-9]*))$/,u=/^[-+]?[0-9]+$/;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],127:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){(0,i.default)(e);try{var t=JSON.parse(e);return!!t&&"object"===a(t)}catch(e){}return!1};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};function a(e){return(a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],128:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),a.test(e)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/^([A-Za-z0-9\-_~+\/]+[=]{0,2})\.([A-Za-z0-9\-_~+\/]+[=]{0,2})(?:\.([A-Za-z0-9\-_~+\/]+[=]{0,2}))?$/;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],129:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){if((0,i.default)(e),!e.includes(","))return!1;var t=e.split(",");return a.test(t[0])&&o.test(t[1])};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/^\(?[+-]?(90(\.0+)?|[1-8]?\d(\.\d+)?)$/,o=/^\s?[+-]?(180(\.0+)?|1[0-7]\d(\.\d+)?|\d{1,2}(\.\d+)?)\)?$/;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],130:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){var r,n;(0,o.default)(e),n="object"===s(t)?(r=t.min||0,t.max):(r=arguments[1],arguments[2]);var i=e.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g)||[],a=e.length-i.length;return r<=a&&(void 0===n||a<=n)};var n,o=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};function s(e){return(s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],131:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),e===e.toLowerCase()};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],132:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){if((0,i.default)(e),t&&t.no_colons)return o.test(e);return a.test(e)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/^([0-9a-fA-F][0-9a-fA-F]:){5}([0-9a-fA-F][0-9a-fA-F])$/,o=/^([0-9a-fA-F]){12}$/;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],133:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),a.test(e)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/^[a-f0-9]{32}$/;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],134:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),a.test(e.trim())};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/^magnet:\?xt=urn:[a-z0-9]+:[a-z0-9]{32,40}&dn=.+&tr=.+$/i;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],135:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),a.test(e)||o.test(e)||s.test(e)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/^(application|audio|font|image|message|model|multipart|text|video)\/[a-zA-Z0-9\.\-\+]{1,100}$/i,o=/^text\/[a-zA-Z0-9\.\-\+]{1,100};\s?charset=("[a-zA-Z0-9\.\-\+\s]{0,70}"|[a-zA-Z0-9\.\-\+]{0,70})(\s?\([a-zA-Z0-9\.\-\+\s]{1,20}\))?$/i,s=/^multipart\/[a-zA-Z0-9\.\-\+]{1,100}(;\s?(boundary|charset)=("[a-zA-Z0-9\.\-\+\s]{0,70}"|[a-zA-Z0-9\.\-\+]{0,70})(\s?\([a-zA-Z0-9\.\-\+\s]{1,20}\))?){0,2}$/i;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],136:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(r,e,t){if((0,a.default)(r),t&&t.strictMode&&!r.startsWith("+"))return!1;{if(Array.isArray(e))return e.some(function(e){if(o.hasOwnProperty(e)){var t=o[e];if(t.test(r))return!0}return!1});if(e in o)return o[e].test(r);if(!e||"any"===e){for(var n in o)if(o.hasOwnProperty(n)){var i=o[n];if(i.test(r))return!0}return!1}}throw new Error("Invalid locale '".concat(e,"'"))},r.locales=void 0;var n,a=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var o={"ar-AE":/^((\+?971)|0)?5[024568]\d{7}$/,"ar-BH":/^(\+?973)?(3|6)\d{7}$/,"ar-DZ":/^(\+?213|0)(5|6|7)\d{8}$/,"ar-EG":/^((\+?20)|0)?1[0125]\d{8}$/,"ar-IQ":/^(\+?964|0)?7[0-9]\d{8}$/,"ar-JO":/^(\+?962|0)?7[789]\d{7}$/,"ar-KW":/^(\+?965)[569]\d{7}$/,"ar-SA":/^(!?(\+?966)|0)?5\d{8}$/,"ar-SY":/^(!?(\+?963)|0)?9\d{8}$/,"ar-TN":/^(\+?216)?[2459]\d{7}$/,"be-BY":/^(\+?375)?(24|25|29|33|44)\d{7}$/,"bg-BG":/^(\+?359|0)?8[789]\d{7}$/,"bn-BD":/^(\+?880|0)1[1356789][0-9]{8}$/,"cs-CZ":/^(\+?420)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/,"da-DK":/^(\+?45)?\s?\d{2}\s?\d{2}\s?\d{2}\s?\d{2}$/,"de-DE":/^(\+49)?0?1(5[0-25-9]\d|6([23]|0\d?)|7([0-57-9]|6\d))\d{7}$/,"el-GR":/^(\+?30|0)?(69\d{8})$/,"en-AU":/^(\+?61|0)4\d{8}$/,"en-GB":/^(\+?44|0)7\d{9}$/,"en-GH":/^(\+233|0)(20|50|24|54|27|57|26|56|23|28)\d{7}$/,"en-HK":/^(\+?852\-?)?[456789]\d{3}\-?\d{4}$/,"en-IE":/^(\+?353|0)8[356789]\d{7}$/,"en-IN":/^(\+?91|0)?[6789]\d{9}$/,"en-KE":/^(\+?254|0)(7|1)\d{8}$/,"en-MT":/^(\+?356|0)?(99|79|77|21|27|22|25)[0-9]{6}$/,"en-MU":/^(\+?230|0)?\d{8}$/,"en-NG":/^(\+?234|0)?[789]\d{9}$/,"en-NZ":/^(\+?64|0)[28]\d{7,9}$/,"en-PK":/^((\+92)|(0092))-{0,1}\d{3}-{0,1}\d{7}$|^\d{11}$|^\d{4}-\d{7}$/,"en-RW":/^(\+?250|0)?[7]\d{8}$/,"en-SG":/^(\+65)?[89]\d{7}$/,"en-TZ":/^(\+?255|0)?[67]\d{8}$/,"en-UG":/^(\+?256|0)?[7]\d{8}$/,"en-US":/^((\+1|1)?( |-)?)?(\([2-9][0-9]{2}\)|[2-9][0-9]{2})( |-)?([2-9][0-9]{2}( |-)?[0-9]{4})$/,"en-ZA":/^(\+?27|0)\d{9}$/,"en-ZM":/^(\+?26)?09[567]\d{7}$/,"es-CL":/^(\+?56|0)[2-9]\d{1}\d{7}$/,"es-ES":/^(\+?34)?(6\d{1}|7[1234])\d{7}$/,"es-MX":/^(\+?52)?(1|01)?\d{10,11}$/,"es-PY":/^(\+?595|0)9[9876]\d{7}$/,"es-UY":/^(\+598|0)9[1-9][\d]{6}$/,"et-EE":/^(\+?372)?\s?(5|8[1-4])\s?([0-9]\s?){6,7}$/,"fa-IR":/^(\+?98[\-\s]?|0)9[0-39]\d[\-\s]?\d{3}[\-\s]?\d{4}$/,"fi-FI":/^(\+?358|0)\s?(4(0|1|2|4|5|6)?|50)\s?(\d\s?){4,8}\d$/,"fj-FJ":/^(\+?679)?\s?\d{3}\s?\d{4}$/,"fo-FO":/^(\+?298)?\s?\d{2}\s?\d{2}\s?\d{2}$/,"fr-FR":/^(\+?33|0)[67]\d{8}$/,"he-IL":/^(\+972|0)([23489]|5[012345689]|77)[1-9]\d{6}$/,"hu-HU":/^(\+?36)(20|30|70)\d{7}$/,"id-ID":/^(\+?62|0)8(1[123456789]|2[1238]|3[1238]|5[12356789]|7[78]|9[56789]|8[123456789])([\s?|\d]{5,11})$/,"it-IT":/^(\+?39)?\s?3\d{2} ?\d{6,7}$/,"ja-JP":/^(\+?81|0)[789]0[ \-]?[1-9]\d{2}[ \-]?\d{5}$/,"kk-KZ":/^(\+?7|8)?7\d{9}$/,"kl-GL":/^(\+?299)?\s?\d{2}\s?\d{2}\s?\d{2}$/,"ko-KR":/^((\+?82)[ \-]?)?0?1([0|1|6|7|8|9]{1})[ \-]?\d{3,4}[ \-]?\d{4}$/,"lt-LT":/^(\+370|8)\d{8}$/,"ms-MY":/^(\+?6?01){1}(([0145]{1}(\-|\s)?\d{7,8})|([236789]{1}(\s|\-)?\d{7}))$/,"nb-NO":/^(\+?47)?[49]\d{7}$/,"nl-BE":/^(\+?32|0)4?\d{8}$/,"nl-NL":/^(\+?31|0)6?\d{8}$/,"nn-NO":/^(\+?47)?[49]\d{7}$/,"pl-PL":/^(\+?48)? ?[5-8]\d ?\d{3} ?\d{2} ?\d{2}$/,"pt-BR":/(?=^(\+?5{2}\-?|0)[1-9]{2}\-?\d{4}\-?\d{4}$)(^(\+?5{2}\-?|0)[1-9]{2}\-?[6-9]{1}\d{3}\-?\d{4}$)|(^(\+?5{2}\-?|0)[1-9]{2}\-?9[6-9]{1}\d{3}\-?\d{4}$)/,"pt-PT":/^(\+?351)?9[1236]\d{7}$/,"ro-RO":/^(\+?4?0)\s?7\d{2}(\/|\s|\.|\-)?\d{3}(\s|\.|\-)?\d{3}$/,"ru-RU":/^(\+?7|8)?9\d{9}$/,"sl-SI":/^(\+386\s?|0)(\d{1}\s?\d{3}\s?\d{2}\s?\d{2}|\d{2}\s?\d{3}\s?\d{3})$/,"sk-SK":/^(\+?421)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/,"sr-RS":/^(\+3816|06)[- \d]{5,9}$/,"sv-SE":/^(\+?46|0)[\s\-]?7[\s\-]?[02369]([\s\-]?\d){7}$/,"th-TH":/^(\+66|66|0)\d{9}$/,"tr-TR":/^(\+?90|0)?5\d{9}$/,"uk-UA":/^(\+?38|8)?0\d{9}$/,"vi-VN":/^(\+?84|0)((3([2-9]))|(5([2689]))|(7([0|6-9]))|(8([1-6|89]))|(9([0-9])))([0-9]{7})$/,"zh-CN":/^((\+|00)86)?1([358][0-9]|4[579]|6[67]|7[0135678]|9[189])[0-9]{8}$/,"zh-TW":/^(\+?886\-?|0)?9\d{8}$/};o["en-CA"]=o["en-US"],o["fr-BE"]=o["nl-BE"],o["zh-HK"]=o["en-HK"];var i=Object.keys(o);r.locales=i},{"./util/assertString":160}],137:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,n.default)(e),(0,i.default)(e)&&24===e.length};var n=a(e("./util/assertString")),i=a(e("./isHexadecimal"));function a(e){return e&&e.__esModule?e:{default:e}}t.exports=r.default,t.exports.default=r.default},{"./isHexadecimal":114,"./util/assertString":160}],138:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),a.test(e)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/[^\x00-\x7F]/;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],139:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){if((0,i.default)(e),t&&t.no_symbols)return o.test(e);return a.test(e)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/^[+-]?([0-9]*[.])?[0-9]+$/,o=/^[0-9]+$/;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],140:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e,{min:0,max:65535})};var n,i=(n=e("./isInt"))&&n.__esModule?n:{default:n};t.exports=r.default,t.exports.default=r.default},{"./isInt":126}],141:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){{if((0,i.default)(e),t in l)return l[t].test(e);if("any"===t){for(var r in l)if(l.hasOwnProperty(r)){var n=l[r];if(n.test(e))return!0}return!1}}throw new Error("Invalid locale '".concat(t,"'"))},r.locales=void 0;var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/^\d{4}$/,o=/^\d{5}$/,s=/^\d{6}$/,l={AD:/^AD\d{3}$/,AT:a,AU:a,BE:a,BG:a,BR:/^\d{5}-\d{3}$/,CA:/^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][\s\-]?\d[ABCEGHJ-NPRSTV-Z]\d$/i,CH:a,CZ:/^\d{3}\s?\d{2}$/,DE:o,DK:a,DZ:o,EE:o,ES:o,FI:o,FR:/^\d{2}\s?\d{3}$/,GB:/^(gir\s?0aa|[a-z]{1,2}\d[\da-z]?\s?(\d[a-z]{2})?)$/i,GR:/^\d{3}\s?\d{2}$/,HR:/^([1-5]\d{4}$)/,HU:a,ID:o,IL:o,IN:s,IS:/^\d{3}$/,IT:o,JP:/^\d{3}\-\d{4}$/,KE:o,LI:/^(948[5-9]|949[0-7])$/,LT:/^LT\-\d{5}$/,LU:a,LV:/^LV\-\d{4}$/,MX:o,MT:/^[A-Za-z]{3}\s{0,1}\d{4}$/,NL:/^\d{4}\s?[a-z]{2}$/i,NO:a,NZ:a,PL:/^\d{2}\-\d{3}$/,PR:/^00[679]\d{2}([ -]\d{4})?$/,PT:/^\d{4}\-\d{3}?$/,RO:s,RU:s,SA:o,SE:/^\d{3}\s?\d{2}$/,SI:a,SK:/^\d{3}\s?\d{2}$/,TN:a,TW:/^\d{3}(\d{2})?$/,UA:o,US:/^\d{5}(-\d{4})?$/,ZA:a,ZM:o},u=Object.keys(l);r.locales=u},{"./util/assertString":160}],142:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),d.test(e)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/([01][0-9]|2[0-3])/,o=/[0-5][0-9]/,s=new RegExp("[-+]".concat(a.source,":").concat(o.source)),l=new RegExp("([zZ]|".concat(s.source,")")),u=new RegExp("".concat(a.source,":").concat(o.source,":").concat(/([0-5][0-9]|60)/.source).concat(/(\.[0-9]+)?/.source)),f=new RegExp("".concat(/[0-9]{4}/.source,"-").concat(/(0[1-9]|1[0-2])/.source,"-").concat(/([12]\d|0[1-9]|3[01])/.source)),c=new RegExp("".concat(u.source).concat(l.source)),d=new RegExp("".concat(f.source,"[ tT]").concat(c.source));t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],143:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),a.test(e)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a=/[\uD800-\uDBFF][\uDC00-\uDFFF]/;t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],144:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){if((0,c.default)(e),!e||2083<=e.length||/[\s<>]/.test(e))return!1;if(0===e.indexOf("mailto:"))return!1;var r,n,i,a,o,s,l,u;if(t=(0,h.default)(t,m),1<(l=(e=(l=(e=(l=e.split("#")).shift()).split("?")).shift()).split("://")).length){if(r=l.shift().toLowerCase(),t.require_valid_protocol&&-1===t.protocols.indexOf(r))return!1}else{if(t.require_protocol)return!1;if("//"===e.substr(0,2)){if(!t.allow_protocol_relative_urls)return!1;l[0]=e.substr(2)}}if(""===(e=l.join("://")))return!1;if(""===(e=(l=e.split("/")).shift())&&!t.require_host)return!0;if(1<(l=e.split("@")).length){if(t.disallow_auth)return!1;if(0<=(n=l.shift()).indexOf(":")&&2<n.split(":").length)return!1}a=l.join("@"),u=s=null;var f=a.match(y);f?(i="",u=f[1],s=f[2]||null):(l=a.split(":"),i=l.shift(),l.length&&(s=l.join(":")));if(null!==s&&(o=parseInt(s,10),!/^[0-9]+$/.test(s)||o<=0||65535<o))return!1;if(!((0,p.default)(i)||(0,d.default)(i,t)||u&&(0,p.default)(u,6)))return!1;if(i=i||u,t.host_whitelist&&!g(i,t.host_whitelist))return!1;if(t.host_blacklist&&g(i,t.host_blacklist))return!1;return!0};var c=n(e("./util/assertString")),d=n(e("./isFQDN")),p=n(e("./isIP")),h=n(e("./util/merge"));function n(e){return e&&e.__esModule?e:{default:e}}var m={protocols:["http","https","ftp"],require_tld:!0,require_protocol:!1,require_host:!0,require_valid_protocol:!0,allow_underscores:!1,allow_trailing_dot:!1,allow_protocol_relative_urls:!1},y=/^\[([^\]]+)\](?::([0-9]+))?$/;function g(e,t){for(var r=0;r<t.length;r++){var n=t[r];if(e===n||(i=n,"[object RegExp]"===Object.prototype.toString.call(i)&&n.test(e)))return!0}var i;return!1}t.exports=r.default,t.exports.default=r.default},{"./isFQDN":108,"./isIP":115,"./util/assertString":160,"./util/merge":162}],145:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:"all";(0,i.default)(e);var r=a[t];return r&&r.test(e)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};var a={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],146:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),e===e.toUpperCase()};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],147:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),a.fullWidth.test(e)&&o.halfWidth.test(e)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n},a=e("./isFullWidth"),o=e("./isHalfWidth");t.exports=r.default,t.exports.default=r.default},{"./isFullWidth":110,"./isHalfWidth":111,"./util/assertString":160}],148:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){(0,i.default)(e);for(var r=e.length-1;0<=r;r--)if(-1===t.indexOf(e[r]))return!1;return!0};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],149:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){(0,i.default)(e);var r=t?new RegExp("^[".concat(t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"]+"),"g"):/^\s+/g;return e.replace(r,"")};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],150:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t,r){(0,i.default)(e),"[object RegExp]"!==Object.prototype.toString.call(t)&&(t=new RegExp(t,r));return t.test(e)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],151:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){t=(0,o.default)(t,s);var r=e.split("@"),n=r.pop(),i=[r.join("@"),n];if(i[1]=i[1].toLowerCase(),"gmail.com"===i[1]||"googlemail.com"===i[1]){if(t.gmail_remove_subaddress&&(i[0]=i[0].split("+")[0]),t.gmail_remove_dots&&(i[0]=i[0].replace(/\.+/g,d)),!i[0].length)return!1;(t.all_lowercase||t.gmail_lowercase)&&(i[0]=i[0].toLowerCase()),i[1]=t.gmail_convert_googlemaildotcom?"gmail.com":i[1]}else if(0<=l.indexOf(i[1])){if(t.icloud_remove_subaddress&&(i[0]=i[0].split("+")[0]),!i[0].length)return!1;(t.all_lowercase||t.icloud_lowercase)&&(i[0]=i[0].toLowerCase())}else if(0<=u.indexOf(i[1])){if(t.outlookdotcom_remove_subaddress&&(i[0]=i[0].split("+")[0]),!i[0].length)return!1;(t.all_lowercase||t.outlookdotcom_lowercase)&&(i[0]=i[0].toLowerCase())}else if(0<=f.indexOf(i[1])){if(t.yahoo_remove_subaddress){var a=i[0].split("-");i[0]=1<a.length?a.slice(0,-1).join("-"):a[0]}if(!i[0].length)return!1;(t.all_lowercase||t.yahoo_lowercase)&&(i[0]=i[0].toLowerCase())}else 0<=c.indexOf(i[1])?((t.all_lowercase||t.yandex_lowercase)&&(i[0]=i[0].toLowerCase()),i[1]="yandex.ru"):t.all_lowercase&&(i[0]=i[0].toLowerCase());return i.join("@")};var n,o=(n=e("./util/merge"))&&n.__esModule?n:{default:n};var s={all_lowercase:!0,gmail_lowercase:!0,gmail_remove_dots:!0,gmail_remove_subaddress:!0,gmail_convert_googlemaildotcom:!0,outlookdotcom_lowercase:!0,outlookdotcom_remove_subaddress:!0,yahoo_lowercase:!0,yahoo_remove_subaddress:!0,yandex_lowercase:!0,icloud_lowercase:!0,icloud_remove_subaddress:!0},l=["icloud.com","me.com"],u=["hotmail.at","hotmail.be","hotmail.ca","hotmail.cl","hotmail.co.il","hotmail.co.nz","hotmail.co.th","hotmail.co.uk","hotmail.com","hotmail.com.ar","hotmail.com.au","hotmail.com.br","hotmail.com.gr","hotmail.com.mx","hotmail.com.pe","hotmail.com.tr","hotmail.com.vn","hotmail.cz","hotmail.de","hotmail.dk","hotmail.es","hotmail.fr","hotmail.hu","hotmail.id","hotmail.ie","hotmail.in","hotmail.it","hotmail.jp","hotmail.kr","hotmail.lv","hotmail.my","hotmail.ph","hotmail.pt","hotmail.sa","hotmail.sg","hotmail.sk","live.be","live.co.uk","live.com","live.com.ar","live.com.mx","live.de","live.es","live.eu","live.fr","live.it","live.nl","msn.com","outlook.at","outlook.be","outlook.cl","outlook.co.il","outlook.co.nz","outlook.co.th","outlook.com","outlook.com.ar","outlook.com.au","outlook.com.br","outlook.com.gr","outlook.com.pe","outlook.com.tr","outlook.com.vn","outlook.cz","outlook.de","outlook.dk","outlook.es","outlook.fr","outlook.hu","outlook.id","outlook.ie","outlook.in","outlook.it","outlook.jp","outlook.kr","outlook.lv","outlook.my","outlook.ph","outlook.pt","outlook.sa","outlook.sg","outlook.sk","passport.com"],f=["rocketmail.com","yahoo.ca","yahoo.co.uk","yahoo.com","yahoo.de","yahoo.fr","yahoo.in","yahoo.it","ymail.com"],c=["yandex.ru","yandex.ua","yandex.kz","yandex.com","yandex.by","ya.ru"];function d(e){return 1<e.length?e:""}t.exports=r.default,t.exports.default=r.default},{"./util/merge":162}],152:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){(0,i.default)(e);var r=t?new RegExp("[".concat(t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"]+$"),"g"):/\s+$/g;return e.replace(r,"")};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],153:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){(0,n.default)(e);var r=t?"\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F":"\\x00-\\x1F\\x7F";return(0,i.default)(e,r)};var n=a(e("./util/assertString")),i=a(e("./blacklist"));function a(e){return e&&e.__esModule?e:{default:e}}t.exports=r.default,t.exports.default=r.default},{"./blacklist":88,"./util/assertString":160}],154:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){if((0,i.default)(e),t)return"1"===e||"true"===e;return"0"!==e&&"false"!==e&&""!==e};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],155:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),e=Date.parse(e),isNaN(e)?null:new Date(e)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],156:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),parseFloat(e)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],157:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){return(0,i.default)(e),parseInt(e,t||10)};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],158:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){return(0,n.default)((0,i.default)(e,t),t)};var n=a(e("./rtrim")),i=a(e("./ltrim"));function a(e){return e&&e.__esModule?e:{default:e}}t.exports=r.default,t.exports.default=r.default},{"./ltrim":149,"./rtrim":152}],159:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(e),e.replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(///g,"/").replace(/\/g,"\\").replace(/`/g,"`")};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],160:[function(e,t,r){"use strict";function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){if(!("string"==typeof e||e instanceof String)){var t;throw t=null===e?"null":"object"===(t=n(e))&&e.constructor&&e.constructor.hasOwnProperty("name")?e.constructor.name:"a ".concat(t),new TypeError("Expected string but received ".concat(t,"."))}},t.exports=r.default,t.exports.default=r.default},{}],161:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n=function(e,t){return e.some(function(e){return t===e})};r.default=n,t.exports=r.default,t.exports.default=r.default},{}],162:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},t=1<arguments.length?arguments[1]:void 0;for(var r in t)void 0===e[r]&&(e[r]=t[r]);return e},t.exports=r.default,t.exports.default=r.default},{}],163:[function(e,t,r){"use strict";function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){"object"===n(e)&&null!==e?e="function"==typeof e.toString?e.toString():"[object Object]":(null==e||isNaN(e)&&!e.length)&&(e="");return String(e)},t.exports=r.default,t.exports.default=r.default},{}],164:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){return(0,i.default)(e),e.replace(new RegExp("[^".concat(t,"]+"),"g"),"")};var n,i=(n=e("./util/assertString"))&&n.__esModule?n:{default:n};t.exports=r.default,t.exports.default=r.default},{"./util/assertString":160}],165:[function(e,t,r){"use strict";t.exports={INVALID_TYPE:"Expected type {0} but found type {1}",INVALID_FORMAT:"Object didn't pass validation for format {0}: {1}",ENUM_MISMATCH:"No enum match for: {0}",ENUM_CASE_MISMATCH:"Enum does not match case for: {0}",ANY_OF_MISSING:"Data does not match any schemas from 'anyOf'",ONE_OF_MISSING:"Data does not match any schemas from 'oneOf'",ONE_OF_MULTIPLE:"Data is valid against more than one schema from 'oneOf'",NOT_PASSED:"Data matches schema from 'not'",ARRAY_LENGTH_SHORT:"Array is too short ({0}), minimum {1}",ARRAY_LENGTH_LONG:"Array is too long ({0}), maximum {1}",ARRAY_UNIQUE:"Array items are not unique (indexes {0} and {1})",ARRAY_ADDITIONAL_ITEMS:"Additional items not allowed",MULTIPLE_OF:"Value {0} is not a multiple of {1}",MINIMUM:"Value {0} is less than minimum {1}",MINIMUM_EXCLUSIVE:"Value {0} is equal or less than exclusive minimum {1}",MAXIMUM:"Value {0} is greater than maximum {1}",MAXIMUM_EXCLUSIVE:"Value {0} is equal or greater than exclusive maximum {1}",OBJECT_PROPERTIES_MINIMUM:"Too few properties defined ({0}), minimum {1}",OBJECT_PROPERTIES_MAXIMUM:"Too many properties defined ({0}), maximum {1}",OBJECT_MISSING_REQUIRED_PROPERTY:"Missing required property: {0}",OBJECT_ADDITIONAL_PROPERTIES:"Additional properties not allowed: {0}",OBJECT_DEPENDENCY_KEY:"Dependency failed - key must exist: {0} (due to key: {1})",MIN_LENGTH:"String is too short ({0} chars), minimum {1}",MAX_LENGTH:"String is too long ({0} chars), maximum {1}",PATTERN:"String does not match pattern {0}: {1}",KEYWORD_TYPE_EXPECTED:"Keyword '{0}' is expected to be of type '{1}'",KEYWORD_UNDEFINED_STRICT:"Keyword '{0}' must be defined in strict mode",KEYWORD_UNEXPECTED:"Keyword '{0}' is not expected to appear in the schema",KEYWORD_MUST_BE:"Keyword '{0}' must be {1}",KEYWORD_DEPENDENCY:"Keyword '{0}' requires keyword '{1}'",KEYWORD_PATTERN:"Keyword '{0}' is not a valid RegExp pattern: {1}",KEYWORD_VALUE_TYPE:"Each element of keyword '{0}' array must be a '{1}'",UNKNOWN_FORMAT:"There is no validation function for format '{0}'",CUSTOM_MODE_FORCE_PROPERTIES:"{0} must define at least one property if present",REF_UNRESOLVED:"Reference has not been resolved during compilation: {0}",UNRESOLVABLE_REFERENCE:"Reference could not be resolved: {0}",SCHEMA_NOT_REACHABLE:"Validator was not able to read schema with uri: {0}",SCHEMA_TYPE_EXPECTED:"Schema is expected to be of type 'object'",SCHEMA_NOT_AN_OBJECT:"Schema is not an object: {0}",ASYNC_TIMEOUT:"{0} asynchronous task(s) have timed out after {1} ms",PARENT_SCHEMA_VALIDATION_FAILED:"Schema failed to validate against its parent schema, see inner errors for details.",REMOTE_NOT_VALID:"Remote reference didn't compile successfully: {0}"}},{}],166:[function(e,t,r){var n=e("validator"),i={date:function(e){if("string"!=typeof e)return!0;var t=/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/.exec(e);return null!==t&&!(t[2]<"01"||"12"<t[2]||t[3]<"01"||"31"<t[3])},"date-time":function(e){if("string"!=typeof e)return!0;var t=e.toLowerCase().split("t");if(!i.date(t[0]))return!1;var r=/^([0-9]{2}):([0-9]{2}):([0-9]{2})(.[0-9]+)?(z|([+-][0-9]{2}:[0-9]{2}))$/.exec(t[1]);return null!==r&&!("23"<r[1]||"59"<r[2]||"59"<r[3])},email:function(e){return"string"!=typeof e||n.isEmail(e,{require_tld:!0})},hostname:function(e){if("string"!=typeof e)return!0;var t=/^[a-zA-Z](([-0-9a-zA-Z]+)?[0-9a-zA-Z])?(\.[a-zA-Z](([-0-9a-zA-Z]+)?[0-9a-zA-Z])?)*$/.test(e);if(t){if(255<e.length)return!1;for(var r=e.split("."),n=0;n<r.length;n++)if(63<r[n].length)return!1}return t},"host-name":function(e){return i.hostname.call(this,e)},ipv4:function(e){return"string"!=typeof e||n.isIP(e,4)},ipv6:function(e){return"string"!=typeof e||n.isIP(e,6)},regex:function(e){try{return RegExp(e),!0}catch(e){return!1}},uri:function(e){return this.options.strictUris?i["strict-uri"].apply(this,arguments):"string"!=typeof e||RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?").test(e)},"strict-uri":function(e){return"string"!=typeof e||n.isURL(e)}};t.exports=i},{validator:86}],167:[function(e,t,p){"use strict";var o=e("./FormatValidators"),s=e("./Report"),h=e("./Utils"),m=function(t,e){return t&&Array.isArray(t.includeErrors)&&0<t.includeErrors.length&&!e.some(function(e){return t.includeErrors.includes(e)})},u={multipleOf:function(e,t,r){m(this.validateOptions,["MULTIPLE_OF"])||"number"==typeof r&&"integer"!==h.whatIs(r/t.multipleOf)&&e.addError("MULTIPLE_OF",[r,t.multipleOf],null,t)},maximum:function(e,t,r){m(this.validateOptions,["MAXIMUM","MAXIMUM_EXCLUSIVE"])||"number"==typeof r&&(!0!==t.exclusiveMaximum?r>t.maximum&&e.addError("MAXIMUM",[r,t.maximum],null,t):r>=t.maximum&&e.addError("MAXIMUM_EXCLUSIVE",[r,t.maximum],null,t))},exclusiveMaximum:function(){},minimum:function(e,t,r){m(this.validateOptions,["MINIMUM","MINIMUM_EXCLUSIVE"])||"number"==typeof r&&(!0!==t.exclusiveMinimum?r<t.minimum&&e.addError("MINIMUM",[r,t.minimum],null,t):r<=t.minimum&&e.addError("MINIMUM_EXCLUSIVE",[r,t.minimum],null,t))},exclusiveMinimum:function(){},maxLength:function(e,t,r){m(this.validateOptions,["MAX_LENGTH"])||"string"==typeof r&&h.ucs2decode(r).length>t.maxLength&&e.addError("MAX_LENGTH",[r.length,t.maxLength],null,t)},minLength:function(e,t,r){m(this.validateOptions,["MIN_LENGTH"])||"string"==typeof r&&h.ucs2decode(r).length<t.minLength&&e.addError("MIN_LENGTH",[r.length,t.minLength],null,t)},pattern:function(e,t,r){m(this.validateOptions,["PATTERN"])||"string"==typeof r&&!1===RegExp(t.pattern).test(r)&&e.addError("PATTERN",[t.pattern,r],null,t)},additionalItems:function(e,t,r){m(this.validateOptions,["ARRAY_ADDITIONAL_ITEMS"])||Array.isArray(r)&&!1===t.additionalItems&&Array.isArray(t.items)&&r.length>t.items.length&&e.addError("ARRAY_ADDITIONAL_ITEMS",null,null,t)},items:function(){},maxItems:function(e,t,r){m(this.validateOptions,["ARRAY_LENGTH_LONG"])||Array.isArray(r)&&r.length>t.maxItems&&e.addError("ARRAY_LENGTH_LONG",[r.length,t.maxItems],null,t)},minItems:function(e,t,r){m(this.validateOptions,["ARRAY_LENGTH_SHORT"])||Array.isArray(r)&&r.length<t.minItems&&e.addError("ARRAY_LENGTH_SHORT",[r.length,t.minItems],null,t)},uniqueItems:function(e,t,r){if(!m(this.validateOptions,["ARRAY_UNIQUE"])&&Array.isArray(r)&&!0===t.uniqueItems){var n=[];!1===h.isUniqueArray(r,n)&&e.addError("ARRAY_UNIQUE",n,null,t)}},maxProperties:function(e,t,r){if(!m(this.validateOptions,["OBJECT_PROPERTIES_MAXIMUM"])&&"object"===h.whatIs(r)){var n=Object.keys(r).length;n>t.maxProperties&&e.addError("OBJECT_PROPERTIES_MAXIMUM",[n,t.maxProperties],null,t)}},minProperties:function(e,t,r){if(!m(this.validateOptions,["OBJECT_PROPERTIES_MINIMUM"])&&"object"===h.whatIs(r)){var n=Object.keys(r).length;n<t.minProperties&&e.addError("OBJECT_PROPERTIES_MINIMUM",[n,t.minProperties],null,t)}},required:function(e,t,r){if(!m(this.validateOptions,["OBJECT_MISSING_REQUIRED_PROPERTY"])&&"object"===h.whatIs(r))for(var n=t.required.length;n--;){var i=t.required[n];void 0===r[i]&&e.addError("OBJECT_MISSING_REQUIRED_PROPERTY",[i],null,t)}},additionalProperties:function(e,t,r){if(void 0===t.properties&&void 0===t.patternProperties)return u.properties.call(this,e,t,r)},patternProperties:function(e,t,r){if(void 0===t.properties)return u.properties.call(this,e,t,r)},properties:function(e,t,r){if(!m(this.validateOptions,["OBJECT_ADDITIONAL_PROPERTIES"])&&"object"===h.whatIs(r)){var n=void 0!==t.properties?t.properties:{},i=void 0!==t.patternProperties?t.patternProperties:{};if(!1===t.additionalProperties){var a=Object.keys(r),o=Object.keys(n),s=Object.keys(i);a=h.difference(a,o);for(var l=s.length;l--;)for(var u=RegExp(s[l]),f=a.length;f--;)!0===u.test(a[f])&&a.splice(f,1);if(0<a.length){var c=this.options.assumeAdditional.length;if(c)for(;c--;){var d=a.indexOf(this.options.assumeAdditional[c]);-1!==d&&a.splice(d,1)}var p=a.length;if(p)for(;p--;)e.addError("OBJECT_ADDITIONAL_PROPERTIES",[a[p]],null,t)}}}},dependencies:function(e,t,r){if(!m(this.validateOptions,["OBJECT_DEPENDENCY_KEY"])&&"object"===h.whatIs(r))for(var n=Object.keys(t.dependencies),i=n.length;i--;){var a=n[i];if(r[a]){var o=t.dependencies[a];if("object"===h.whatIs(o))p.validate.call(this,e,o,r);else for(var s=o.length;s--;){var l=o[s];void 0===r[l]&&e.addError("OBJECT_DEPENDENCY_KEY",[l,a],null,t)}}}},enum:function(e,t,r){if(!m(this.validateOptions,["ENUM_CASE_MISMATCH","ENUM_MISMATCH"])){for(var n=!1,i=!1,a=t.enum.length;a--;){if(h.areEqual(r,t.enum[a])){n=!0;break}h.areEqual(r,t.enum[a]),i=!0}if(!1===n){var o=i&&this.options.enumCaseInsensitiveComparison?"ENUM_CASE_MISMATCH":"ENUM_MISMATCH";e.addError(o,[r],null,t)}}},type:function(e,t,r){if(!m(this.validateOptions,["INVALID_TYPE"])){var n=h.whatIs(r);"string"==typeof t.type?n===t.type||"integer"===n&&"number"===t.type||e.addError("INVALID_TYPE",[t.type,n],null,t):-1!==t.type.indexOf(n)||"integer"===n&&-1!==t.type.indexOf("number")||e.addError("INVALID_TYPE",[t.type,n],null,t)}},allOf:function(e,t,r){for(var n=t.allOf.length;n--;){var i=p.validate.call(this,e,t.allOf[n],r);if(this.options.breakOnFirstError&&!1===i)break}},anyOf:function(e,t,r){for(var n=[],i=!1,a=t.anyOf.length;a--&&!1===i;){var o=new s(e);n.push(o),i=p.validate.call(this,o,t.anyOf[a],r)}!1===i&&e.addError("ANY_OF_MISSING",void 0,n,t)},oneOf:function(e,t,r){for(var n=0,i=[],a=t.oneOf.length;a--;){var o=new s(e,{maxErrors:1});i.push(o),!0===p.validate.call(this,o,t.oneOf[a],r)&&n++}0===n?e.addError("ONE_OF_MISSING",void 0,i,t):1<n&&e.addError("ONE_OF_MULTIPLE",null,null,t)},not:function(e,t,r){var n=new s(e);!0===p.validate.call(this,n,t.not,r)&&e.addError("NOT_PASSED",null,null,t)},definitions:function(){},format:function(r,n,i){var e=o[n.format];if("function"==typeof e){if(m(this.validateOptions,["INVALID_FORMAT"]))return;if(2===e.length){var a=h.clone(r.path);r.addAsyncTask(e,[i],function(e){if(!0!==e){var t=r.path;r.path=a,r.addError("INVALID_FORMAT",[n.format,i],null,n),r.path=t}})}else!0!==e.call(this,i)&&r.addError("INVALID_FORMAT",[n.format,i],null,n)}else!0!==this.options.ignoreUnknownFormats&&r.addError("UNKNOWN_FORMAT",[n.format],null,n)}};p.JsonValidators=u,p.validate=function(e,t,r){e.commonErrorMessage="JSON_OBJECT_VALIDATION_FAILED";var n=h.whatIs(t);if("object"!==n)return e.addError("SCHEMA_NOT_AN_OBJECT",[n],null,t),!1;var i=Object.keys(t);if(0===i.length)return!0;var a=!1;if(e.rootSchema||(e.rootSchema=t,a=!0),void 0!==t.$ref){for(var o=99;t.$ref&&0<o;){if(!t.__$refResolved){e.addError("REF_UNRESOLVED",[t.$ref],null,t);break}if(t.__$refResolved===t)break;t=t.__$refResolved,i=Object.keys(t),o--}if(0===o)throw new Error("Circular dependency by $ref references!")}var s=h.whatIs(r);if(t.type&&(i.splice(i.indexOf("type"),1),u.type.call(this,e,t,r),e.errors.length&&this.options.breakOnFirstError))return!1;for(var l=i.length;l--&&!(u[i[l]]&&(u[i[l]].call(this,e,t,r),e.errors.length&&this.options.breakOnFirstError)););return 0!==e.errors.length&&!1!==this.options.breakOnFirstError||("array"===s?function(e,t,r){var n=r.length;if(Array.isArray(t.items))for(;n--;)n<t.items.length?(e.path.push(n),p.validate.call(this,e,t.items[n],r[n]),e.path.pop()):"object"==typeof t.additionalItems&&(e.path.push(n),p.validate.call(this,e,t.additionalItems,r[n]),e.path.pop());else if("object"==typeof t.items)for(;n--;)e.path.push(n),p.validate.call(this,e,t.items,r[n]),e.path.pop()}.call(this,e,t,r):"object"===s&&function(e,t,r){var n=t.additionalProperties;!0!==n&&void 0!==n||(n={});for(var i=t.properties?Object.keys(t.properties):[],a=t.patternProperties?Object.keys(t.patternProperties):[],o=Object.keys(r),s=o.length;s--;){var l=o[s],u=r[l],f=[];-1!==i.indexOf(l)&&f.push(t.properties[l]);for(var c=a.length;c--;){var d=a[c];!0===RegExp(d).test(l)&&f.push(t.patternProperties[d])}for(0===f.length&&!1!==n&&f.push(n),c=f.length;c--;)e.path.push(l),p.validate.call(this,e,f[c],u),e.path.pop()}}.call(this,e,t,r)),"function"==typeof this.options.customValidator&&this.options.customValidator(e,t,r),a&&(e.rootSchema=void 0),0===e.errors.length}},{"./FormatValidators":166,"./Report":169,"./Utils":173}],168:[function(e,t,r){"function"!=typeof Number.isFinite&&(Number.isFinite=function(e){return"number"==typeof e&&(e==e&&e!==1/0&&e!==-1/0)})},{}],169:[function(e,t,r){(function(f){"use strict";var r=e("lodash.get"),i=e("./Errors"),c=e("./Utils");function n(e,t){this.parentReport=e instanceof n?e:void 0,this.options=e instanceof n?e.options:e||{},this.reportOptions=t||{},this.errors=[],this.path=[],this.asyncTasks=[],this.rootSchema=void 0,this.commonErrorMessage=void 0,this.json=void 0}n.prototype.isValid=function(){if(0<this.asyncTasks.length)throw new Error("Async tasks pending, can't answer isValid");return 0===this.errors.length},n.prototype.addAsyncTask=function(e,t,r){this.asyncTasks.push([e,t,r])},n.prototype.getAncestor=function(e){if(this.parentReport)return this.parentReport.getSchemaId()===e?this.parentReport:this.parentReport.getAncestor(e)},n.prototype.processAsyncTasks=function(e,r){var t=e||2e3,n=this.asyncTasks.length,i=n,a=!1,o=this;function s(){f.nextTick(function(){var e=0===o.errors.length,t=e?void 0:o.errors;r(t,e)})}function l(t){return function(e){a||(t(e),0==--n&&s())}}if(0===n||0<this.errors.length&&this.options.breakOnFirstError)s();else{for(;i--;){var u=this.asyncTasks[i];u[0].apply(null,u[1].concat(l(u[2])))}setTimeout(function(){0<n&&(a=!0,o.addError("ASYNC_TIMEOUT",[n,t]),r(o.errors,!1))},t)}},n.prototype.getPath=function(e){var t=[];return this.parentReport&&(t=t.concat(this.parentReport.path)),t=t.concat(this.path),!0!==e&&(t="#/"+t.map(function(e){return e=e.toString(),c.isAbsoluteUri(e)?"uri("+e+")":e.replace(/\~/g,"~0").replace(/\//g,"~1")}).join("/")),t},n.prototype.getSchemaId=function(){if(!this.rootSchema)return null;var e=[];for(this.parentReport&&(e=e.concat(this.parentReport.path)),e=e.concat(this.path);0<e.length;){var t=r(this.rootSchema,e);if(t&&t.id)return t.id;e.pop()}return this.rootSchema.id},n.prototype.hasError=function(e,t){for(var r=this.errors.length;r--;)if(this.errors[r].code===e){for(var n=!0,i=this.errors[r].params.length;i--;)this.errors[r].params[i]!==t[i]&&(n=!1);if(n)return n}return!1},n.prototype.addError=function(e,t,r,n){if(!e)throw new Error("No errorCode passed into addError()");this.addCustomError(e,i[e],t,r,n)},n.prototype.getJson=function(){for(var e=this;void 0===e.json;)if(void 0===(e=e.parentReport))return;return e.json},n.prototype.addCustomError=function(e,t,r,n,i){if(!(this.errors.length>=this.reportOptions.maxErrors)){if(!t)throw new Error("No errorMessage known for code "+e);for(var a=(r=r||[]).length;a--;){var o=c.whatIs(r[a]),s="object"===o||"null"===o?JSON.stringify(r[a]):r[a];t=t.replace("{"+a+"}",s)}var l={code:e,params:r,message:t,path:this.getPath(this.options.reportPathAsArray),schemaId:this.getSchemaId()};if(l[c.schemaSymbol]=i,l[c.jsonSymbol]=this.getJson(),i&&"string"==typeof i?l.description=i:i&&"object"==typeof i&&(i.title&&(l.title=i.title),i.description&&(l.description=i.description)),null!=n){for(Array.isArray(n)||(n=[n]),l.inner=[],a=n.length;a--;)for(var u=n[a],f=u.errors.length;f--;)l.inner.push(u.errors[f]);0===l.inner.length&&(l.inner=void 0)}this.errors.push(l)}},t.exports=n}).call(this,e("_process"))},{"./Errors":165,"./Utils":173,_process:85,"lodash.get":83}],170:[function(e,t,r){"use strict";var i=e("lodash.isequal"),g=e("./Report"),v=e("./SchemaCompilation"),_=e("./SchemaValidation"),a=e("./Utils");function b(e){var t=e.indexOf("#");return-1===t?e:e.slice(0,t)}function E(e,t){if("object"==typeof e&&null!==e){if(!t)return e;if(e.id&&(e.id===t||"#"===e.id[0]&&e.id.substring(1)===t))return e;var r,n;if(Array.isArray(e)){for(r=e.length;r--;)if(n=E(e[r],t))return n}else{var i=Object.keys(e);for(r=i.length;r--;){var a=i[r];if(0!==a.indexOf("__$")&&(n=E(e[a],t)))return n}}}}r.cacheSchemaByUri=function(e,t){var r=b(e);r&&(this.cache[r]=t)},r.removeFromCacheByUri=function(e){var t=b(e);t&&delete this.cache[t]},r.checkCacheForUri=function(e){var t=b(e);return!!t&&null!=this.cache[t]},r.getSchema=function(e,t){return"object"==typeof t&&(t=r.getSchemaByReference.call(this,e,t)),"string"==typeof t&&(t=r.getSchemaByUri.call(this,e,t)),t},r.getSchemaByReference=function(e,t){for(var r=this.referenceCache.length;r--;)if(i(this.referenceCache[r][0],t))return this.referenceCache[r][1];var n=a.cloneDeep(t);return this.referenceCache.push([t,n]),n},r.getSchemaByUri=function(e,t,r){var n,i,a,o=b(t),s=-1===(i=(n=t).indexOf("#"))?void 0:n.slice(i+1),l=o?this.cache[o]:r;if(l&&o&&l!==r){var u;e.path.push(o);var f=e.getAncestor(l.id);if(f)u=f;else if(u=new g(e),v.compileSchema.call(this,u,l)){var c=this.options;try{this.options=l.__$validationOptions||this.options,_.validateSchema.call(this,u,l)}finally{this.options=c}}var d=u.isValid();if(d||e.addError("REMOTE_NOT_VALID",[t],u),e.path.pop(),!d)return}if(l&&s)for(var p=s.split("/"),h=0,m=p.length;l&&h<m;h++){var y=(a=p[h],decodeURIComponent(a).replace(/~[0-1]/g,function(e){return"~1"===e?"/":"~"}));l=0===h?E(l,y):l[y]}return l},r.getRemotePath=b},{"./Report":169,"./SchemaCompilation":171,"./SchemaValidation":172,"./Utils":173,"lodash.isequal":84}],171:[function(e,t,g){"use strict";var v=e("./Report"),_=e("./SchemaCache"),b=e("./Utils");function E(e,t){if(b.isAbsoluteUri(t))return t;var r,n=e.join(""),i=b.isAbsoluteUri(n),a=b.isRelativeUri(n),o=b.isRelativeUri(t);i&&o?(r=n.match(/\/[^\/]*$/))&&(n=n.slice(0,r.index+1)):a&&o?n="":(r=n.match(/[^#/]+$/))&&(n=n.slice(0,r.index));var s=n+t;return s=s.replace(/##/,"#")}var S=function(e,t){for(var r=t.length,n=0;r--;){var i=new v(e);g.compileSchema.call(this,i,t[r])&&n++,e.errors=e.errors.concat(i.errors)}return n};function O(e,t){for(var r=e.length;r--;)if(e[r].id===t)return e[r];return null}g.compileSchema=function(e,t){if(e.commonErrorMessage="SCHEMA_COMPILATION_FAILED","string"==typeof t){var r=_.getSchemaByUri.call(this,e,t);if(!r)return e.addError("SCHEMA_NOT_REACHABLE",[t]),!1;t=r}if(Array.isArray(t))return function(e,t){var r,n=0;do{for(var i=e.errors.length;i--;)"UNRESOLVABLE_REFERENCE"===e.errors[i].code&&e.errors.splice(i,1);for(r=n,n=S.call(this,e,t),i=t.length;i--;){var a=t[i];if(a.__$missingReferences){for(var o=a.__$missingReferences.length;o--;){var s=a.__$missingReferences[o],l=O(t,s.ref);l&&(s.obj["__"+s.key+"Resolved"]=l,a.__$missingReferences.splice(o,1))}0===a.__$missingReferences.length&&delete a.__$missingReferences}}}while(n!==t.length&&n!==r);return e.isValid()}.call(this,e,t);if(t.__$compiled&&t.id&&!1===_.checkCacheForUri.call(this,t.id)&&(t.__$compiled=void 0),t.__$compiled)return!0;t.id&&"string"==typeof t.id&&_.cacheSchemaByUri.call(this,t.id,t);var n=!1;e.rootSchema||(e.rootSchema=t,n=!0);var i=e.isValid();delete t.__$missingReferences;for(var a=function e(t,r,n,i){if(r=r||[],n=n||[],i=i||[],"object"!=typeof t||null===t)return r;var a;if("string"==typeof t.id&&n.push(t.id),"string"==typeof t.$ref&&void 0===t.__$refResolved&&r.push({ref:E(n,t.$ref),key:"$ref",obj:t,path:i.slice(0)}),"string"==typeof t.$schema&&void 0===t.__$schemaResolved&&r.push({ref:E(n,t.$schema),key:"$schema",obj:t,path:i.slice(0)}),Array.isArray(t))for(a=t.length;a--;)i.push(a.toString()),e(t[a],r,n,i),i.pop();else{var o=Object.keys(t);for(a=o.length;a--;)0!==o[a].indexOf("__$")&&(i.push(o[a]),e(t[o[a]],r,n,i),i.pop())}return"string"==typeof t.id&&n.pop(),r}.call(this,t),o=a.length;o--;){var s=a[o],l=_.getSchemaByUri.call(this,e,s.ref,t);if(!l){var u=this.getSchemaReader();if(u){var f=u(s.ref);if(f){f.id=s.ref;var c=new v(e);g.compileSchema.call(this,c,f)?l=_.getSchemaByUri.call(this,e,s.ref,t):e.errors=e.errors.concat(c.errors)}}}if(!l){var d=e.hasError("REMOTE_NOT_VALID",[s.ref]),p=b.isAbsoluteUri(s.ref),h=!1,m=!0===this.options.ignoreUnresolvableReferences;p&&(h=_.checkCacheForUri.call(this,s.ref)),d||m&&p||h||(Array.prototype.push.apply(e.path,s.path),e.addError("UNRESOLVABLE_REFERENCE",[s.ref]),e.path=e.path.slice(0,-s.path.length),i&&(t.__$missingReferences=t.__$missingReferences||[],t.__$missingReferences.push(s)))}s.obj["__"+s.key+"Resolved"]=l}var y=e.isValid();return y?t.__$compiled=!0:t.id&&"string"==typeof t.id&&_.removeFromCacheByUri.call(this,t.id),n&&(e.rootSchema=void 0),y}},{"./Report":169,"./SchemaCache":170,"./Utils":173}],172:[function(e,t,f){"use strict";var r=e("./FormatValidators"),c=e("./JsonValidation"),d=e("./Report"),p=e("./Utils"),h={$ref:function(e,t){"string"!=typeof t.$ref&&e.addError("KEYWORD_TYPE_EXPECTED",["$ref","string"])},$schema:function(e,t){"string"!=typeof t.$schema&&e.addError("KEYWORD_TYPE_EXPECTED",["$schema","string"])},multipleOf:function(e,t){"number"!=typeof t.multipleOf?e.addError("KEYWORD_TYPE_EXPECTED",["multipleOf","number"]):t.multipleOf<=0&&e.addError("KEYWORD_MUST_BE",["multipleOf","strictly greater than 0"])},maximum:function(e,t){"number"!=typeof t.maximum&&e.addError("KEYWORD_TYPE_EXPECTED",["maximum","number"])},exclusiveMaximum:function(e,t){"boolean"!=typeof t.exclusiveMaximum?e.addError("KEYWORD_TYPE_EXPECTED",["exclusiveMaximum","boolean"]):void 0===t.maximum&&e.addError("KEYWORD_DEPENDENCY",["exclusiveMaximum","maximum"])},minimum:function(e,t){"number"!=typeof t.minimum&&e.addError("KEYWORD_TYPE_EXPECTED",["minimum","number"])},exclusiveMinimum:function(e,t){"boolean"!=typeof t.exclusiveMinimum?e.addError("KEYWORD_TYPE_EXPECTED",["exclusiveMinimum","boolean"]):void 0===t.minimum&&e.addError("KEYWORD_DEPENDENCY",["exclusiveMinimum","minimum"])},maxLength:function(e,t){"integer"!==p.whatIs(t.maxLength)?e.addError("KEYWORD_TYPE_EXPECTED",["maxLength","integer"]):t.maxLength<0&&e.addError("KEYWORD_MUST_BE",["maxLength","greater than, or equal to 0"])},minLength:function(e,t){"integer"!==p.whatIs(t.minLength)?e.addError("KEYWORD_TYPE_EXPECTED",["minLength","integer"]):t.minLength<0&&e.addError("KEYWORD_MUST_BE",["minLength","greater than, or equal to 0"])},pattern:function(t,r){if("string"!=typeof r.pattern)t.addError("KEYWORD_TYPE_EXPECTED",["pattern","string"]);else try{RegExp(r.pattern)}catch(e){t.addError("KEYWORD_PATTERN",["pattern",r.pattern])}},additionalItems:function(e,t){var r=p.whatIs(t.additionalItems);"boolean"!==r&&"object"!==r?e.addError("KEYWORD_TYPE_EXPECTED",["additionalItems",["boolean","object"]]):"object"===r&&(e.path.push("additionalItems"),f.validateSchema.call(this,e,t.additionalItems),e.path.pop())},items:function(e,t){var r=p.whatIs(t.items);if("object"===r)e.path.push("items"),f.validateSchema.call(this,e,t.items),e.path.pop();else if("array"===r)for(var n=t.items.length;n--;)e.path.push("items"),e.path.push(n.toString()),f.validateSchema.call(this,e,t.items[n]),e.path.pop(),e.path.pop();else e.addError("KEYWORD_TYPE_EXPECTED",["items",["array","object"]]);!0===this.options.forceAdditional&&void 0===t.additionalItems&&Array.isArray(t.items)&&e.addError("KEYWORD_UNDEFINED_STRICT",["additionalItems"]),this.options.assumeAdditional&&void 0===t.additionalItems&&Array.isArray(t.items)&&(t.additionalItems=!1)},maxItems:function(e,t){"number"!=typeof t.maxItems?e.addError("KEYWORD_TYPE_EXPECTED",["maxItems","integer"]):t.maxItems<0&&e.addError("KEYWORD_MUST_BE",["maxItems","greater than, or equal to 0"])},minItems:function(e,t){"integer"!==p.whatIs(t.minItems)?e.addError("KEYWORD_TYPE_EXPECTED",["minItems","integer"]):t.minItems<0&&e.addError("KEYWORD_MUST_BE",["minItems","greater than, or equal to 0"])},uniqueItems:function(e,t){"boolean"!=typeof t.uniqueItems&&e.addError("KEYWORD_TYPE_EXPECTED",["uniqueItems","boolean"])},maxProperties:function(e,t){"integer"!==p.whatIs(t.maxProperties)?e.addError("KEYWORD_TYPE_EXPECTED",["maxProperties","integer"]):t.maxProperties<0&&e.addError("KEYWORD_MUST_BE",["maxProperties","greater than, or equal to 0"])},minProperties:function(e,t){"integer"!==p.whatIs(t.minProperties)?e.addError("KEYWORD_TYPE_EXPECTED",["minProperties","integer"]):t.minProperties<0&&e.addError("KEYWORD_MUST_BE",["minProperties","greater than, or equal to 0"])},required:function(e,t){if("array"!==p.whatIs(t.required))e.addError("KEYWORD_TYPE_EXPECTED",["required","array"]);else if(0===t.required.length)e.addError("KEYWORD_MUST_BE",["required","an array with at least one element"]);else{for(var r=t.required.length;r--;)"string"!=typeof t.required[r]&&e.addError("KEYWORD_VALUE_TYPE",["required","string"]);!1===p.isUniqueArray(t.required)&&e.addError("KEYWORD_MUST_BE",["required","an array with unique items"])}},additionalProperties:function(e,t){var r=p.whatIs(t.additionalProperties);"boolean"!==r&&"object"!==r?e.addError("KEYWORD_TYPE_EXPECTED",["additionalProperties",["boolean","object"]]):"object"===r&&(e.path.push("additionalProperties"),f.validateSchema.call(this,e,t.additionalProperties),e.path.pop())},properties:function(e,t){if("object"===p.whatIs(t.properties)){for(var r=Object.keys(t.properties),n=r.length;n--;){var i=r[n],a=t.properties[i];e.path.push("properties"),e.path.push(i),f.validateSchema.call(this,e,a),e.path.pop(),e.path.pop()}!0===this.options.forceAdditional&&void 0===t.additionalProperties&&e.addError("KEYWORD_UNDEFINED_STRICT",["additionalProperties"]),this.options.assumeAdditional&&void 0===t.additionalProperties&&(t.additionalProperties=!1),!0===this.options.forceProperties&&0===r.length&&e.addError("CUSTOM_MODE_FORCE_PROPERTIES",["properties"])}else e.addError("KEYWORD_TYPE_EXPECTED",["properties","object"])},patternProperties:function(t,e){if("object"===p.whatIs(e.patternProperties)){for(var r=Object.keys(e.patternProperties),n=r.length;n--;){var i=r[n],a=e.patternProperties[i];try{RegExp(i)}catch(e){t.addError("KEYWORD_PATTERN",["patternProperties",i])}t.path.push("patternProperties"),t.path.push(i.toString()),f.validateSchema.call(this,t,a),t.path.pop(),t.path.pop()}!0===this.options.forceProperties&&0===r.length&&t.addError("CUSTOM_MODE_FORCE_PROPERTIES",["patternProperties"])}else t.addError("KEYWORD_TYPE_EXPECTED",["patternProperties","object"])},dependencies:function(e,t){if("object"!==p.whatIs(t.dependencies))e.addError("KEYWORD_TYPE_EXPECTED",["dependencies","object"]);else for(var r=Object.keys(t.dependencies),n=r.length;n--;){var i=r[n],a=t.dependencies[i],o=p.whatIs(a);if("object"===o)e.path.push("dependencies"),e.path.push(i),f.validateSchema.call(this,e,a),e.path.pop(),e.path.pop();else if("array"===o){var s=a.length;for(0===s&&e.addError("KEYWORD_MUST_BE",["dependencies","not empty array"]);s--;)"string"!=typeof a[s]&&e.addError("KEYWORD_VALUE_TYPE",["dependensices","string"]);!1===p.isUniqueArray(a)&&e.addError("KEYWORD_MUST_BE",["dependencies","an array with unique items"])}else e.addError("KEYWORD_VALUE_TYPE",["dependencies","object or array"])}},enum:function(e,t){!1===Array.isArray(t.enum)?e.addError("KEYWORD_TYPE_EXPECTED",["enum","array"]):0===t.enum.length?e.addError("KEYWORD_MUST_BE",["enum","an array with at least one element"]):!1===p.isUniqueArray(t.enum)&&e.addError("KEYWORD_MUST_BE",["enum","an array with unique elements"])},type:function(e,t){var r=["array","boolean","integer","number","null","object","string"],n=r.join(","),i=Array.isArray(t.type);if(i){for(var a=t.type.length;a--;)-1===r.indexOf(t.type[a])&&e.addError("KEYWORD_TYPE_EXPECTED",["type",n]);!1===p.isUniqueArray(t.type)&&e.addError("KEYWORD_MUST_BE",["type","an object with unique properties"])}else"string"==typeof t.type?-1===r.indexOf(t.type)&&e.addError("KEYWORD_TYPE_EXPECTED",["type",n]):e.addError("KEYWORD_TYPE_EXPECTED",["type",["string","array"]]);!0===this.options.noEmptyStrings&&("string"===t.type||i&&-1!==t.type.indexOf("string"))&&void 0===t.minLength&&void 0===t.enum&&void 0===t.format&&(t.minLength=1),!0===this.options.noEmptyArrays&&("array"===t.type||i&&-1!==t.type.indexOf("array"))&&void 0===t.minItems&&(t.minItems=1),!0===this.options.forceProperties&&("object"===t.type||i&&-1!==t.type.indexOf("object"))&&void 0===t.properties&&void 0===t.patternProperties&&e.addError("KEYWORD_UNDEFINED_STRICT",["properties"]),!0===this.options.forceItems&&("array"===t.type||i&&-1!==t.type.indexOf("array"))&&void 0===t.items&&e.addError("KEYWORD_UNDEFINED_STRICT",["items"]),!0===this.options.forceMinItems&&("array"===t.type||i&&-1!==t.type.indexOf("array"))&&void 0===t.minItems&&e.addError("KEYWORD_UNDEFINED_STRICT",["minItems"]),!0===this.options.forceMaxItems&&("array"===t.type||i&&-1!==t.type.indexOf("array"))&&void 0===t.maxItems&&e.addError("KEYWORD_UNDEFINED_STRICT",["maxItems"]),!0===this.options.forceMinLength&&("string"===t.type||i&&-1!==t.type.indexOf("string"))&&void 0===t.minLength&&void 0===t.format&&void 0===t.enum&&void 0===t.pattern&&e.addError("KEYWORD_UNDEFINED_STRICT",["minLength"]),!0===this.options.forceMaxLength&&("string"===t.type||i&&-1!==t.type.indexOf("string"))&&void 0===t.maxLength&&void 0===t.format&&void 0===t.enum&&void 0===t.pattern&&e.addError("KEYWORD_UNDEFINED_STRICT",["maxLength"])},allOf:function(e,t){if(!1===Array.isArray(t.allOf))e.addError("KEYWORD_TYPE_EXPECTED",["allOf","array"]);else if(0===t.allOf.length)e.addError("KEYWORD_MUST_BE",["allOf","an array with at least one element"]);else for(var r=t.allOf.length;r--;)e.path.push("allOf"),e.path.push(r.toString()),f.validateSchema.call(this,e,t.allOf[r]),e.path.pop(),e.path.pop()},anyOf:function(e,t){if(!1===Array.isArray(t.anyOf))e.addError("KEYWORD_TYPE_EXPECTED",["anyOf","array"]);else if(0===t.anyOf.length)e.addError("KEYWORD_MUST_BE",["anyOf","an array with at least one element"]);else for(var r=t.anyOf.length;r--;)e.path.push("anyOf"),e.path.push(r.toString()),f.validateSchema.call(this,e,t.anyOf[r]),e.path.pop(),e.path.pop()},oneOf:function(e,t){if(!1===Array.isArray(t.oneOf))e.addError("KEYWORD_TYPE_EXPECTED",["oneOf","array"]);else if(0===t.oneOf.length)e.addError("KEYWORD_MUST_BE",["oneOf","an array with at least one element"]);else for(var r=t.oneOf.length;r--;)e.path.push("oneOf"),e.path.push(r.toString()),f.validateSchema.call(this,e,t.oneOf[r]),e.path.pop(),e.path.pop()},not:function(e,t){"object"!==p.whatIs(t.not)?e.addError("KEYWORD_TYPE_EXPECTED",["not","object"]):(e.path.push("not"),f.validateSchema.call(this,e,t.not),e.path.pop())},definitions:function(e,t){if("object"!==p.whatIs(t.definitions))e.addError("KEYWORD_TYPE_EXPECTED",["definitions","object"]);else for(var r=Object.keys(t.definitions),n=r.length;n--;){var i=r[n],a=t.definitions[i];e.path.push("definitions"),e.path.push(i),f.validateSchema.call(this,e,a),e.path.pop(),e.path.pop()}},format:function(e,t){"string"!=typeof t.format?e.addError("KEYWORD_TYPE_EXPECTED",["format","string"]):void 0===r[t.format]&&!0!==this.options.ignoreUnknownFormats&&e.addError("UNKNOWN_FORMAT",[t.format])},id:function(e,t){"string"!=typeof t.id&&e.addError("KEYWORD_TYPE_EXPECTED",["id","string"])},title:function(e,t){"string"!=typeof t.title&&e.addError("KEYWORD_TYPE_EXPECTED",["title","string"])},description:function(e,t){"string"!=typeof t.description&&e.addError("KEYWORD_TYPE_EXPECTED",["description","string"])},default:function(){}};f.validateSchema=function(e,t){if(e.commonErrorMessage="SCHEMA_VALIDATION_FAILED",Array.isArray(t))return function(e,t){for(var r=t.length;r--;)f.validateSchema.call(this,e,t[r]);return e.isValid()}.call(this,e,t);if(t.__$validated)return!0;var r=t.$schema&&t.id!==t.$schema;if(r)if(t.__$schemaResolved&&t.__$schemaResolved!==t){var n=new d(e);!1===c.validate.call(this,n,t.__$schemaResolved,t)&&e.addError("PARENT_SCHEMA_VALIDATION_FAILED",null,n)}else!0!==this.options.ignoreUnresolvableReferences&&e.addError("REF_UNRESOLVED",[t.$schema]);if(!0===this.options.noTypeless){if(void 0!==t.type){var i=[];Array.isArray(t.anyOf)&&(i=i.concat(t.anyOf)),Array.isArray(t.oneOf)&&(i=i.concat(t.oneOf)),Array.isArray(t.allOf)&&(i=i.concat(t.allOf)),i.forEach(function(e){e.type||(e.type=t.type)})}void 0===t.enum&&void 0===t.type&&void 0===t.anyOf&&void 0===t.oneOf&&void 0===t.not&&void 0===t.$ref&&e.addError("KEYWORD_UNDEFINED_STRICT",["type"])}for(var a=Object.keys(t),o=a.length;o--;){var s=a[o];0!==s.indexOf("__")&&(void 0!==h[s]?h[s].call(this,e,t):r||!0===this.options.noExtraKeywords&&e.addError("KEYWORD_UNEXPECTED",[s]))}if(!0===this.options.pedanticCheck){if(t.enum){var l=p.clone(t);for(delete l.enum,delete l.default,e.path.push("enum"),o=t.enum.length;o--;)e.path.push(o.toString()),c.validate.call(this,e,l,t.enum[o]),e.path.pop();e.path.pop()}t.default&&(e.path.push("default"),c.validate.call(this,e,t,t.default),e.path.pop())}var u=e.isValid();return u&&(t.__$validated=!0),u}},{"./FormatValidators":166,"./JsonValidation":167,"./Report":169,"./Utils":173}],173:[function(e,t,l){"use strict";e("core-js/es/symbol"),l.jsonSymbol=Symbol.for("z-schema/json"),l.schemaSymbol=Symbol.for("z-schema/schema");var u=l.sortedKeys=function(e){return Object.keys(e).sort()};l.isAbsoluteUri=function(e){return/^https?:\/\//.test(e)},l.isRelativeUri=function(e){return/.+#/.test(e)},l.whatIs=function(e){var t=typeof e;return"object"===t?null===e?"null":Array.isArray(e)?"array":"object":"number"===t?Number.isFinite(e)?e%1==0?"integer":"number":Number.isNaN(e)?"not-a-number":"unknown-number":t},l.areEqual=function e(t,r,n){var i,a,o=(n=n||{}).caseInsensitiveComparison||!1;if(t===r)return!0;if(!0===o&&"string"==typeof t&&"string"==typeof r&&t.toUpperCase()===r.toUpperCase())return!0;if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return!1;for(a=t.length,i=0;i<a;i++)if(!e(t[i],r[i],{caseInsensitiveComparison:o}))return!1;return!0}if("object"!==l.whatIs(t)||"object"!==l.whatIs(r))return!1;var s=u(t);if(!e(s,u(r),{caseInsensitiveComparison:o}))return!1;for(a=s.length,i=0;i<a;i++)if(!e(t[s[i]],r[s[i]],{caseInsensitiveComparison:o}))return!1;return!0},l.isUniqueArray=function(e,t){var r,n,i=e.length;for(r=0;r<i;r++)for(n=r+1;n<i;n++)if(l.areEqual(e[r],e[n]))return t&&t.push(r,n),!1;return!0},l.difference=function(e,t){for(var r=[],n=e.length;n--;)-1===t.indexOf(e[n])&&r.push(e[n]);return r},l.clone=function(e){if(void 0!==e){if("object"!=typeof e||null===e)return e;var t,r;if(Array.isArray(e))for(t=[],r=e.length;r--;)t[r]=e[r];else{t={};var n=Object.keys(e);for(r=n.length;r--;){var i=n[r];t[i]=e[i]}}return t}},l.cloneDeep=function(e){var s=0,l=new Map,u=[];return function e(t){if("object"!=typeof t||null===t)return t;var r,n,i;if(void 0!==(i=l.get(t)))return u[i];if(l.set(t,s++),Array.isArray(t))for(r=[],u.push(r),n=t.length;n--;)r[n]=e(t[n]);else{r={},u.push(r);var a=Object.keys(t);for(n=a.length;n--;){var o=a[n];r[o]=e(t[o])}}return r}(e)},l.ucs2decode=function(e){for(var t,r,n=[],i=0,a=e.length;i<a;)55296<=(t=e.charCodeAt(i++))&&t<=56319&&i<a?56320==(64512&(r=e.charCodeAt(i++)))?n.push(((1023&t)<<10)+(1023&r)+65536):(n.push(t),i--):n.push(t);return n}},{"core-js/es/symbol":1}],174:[function(e,s,t){(function(c){"use strict";e("./Polyfills");var d=e("lodash.get"),p=e("./Report"),r=e("./FormatValidators"),h=e("./JsonValidation"),m=e("./SchemaCache"),y=e("./SchemaCompilation"),g=e("./SchemaValidation"),v=e("./Utils"),n=e("./schemas/schema.json"),i=e("./schemas/hyper-schema.json"),a={asyncTimeout:2e3,forceAdditional:!1,assumeAdditional:!1,enumCaseInsensitiveComparison:!1,forceItems:!1,forceMinItems:!1,forceMaxItems:!1,forceMinLength:!1,forceMaxLength:!1,forceProperties:!1,ignoreUnresolvableReferences:!1,noExtraKeywords:!1,noTypeless:!1,noEmptyStrings:!1,noEmptyArrays:!1,strictUris:!1,strictMode:!1,reportPathAsArray:!1,breakOnFirstError:!0,pedanticCheck:!1,ignoreUnknownFormats:!1,customValidator:null};function o(e){var t;if("object"==typeof e){for(var r,n=Object.keys(e),i=n.length;i--;)if(r=n[i],void 0===a[r])throw new Error("Unexpected option passed to constructor: "+r);for(i=(n=Object.keys(a)).length;i--;)void 0===e[r=n[i]]&&(e[r]=v.clone(a[r]));t=e}else t=v.clone(a);return!0===t.strictMode&&(t.forceAdditional=!0,t.forceItems=!0,t.forceMaxLength=!0,t.forceProperties=!0,t.noExtraKeywords=!0,t.noTypeless=!0,t.noEmptyStrings=!0,t.noEmptyArrays=!0),t}function t(e){this.cache={},this.referenceCache=[],this.validateOptions={},this.options=o(e);var t=o({});this.setRemoteReference("http://json-schema.org/draft-04/schema",n,t),this.setRemoteReference("http://json-schema.org/draft-04/hyper-schema",i,t)}t.prototype.compileSchema=function(e){var t=new p(this.options);return e=m.getSchema.call(this,t,e),y.compileSchema.call(this,t,e),(this.lastReport=t).isValid()},t.prototype.validateSchema=function(e){if(Array.isArray(e)&&0===e.length)throw new Error(".validateSchema was called with an empty array");var t=new p(this.options);return e=m.getSchema.call(this,t,e),y.compileSchema.call(this,t,e)&&g.validateSchema.call(this,t,e),(this.lastReport=t).isValid()},t.prototype.validate=function(e,t,r,n){"function"===v.whatIs(r)&&(n=r,r={}),r||(r={}),this.validateOptions=r;var i=v.whatIs(t);if("string"!==i&&"object"!==i){var a=new Error("Invalid .validate call - schema must be an string or object but "+i+" was passed!");if(n)return void c.nextTick(function(){n(a,!1)});throw a}var o=!1,s=new p(this.options);if(s.json=e,"string"==typeof t){var l=t;if(!(t=m.getSchema.call(this,s,l)))throw new Error("Schema with id '"+l+"' wasn't found in the validator cache!")}else t=m.getSchema.call(this,s,t);var u=!1;o||(u=y.compileSchema.call(this,s,t)),u||(this.lastReport=s,o=!0);var f=!1;if(o||(f=g.validateSchema.call(this,s,t)),f||(this.lastReport=s,o=!0),r.schemaPath&&(s.rootSchema=t,!(t=d(t,r.schemaPath))))throw new Error("Schema path '"+r.schemaPath+"' wasn't found in the schema!");if(o||h.validate.call(this,s,t,e),!n){if(0<s.asyncTasks.length)throw new Error("This validation has async tasks and cannot be done in sync mode, please provide callback argument.");return(this.lastReport=s).isValid()}s.processAsyncTasks(this.options.asyncTimeout,n)},t.prototype.getLastError=function(){if(0===this.lastReport.errors.length)return null;var e=new Error;return e.name="z-schema validation error",e.message=this.lastReport.commonErrorMessage,e.details=this.lastReport.errors,e},t.prototype.getLastErrors=function(){return this.lastReport&&0<this.lastReport.errors.length?this.lastReport.errors:void 0},t.prototype.getMissingReferences=function(e){for(var t=[],r=(e=e||this.lastReport.errors).length;r--;){var n=e[r];if("UNRESOLVABLE_REFERENCE"===n.code){var i=n.params[0];-1===t.indexOf(i)&&t.push(i)}n.inner&&(t=t.concat(this.getMissingReferences(n.inner)))}return t},t.prototype.getMissingRemoteReferences=function(){for(var e=this.getMissingReferences(),t=[],r=e.length;r--;){var n=m.getRemotePath(e[r]);n&&-1===t.indexOf(n)&&t.push(n)}return t},t.prototype.setRemoteReference=function(e,t,r){t="string"==typeof t?JSON.parse(t):v.cloneDeep(t),r&&(t.__$validationOptions=o(r)),m.cacheSchemaByUri.call(this,e,t)},t.prototype.getResolvedSchema=function(e){var t=new p(this.options);e=m.getSchema.call(this,t,e),e=v.cloneDeep(e);var a=[],o=function(e){var t,r=v.whatIs(e);if(("object"===r||"array"===r)&&!e.___$visited){if(e.___$visited=!0,a.push(e),e.$ref&&e.__$refResolved){var n=e.__$refResolved,i=e;for(t in delete e.$ref,delete e.__$refResolved,n)n.hasOwnProperty(t)&&(i[t]=n[t])}for(t in e)e.hasOwnProperty(t)&&(0===t.indexOf("__$")?delete e[t]:o(e[t]))}};if(o(e),a.forEach(function(e){delete e.___$visited}),(this.lastReport=t).isValid())return e;throw this.getLastError()},t.prototype.setSchemaReader=function(e){return t.setSchemaReader(e)},t.prototype.getSchemaReader=function(){return t.schemaReader},t.schemaReader=void 0,t.setSchemaReader=function(e){t.schemaReader=e},t.registerFormat=function(e,t){r[e]=t},t.unregisterFormat=function(e){delete r[e]},t.getRegisteredFormats=function(){return Object.keys(r)},t.getDefaultOptions=function(){return v.cloneDeep(a)},t.schemaSymbol=v.schemaSymbol,t.jsonSymbol=v.jsonSymbol,s.exports=t}).call(this,e("_process"))},{"./FormatValidators":166,"./JsonValidation":167,"./Polyfills":168,"./Report":169,"./SchemaCache":170,"./SchemaCompilation":171,"./SchemaValidation":172,"./Utils":173,"./schemas/hyper-schema.json":175,"./schemas/schema.json":176,_process:85,"lodash.get":83}],175:[function(e,t,r){t.exports={$schema:"http://json-schema.org/draft-04/hyper-schema#",id:"http://json-schema.org/draft-04/hyper-schema#",title:"JSON Hyper-Schema",allOf:[{$ref:"http://json-schema.org/draft-04/schema#"}],properties:{additionalItems:{anyOf:[{type:"boolean"},{$ref:"#"}]},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#"}]},dependencies:{additionalProperties:{anyOf:[{$ref:"#"},{type:"array"}]}},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}]},definitions:{additionalProperties:{$ref:"#"}},patternProperties:{additionalProperties:{$ref:"#"}},properties:{additionalProperties:{$ref:"#"}},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"},links:{type:"array",items:{$ref:"#/definitions/linkDescription"}},fragmentResolution:{type:"string"},media:{type:"object",properties:{type:{description:"A media type, as described in RFC 2046",type:"string"},binaryEncoding:{description:"A content encoding scheme, as described in RFC 2045",type:"string"}}},pathStart:{description:"Instances' URIs must start with this value for this schema to apply to them",type:"string",format:"uri"}},definitions:{schemaArray:{type:"array",items:{$ref:"#"}},linkDescription:{title:"Link Description Object",type:"object",required:["href","rel"],properties:{href:{description:"a URI template, as defined by RFC 6570, with the addition of the $, ( and ) characters for pre-processing",type:"string"},rel:{description:"relation to the target resource of the link",type:"string"},title:{description:"a title for the link",type:"string"},targetSchema:{description:"JSON Schema describing the link target",$ref:"#"},mediaType:{description:"media type (as defined by RFC 2046) describing the link target",type:"string"},method:{description:'method for requesting the target of the link (e.g. for HTTP this might be "GET" or "DELETE")',type:"string"},encType:{description:"The media type in which to submit data along with the request",type:"string",default:"application/json"},schema:{description:"Schema describing the data to submit along with the request",$ref:"#"}}}}}},{}],176:[function(e,t,r){t.exports={id:"http://json-schema.org/draft-04/schema#",$schema:"http://json-schema.org/draft-04/schema#",description:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},positiveInteger:{type:"integer",minimum:0},positiveIntegerDefault0:{allOf:[{$ref:"#/definitions/positiveInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},minItems:1,uniqueItems:!0}},type:"object",properties:{id:{type:"string",format:"uri"},$schema:{type:"string",format:"uri"},title:{type:"string"},description:{type:"string"},default:{},multipleOf:{type:"number",minimum:0,exclusiveMinimum:!0},maximum:{type:"number"},exclusiveMaximum:{type:"boolean",default:!1},minimum:{type:"number"},exclusiveMinimum:{type:"boolean",default:!1},maxLength:{$ref:"#/definitions/positiveInteger"},minLength:{$ref:"#/definitions/positiveIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{anyOf:[{type:"boolean"},{$ref:"#"}],default:{}},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:{}},maxItems:{$ref:"#/definitions/positiveInteger"},minItems:{$ref:"#/definitions/positiveIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxProperties:{$ref:"#/definitions/positiveInteger"},minProperties:{$ref:"#/definitions/positiveIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#"}],default:{}},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},enum:{type:"array",minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},dependencies:{exclusiveMaximum:["maximum"],exclusiveMinimum:["minimum"]},default:{}}},{}]},{},[165,166,167,168,169,170,171,172,173,174])(174)});
//# sourceMappingURL=ZSchema-browser-min.js.map
|
var a00279 =
[
[ "BLOB_CHOICE", "a00279.html#ac5eecc4e7e27e6f6f6defb9de1aceaf7", null ],
[ "BLOB_CHOICE", "a00279.html#a8a3ee3cbec5c8f9d8238fb60ca5bb800", null ],
[ "BLOB_CHOICE", "a00279.html#a511e25dca4c5a933bdc5f419320a3f6b", null ],
[ "~BLOB_CHOICE", "a00279.html#a9044dc95d425d627cd7ad513ddd449f7", null ],
[ "certainty", "a00279.html#af53d45b718c562ea7209b583c77ac14e", null ],
[ "classifier", "a00279.html#a038aafcd01612d7146d0d8bdb38d5326", null ],
[ "fontinfo_id", "a00279.html#a3594e34861be86d775724f5f91fba3be", null ],
[ "fontinfo_id2", "a00279.html#a22193fee2f759262aa5ce68e4b288192", null ],
[ "fonts", "a00279.html#aabee74a6a1007d92e809b17fed7ea1ab", null ],
[ "IsAdapted", "a00279.html#a9bdfaafb7bf74ed66d4b8692ccb9d62c", null ],
[ "IsClassified", "a00279.html#a8ddbb94cfc6eecb95902c00ac676e6d7", null ],
[ "matrix_cell", "a00279.html#ad3d14608128f7074b40927cbb0bee855", null ],
[ "max_xheight", "a00279.html#acde597d08a8bb994c000f9b29003be0b", null ],
[ "min_xheight", "a00279.html#adb243de91aeefae6a959a9b82da2897f", null ],
[ "PosAndSizeAgree", "a00279.html#a014b4ce14a069bf4292e299de2c51504", null ],
[ "print", "a00279.html#aa8b5ed696b1c87aeea65a8e881a935fc", null ],
[ "print_full", "a00279.html#a3535ecafa25fca25c5eec0d99cbb9c8b", null ],
[ "rating", "a00279.html#a7fbd2d505bf5b55beee424096fb1e9bc", null ],
[ "script_id", "a00279.html#a746d149d149ec75e4bea96f338b48433", null ],
[ "set_certainty", "a00279.html#ae3331f9e390403bdf37c6e98fa067742", null ],
[ "set_classifier", "a00279.html#a389f3ddc1bb2dec5320c89fdd01d6bd0", null ],
[ "set_fonts", "a00279.html#a357049b41d1f8f5c3f7901989eb4c135", null ],
[ "set_matrix_cell", "a00279.html#acd1a2f8fa2cac5894de41a0ad93d9005", null ],
[ "set_rating", "a00279.html#a20cb2e28102e9a34e5eb098f8c57ff64", null ],
[ "set_script", "a00279.html#a196ab353d2ea612604364642ab33e0ec", null ],
[ "set_unichar_id", "a00279.html#af740a2c4156630dcf9cadf54aecaa2e7", null ],
[ "set_xgap_after", "a00279.html#ad2c31c8520280310f9006f788f63480b", null ],
[ "set_xgap_before", "a00279.html#a2cc370419c946a3b1855f31bffc19bf1", null ],
[ "unichar_id", "a00279.html#aaba6190b77c5f3dc21905fc4118afa94", null ],
[ "xgap_after", "a00279.html#aa29db6f7e4f29118858ddcd8ee633ea4", null ],
[ "xgap_before", "a00279.html#a10a38e3bb5a661cf2e3deef952c2bf5b", null ],
[ "yshift", "a00279.html#a48de11e6a7c7fe505667bcc1f032f632", null ]
];
|
import React, { useState } from 'react';
import { ReportService } from './service';
import * as Yup from 'yup';
import { Formik } from 'formik';
import 'bootstrap/dist/css/bootstrap.min.css';
import Select from '@material-ui/core/Select';
import MenuItem from '@material-ui/core/MenuItem';
import {
Box,
Button,
Container,
TextField,
Typography
} from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles({
root: {
background: 'white',
border: 1,
borderRadius: 3,
boxShadow: '-1px 8px 36px 4px rgba(158,158,158,1)',
paddingTop: '30px',
paddingLeft: '50px',
paddingRight: '50px',
paddingBottom: '40px'
},
container: {
marginTop: '30px'
}
});
const GenerateReportView = () => {
const clases = useStyles();
const [year, setyear] = useState(' ');
const [type, setType] = useState(' ');
const handleCreate = () => {
ReportService({
year: year,
type: type
})
.then(() => {
let url = `https://mdquilindo.pythonanywhere.com/api/1.0/report/${year}/${type}`;
console.log(url)
window.open (url,'reporte',"directories=no, location=no, menubar=no, scrollbars=yes, statusbar=no, tittlebar=no, width=400, height=400");
})
.catch(() => {
});
};
const handleSubmit = event => {
event.preventDefault()
handleCreate();
};
const handleOnchangeyear = e => {
setyear(e.target.value);
};
const handleOnchangetype = e => {
setType(e.target.value);
};
return (
<Container maxWidth="sm" className={clases.container}>
<Formik
initialValues={{
year: ''
}}
validationSchema={Yup.object().shape({
year: Yup.string()
.max(255)
.required('year is required')
})}
onSubmit={() => {
return 1;
}}
>
{({
errors,
handleBlur,
handleChange,
isSubmitting,
touched,
values
}) => (
<>
<Box
display="flex"
flexDirection="column"
height="100%"
justifyContent="center"
>
<form onSubmit={e => handleSubmit(e)} className={clases.root}>
<Typography color="textPrimary" variant="h1" align="center">
Generar Reporte por año de Ingreso
</Typography>
<Box mb={3}>
<TextField
error={Boolean(touched.year && errors.year)}
fullWidth
helperText={touched.year && errors.year}
label="Año de Ingreso"
margin="normal"
name="year"
onChange={e => {
handleOnchangeyear(e);
handleChange(e);
}}
onBlur={handleBlur}
type="text"
value={values.year}
variant="outlined"
/>
<Select
id="Select-cohorte"
onChange={handleOnchangetype}>
<MenuItem value={1}>Excel</MenuItem>
<MenuItem value={2}>Pdf</MenuItem>
</Select>
<Box my={2}>
<Button
color="primary"
disabled={isSubmitting}
fullWidth
size="large"
type="submit"
variant="contained"
>
Generar Reporte
</Button>
</Box>
</Box>
</form>
</Box>
</>
)}
</Formik>
</Container>
);
};
export default GenerateReportView;
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var test = function test(msg) {
console.log(msg);
};
exports.default = test;
//# sourceMappingURL=test.js.map
|
export const groupFormPlus32 = "M26 20.5v-2a1.502 1.502 0 0 0-1.5-1.5h-17A1.502 1.502 0 0 0 6 18.5v2A1.502 1.502 0 0 0 7.5 22h17a1.502 1.502 0 0 0 1.5-1.5zm-19 0v-2a.5.5 0 0 1 .5-.5h17a.5.5 0 0 1 .5.5v2a.5.5 0 0 1-.5.5h-17a.5.5 0 0 1-.5-.5zM3 11H2V9h1zm0 4H2v-2h1zm26-2h1v2h-1zM3 19H2v-2h1zm26-2h1v2h-1zM3 23H2v-2h1zm26-2h1v2h-1zM7 6H5V5h2zm4 0H9V5h2zm4 0h-2V5h2zM3 26h1v1H2v-2h1zM2 5h2v1H3v1H2zm3 21h2v1H5zm6 1H9v-1h2zm4 0h-2v-1h2zm14-2h1v2h-2v-1h1zm-4 1h2v1h-2zm-2 0v1h-2v-1zm-4 0v1h-2v-1zM30 7v1h-6v6h-1V8h-6V7h6V1h1v6z";
|
import Homepage from '@/pages/HomePage';
import { SET_QUERY } from '@/store/mutation-types';
import render from '../../test-utils/render';
describe('Homepage', () => {
it('should render correct contents', () => {
const wrapper = render(Homepage);
expect(wrapper.find({ name: 'header-section' }).vm).toBeDefined();
expect(wrapper.find({ name: 'footer-section' }).vm).toBeDefined();
expect(wrapper.find({ name: 'license-icons' }).vm).toBeDefined();
});
it('should expose correct data values', () => {
const wrapper = render(Homepage);
expect(wrapper.vm.$data.images).toHaveLength(7);
});
it('commits a mutation when category is clicked', () => {
const storeMock = {
commit: jest.fn(),
};
const opts = {
mocks: {
$store: storeMock,
},
};
const wrapper = render(Homepage, opts);
const category = wrapper.find('.featured-images_banner').text().toLowerCase();
wrapper.find('.featured-images_item').trigger('click');
expect(storeMock.commit).toHaveBeenCalledWith(SET_QUERY,
{ query: { q: category }, shouldNavigate: true });
});
it('redirects to detail page when clicking on image in header-grid', () => {
const routerMock = {
push: jest.fn(),
};
const opts = {
mocks: {
$router: routerMock,
},
};
const wrapper = render(Homepage, opts);
wrapper.setData({ images: [
{
class: 'grid-item block b1',
id: '2b091d94',
},
],
});
wrapper.find('.grid-item').trigger('click');
expect(routerMock.push).toHaveBeenCalledWith('/photos/2b091d94');
});
});
|
$(document).ready(function() {
$('input[name="selectedTimeslot"]').on('input', function() {
var rawInput = $(this).val();
var filteredInput = rawInput.replace( /[^\d,]/g, '' );
var appid = $(this).data('appid');
var parsed = filteredInput.split(',');
var valid = true;
$(this).val(filteredInput);
if ($(this).val() ) {
var parsed = $(this).val().split(',');
for (var c in parsed) {
var char = parseInt(parsed[c]);
if (char === NaN || char < 0 || char > 167 ) {
valid = false;
break;
}
}
} else {
valid = false;
}
var submitButton = $('button.approveApp[data-appid="'+appid+'"]');
submitButton.prop('disabled', !valid);
}).on('change', function() {
var rawInput = $(this).val();
var filteredInput = rawInput.replace( /[^\d,]/g, '' );
var appid = $(this).data('appid');
var parsed = filteredInput.split(',');
var ts = parseInt(filteredInput);
$(this).val(filteredInput);
});
});
|
/**
* @file Data table stories.
* @copyright IBM Security 2019
*/
import { storiesOf } from '@storybook/react';
import { components } from '../../../.storybook';
const props = () => ({
useZebraStyles: false,
});
const readmeURL = 'https://goo.gl/dq6CEK';
/* eslint-disable global-require */
storiesOf(components('DataTable'), module)
.add('default', () => require('./stories/default').default(props()), {
info: {
/* eslint-disable no-useless-escape */
text: `
Data Tables are used to represent a collection of resources, displaying a
subset of their fields in columns, or headers. The \`DataTable\` component
that we export from Carbon requires two props to be passed in: \`rows\`
and \`headers\`.
You can find more detailed information surrounding usage of this component
at the following url: ${readmeURL}
`,
/* eslint-enable no-useless-escape */
},
})
.add(
'with batch actions',
() => require('./stories/with-batch-actions').default(props()),
{
info: {
text: `
Uses <TableToolbar> alongside <TableBatchActions> and <TableBatchAction>
to create the toolbar and placeholder for where the batch action menu will
be displayed.
You can use the \`getBatchActionProps\` prop getter on the
<TableBatchActions> component to have it wire up the ghost menu for you.
Individual <TableBatchAction> components take in any kind of event handler
prop that you would expect to use, like \`onClick\`. You can use these
alongside the \`selectedRows\` property in your \`render\` prop function
to pass along this info to your batch action handler.
You can find more detailed information surrounding usage of this component
at the following url: ${readmeURL}
`,
},
}
)
.add(
'with expansion',
() => require('./stories/with-expansion').default(props()),
{
info: {
text: `
DataTable with expansion
You can find more detailed information surrounding usage of this component
at the following url: ${readmeURL}
`,
},
}
)
.add('with overflow menu', () =>
require('./stories/with-overflow-menu').default(props())
)
.add(
'with selection',
() => require('./stories/with-selection').default(props()),
{
info: {
text: `
DataTable with selection
You can find more detailed information surrounding usage of this component
at the following url: ${readmeURL}
`,
},
}
)
.add(
'with sorting',
() => require('./stories/with-sorting').default(props()),
{
info: {
text: `
DataTable with sorting
You can find more detailed information surrounding usage of this component
at the following url: ${readmeURL}
`,
},
}
)
.add(
'with toolbar',
() => require('./stories/with-toolbar').default(props()),
{
info: {
text: `
DataTable with action menu, filtering, and CSV exporting. Note, the TableToolbarDownload
component expects the same rows and header props as provided to the parent Datatable component.
You can find more detailed information surrounding usage of the Datatable component
at the following url: ${readmeURL}
`,
},
}
)
.add('with skeleton', () =>
require('./stories/with-skeleton').default(props())
);
/* eslint-enable */
|
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../../coverage/store'),
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
|
/* Setting Vars */
let a_dir, a_col = [0, 0, 0, 255],
t_dir, t_col = [0, 0, 0, 255],
g_dir, g_col = [0, 0, 0, 255],
c_dir, c_col = [0, 0, 0, 255],
x_dir, x_col = [0, 0, 0, 255],
point_offset,
is_color_enabled = true,
in_file,
point_size = 3,
chunk_size = 4,
previous_config = {
in_file: in_file,
point_size: point_size,
point_offset: point_offset,
chunk_size: chunk_size
};
/**
* Converts color hex strings to numbers
*
* @param {string} hex
*
* @returns {Array} array holding [R, G, B]
*/
function hexToRGB(hex) {
let r = parseInt(hex.slice(1, 3), 16),
g = parseInt(hex.slice(3, 5), 16),
b = parseInt(hex.slice(5, 7), 16);
return [r, g, b];
}
/**
* Takes whats supplied in the inputs and applies it to global variables.
*/
function applySettings() {
a_dir = document.getElementById('a-dir').value;
[a_col[0], a_col[1], a_col[2], ] = hexToRGB(document.getElementById('a-col').value);
t_dir = document.getElementById('t-dir').value;
[t_col[0], t_col[1], t_col[2], ] = hexToRGB(document.getElementById('t-col').value);
g_dir = document.getElementById('g-dir').value;
[g_col[0], g_col[1], g_col[2], ] = hexToRGB(document.getElementById('g-col').value);
c_dir = document.getElementById('c-dir').value;
[c_col[0], c_col[1], c_col[2], ] = hexToRGB(document.getElementById('c-col').value);
x_dir = document.getElementById('x-dir').value;
[x_col[0], x_col[1], x_col[2], ] = hexToRGB(document.getElementById('x-col').value);
previous_config.point_offset = point_offset;
point_offset = parseInt(document.getElementById('offset').value); // resolution
previous_config.point_size = point_size;
point_size = parseInt(document.getElementById('size').value);
is_color_enabled = document.getElementById('color').checked;
previous_config.chunk_size = chunk_size;
chunk_size = parseInt(document.getElementById('chunksize').value);
}
/**
* Moves the cursor X and Y coordinates.
*
* @param {string} direction
* In which direction the cursor should move.
* Either N, E, S, W or defaults to not moving the cursor.
*
* @param {Object} cursor
* The cursor of which you want to change
* @param {number} cursor.x X coordinate
* @param {number} cursor.y Y coordinate
*
*/
function moveCursor(direction, cursor) {
switch (direction) {
case 'N':
cursor.y += 1;
break;
case 'E':
cursor.x += 1;
break;
case 'S':
cursor.y -= 1;
break;
case 'W':
cursor.x -= 1;
break;
case 'NE':
cursor.x += 1;
cursor.y += 1;
break;
case 'NW':
cursor.x -= 1;
cursor.y += 1;
break;
case 'SE':
cursor.x += 1;
cursor.y -= 1;
break;
case 'SW':
cursor.x -= 1;
cursor.y -= 1;
break;
default:
break;
}
}
function start() {
if(in_file === undefined) {
alert("Error: No file was specified. Select a file before drawing.");
return;
}
applySettings();
// check if it even needs complete re-plotting or just redrawing
if (previous_config.in_file === in_file
&& previous_config.chunk_size === chunk_size
&& previous_config.point_size === point_size
&& previous_config.point_offset === point_offset)
{
console.log("Did nothing since no parameter changed.");
}
else if(document.querySelector('#plot.js-plotly-plot') !== null // = got plotted before
&& previous_config.chunk_size === chunk_size
&& previous_config.in_file === in_file
&& previous_config.point_offset === point_offset
&& previous_config.point_size !== point_size)
{
Plotly.restyle('plot', { 'marker.size': point_size });
previous_config.point_size = point_size;
// only scroll on mobile since then it's hard to understand that the plot changed
if (/Mobi/.test(navigator.userAgent)) {
document.getElementById('progress-text').scrollIntoView(true);
}
console.log("Reused previous plot with new parameters.");
} else {
$('#plot').addClass('fullscreen');
document.getElementById('progress-text').scrollIntoView(true);
$('#unplotted-text').addClass('d-none');
plotFASTAfile(in_file);
}
}
document.getElementById('btn-start').addEventListener('click', start);
/**
* Returns an array holding the sequential data.
* Ignores lines that start with `>` (comments)
*
* @param {string} data
*/
function parseFASTAformat(data) {
const fasta = [];
const lines = data.toUpperCase().split('\n');
for (let i = 0; i < lines.length; i++) {
// ignore comment lines
if(lines[i][0] !== '>') {
for(let j = 0; j < lines[i].length; j++) {
fasta.push(lines[i][j]);
}
}
}
return fasta;
}
/**
*
* @param {File} file
*/
async function plotFASTAfile(file) {
// Delete the old plot if it exists,
// because otherwise Plotly.react won't update the plot.
Plotly.purge('plot');
const progress = $('#progress-text>span');
progress.removeClass('text-success text-danger').addClass('text-info');
let chunk_size_mb = 1000000*chunk_size;
let chunk_index = 1;
let total_chunks = Math.ceil((file.size/chunk_size_mb), chunk_size_mb);
console.log("There will be", total_chunks, "chunk/s.")
const colors = [[]];
let last_color = x_col;
const scatter_x = [], scatter_y = [];
const cursor = { x: 0, y: 0 };
const file_reader = new FileReader();
let offset = 0;
let last_point = 0;
let datarevision = 0;
while (chunk_index <= total_chunks) {
offset = (chunk_index - 1) * chunk_size_mb;
let blob = file.slice(offset, (offset + chunk_size_mb));
const data = await new Promise((resolve, reject) => {
file_reader.onloadend = (event) => {
const target = (event.target);
if (target.error === null) {
offset += target.result.length;
resolve(target.result);
}
else {
reject(target.error);
}
};
file_reader.readAsText(blob);
});
const fasta_data = parseFASTAformat(data);
for (let i = 0; i < fasta_data.length; i++) {
switch ( fasta_data[i] ) {
case 'A':
moveCursor(a_dir, cursor);
if(is_color_enabled) {last_color = a_col;}
break;
case 'T':
moveCursor(t_dir, cursor);
if(is_color_enabled) {last_color = t_col;}
break;
case 'G':
moveCursor(g_dir, cursor);
if(is_color_enabled) {last_color = g_col;}
break;
case 'C':
moveCursor(c_dir, cursor);
if(is_color_enabled) {last_color = c_col;}
break;
default:
moveCursor(x_dir, cursor);
if(is_color_enabled) {last_color = x_col;}
break;
}
if(last_point % point_offset === 0) {
if(is_color_enabled) {
colors[0].push(last_color);
}
scatter_x.push(cursor.x);
scatter_y.push(cursor.y);
}
last_point++;
}
const plotly_data = [
{
type: "scattergl",
mode: "markers",
marker: {
size: point_size,
color: 'rgb(0, 0, 0)',
// line: {
// width: 1,
// color: 'rgb(0,0,0)'}
},
x: scatter_x,
y: scatter_y
}
];
datarevision += 1;
const plotly_layout = {
datarevision: datarevision
}
Plotly.react('plot', plotly_data, plotly_layout);
let percentage = ((offset/file.size)*100).toFixed(1) + '%';
progress.html(percentage);
document.getElementById('progress-bar').style.width = percentage;
chunk_index++;
}
if(is_color_enabled) {
Plotly.restyle('plot', 'marker.color', colors);
}
progress.removeClass('text-info').addClass('text-success').html('100%');
const plot = document.getElementById('plot');
console.log('----------------------------\nDone plotting. Report:');
console.log('- The plot holds: (', plot.data[0].x.length, ',', plot.data[0].y.length, ') points.');
console.log('- The color holds: (', colors[0].length, ') points.');
console.log('- Offset:', point_offset,
',\n- Chunk size:', chunk_size_mb,
',\n- Chunks:', chunk_index - 1,
',\n- Total calculated points:', last_point);
}
$('#file').change(() => {
if(previous_config.in_file !== undefined) {
previous_config.in_file = in_file;
} else {
previous_config.in_file = document.getElementById('file').files[0];
}
in_file = document.getElementById('file').files[0];
if(in_file === undefined) {
$('#label-file>b').text('Open FASTA File');
$('#label-file').tooltip('dispose');
} else {
$('#label-file>b').text(in_file.name.substr(0, 10) + '...');
$('#label-file').attr('data-original-title', in_file.name).tooltip('show');
}
});
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
|
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2018 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(["jquery.sap.global","sap/ui/base/Object","sap/ui/test/matchers/Interactable","sap/ui/test/matchers/Visible"],function($,U,I,V){"use strict";var M={getInteractabilityMatchers:function(i){return[i?new I():new V()];},getFilteringMatchers:function(o){var m=_(o);if(o.matchers){if($.isPlainObject(o.matchers)){m=m.concat(_(o.matchers));}else if($.isArray(o.matchers)){o.matchers.forEach(function(v){if($.isPlainObject(v)){m=m.concat(_(v));}else{m.push(v);}});}else{m=m.concat(o.matchers);}}return m;}};function _(m){if(m["isMatching"]){return[m];}var s=["aggregationContainsPropertyEqual","aggregationEmpty","aggregationFilled","aggregationLengthEquals","ancestor","bindingPath","I18NText","labelFor","properties","propertyStrictEquals"];return Object.keys(m).filter(function(a){return s.indexOf(a)>-1;}).map(function(a){var b=$.sap.charToUpperCase(a);sap.ui.require(["sap/ui/test/matchers/"+b]);var c=sap.ui.test.matchers[b];var d=$.isArray(m[a])?m[a]:[m[a]];return d.map(function(o){if($.isArray(o)){return new function(){return c.apply(this,o);}();}else{return new c(o);}});}).reduce(function(r,a){return r.concat(a);},[]);}return U.extend("sap.ui.test.matchers.MatcherFactory",M);});
|
import React from 'react'
import { isFileViewed } from './lib'
import File from './components/file'
import Folder from './components/folder'
export const createTree = ({ nodeLabel, list, href, hasComments, isDeleted, diffElement, diffStats, visibleElement, filter, hideViewed, hideFilesWithoutComments }) => {
if (href) {
const isVisible = (diffElement === visibleElement)
const isViewed = isFileViewed(diffElement)
const shouldHide = (isViewed && hideViewed) || (!hasComments && hideFilesWithoutComments)
return (
<File
key={href}
name={nodeLabel}
href={href}
hasComments={hasComments}
isDeleted={isDeleted}
isVisible={isVisible}
diffStats={diffStats}
isViewed={isViewed}
filter={filter}
hidden={shouldHide}
/>
)
}
const rawChildren = list.map(node => createTree({ ...node, visibleElement, filter, hideViewed, hideFilesWithoutComments }))
const numberOfDirectChildren = rawChildren.filter(c => c.props.href && !c.props.hidden).length
const numberOfChildrenOfChildFolders = rawChildren.filter(c => !!c.props.fileCount).map(c => c.props.fileCount).reduce((partialSum, a) => partialSum + a, 0)
const fileCount = numberOfDirectChildren + numberOfChildrenOfChildFolders
const childrenAreViewed = rawChildren.every(child => child.props.isViewed)
const shouldHide = rawChildren.every(child => child.props.hidden)
return (
<Folder
key={nodeLabel}
nodeLabel={nodeLabel}
fileCount={fileCount}
isViewed={childrenAreViewed}
hidden={shouldHide}
filter={filter}
>
{rawChildren.map(node => (
<span key={node.key}>
{node}
</span>
))}
</Folder>
)
}
|
import React, { useState, useContext, useMemo } from 'react';
import { useEffect } from 'react';
import DRIVERS_DATA from './data';
import { getTransformedData } from './utils';
const initialStateContext = {
drivers: {},
rankingByRace: {},
globalRanking: {},
isTVMode: false
};
const Context = React.createContext(initialStateContext);
function DataProvider({ children }) {
const [data, setData] = useState(initialStateContext);
const [isTVMode, setIsTVMode] = useState(false);
const transformedData = useMemo(() => getTransformedData(DRIVERS_DATA), []);
useEffect(() => setTimeout(() => setData(transformedData), 1000), [transformedData]);
return <Context.Provider value={{ ...data, isTVMode, setIsTVMode }}>{children}</Context.Provider>;
}
function useData() {
const context = useContext(Context);
if (context === undefined) {
throw new Error('useData must be used within a DataContextProvider');
}
return context;
}
export { DataProvider, useData };
|
/**
*
*/
define(['jquery', 'kissy'], function($, S){
return {
width: 500,
height: 400,
height: 400,
title: '弹出层',
url: 'content.php',
param: 'a=1&b=2',
onHide: function(){
},
onCreate: function(){
}
};
});
|
// Copyright 2021 Google LLC
//
// 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.
'use strict';
function main(product, type, placeIds) {
// [START retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
/**
* Required. Full resource name of
* [Product][google.cloud.retail.v2beta.Product], such as
* `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`.
* If the caller does not have permission to access the
* [Product][google.cloud.retail.v2beta.Product], regardless of whether or not
* it exists, a PERMISSION_DENIED error is returned.
*/
// const product = 'abc123'
/**
* Required. The fulfillment type, including commonly used types (such as
* pickup in store and same day delivery), and custom types.
* Supported values:
* * "pickup-in-store"
* * "ship-to-store"
* * "same-day-delivery"
* * "next-day-delivery"
* * "custom-type-1"
* * "custom-type-2"
* * "custom-type-3"
* * "custom-type-4"
* * "custom-type-5"
* If this field is set to an invalid value other than these, an
* INVALID_ARGUMENT error is returned.
* This field directly corresponds to [Product.fulfillment_info.type][].
*/
// const type = 'abc123'
/**
* Required. The IDs for this
* [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type], such
* as the store IDs for "pickup-in-store" or the region IDs for
* "same-day-delivery" to be added for this
* [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type].
* Duplicate IDs will be automatically ignored.
* At least 1 value is required, and a maximum of 2000 values are allowed.
* Each value must be a string with a length limit of 10 characters, matching
* the pattern `[a-zA-Z0-9_-]+`, such as "store1" or "REGION-2". Otherwise, an
* INVALID_ARGUMENT error is returned.
* If the total number of place IDs exceeds 2000 for this
* [type][google.cloud.retail.v2beta.AddFulfillmentPlacesRequest.type] after
* adding, then the update will be rejected.
*/
// const placeIds = 'abc123'
/**
* The time when the fulfillment updates are issued, used to prevent
* out-of-order updates on fulfillment information. If not provided, the
* internal system time will be used.
*/
// const addTime = ''
/**
* If set to true, and the [Product][google.cloud.retail.v2beta.Product] is
* not found, the fulfillment information will still be processed and retained
* for at most 1 day and processed once the
* [Product][google.cloud.retail.v2beta.Product] is created. If set to false,
* a NOT_FOUND error is returned if the
* [Product][google.cloud.retail.v2beta.Product] is not found.
*/
// const allowMissing = true
// Imports the Retail library
const {ProductServiceClient} = require('@google-cloud/retail').v2beta;
// Instantiates a client
const retailClient = new ProductServiceClient();
async function addFulfillmentPlaces() {
// Construct request
const request = {
product,
type,
placeIds,
};
// Run request
const [operation] = await retailClient.addFulfillmentPlaces(request);
const [response] = await operation.promise();
console.log(response);
}
addFulfillmentPlaces();
// [END retail_v2beta_generated_ProductService_AddFulfillmentPlaces_async]
}
process.on('unhandledRejection', err => {
console.error(err.message);
process.exitCode = 1;
});
main(...process.argv.slice(2));
|
global.firstNames = ['Abigail',
'Alexandra',
'Alison',
'Amanda',
'Amelia',
'Amy',
'Andrea',
'Angela',
'Anna',
'Anne',
'Audrey',
'Ava',
'Bella',
'Bernadette',
'Carol',
'Caroline',
'Carolyn',
'Chloe',
'Claire',
'Deirdre',
'Diana',
'Diane',
'Donna',
'Dorothy',
'Elizabeth',
'Ella',
'Emily',
'Emma',
'Faith',
'Felicity',
'Fiona',
'Gabrielle',
'Grace',
'Hannah',
'Heather',
'Irene',
'Jan',
'Jane',
'Jasmine',
'Jennifer',
'Jessica',
'Joan',
'Joanne',
'Julia',
'Karen',
'Katherine',
'Kimberly',
'Kylie',
'Lauren',
'Leah',
'Lillian',
'Lily',
'Lisa',
'Madeleine',
'Maria',
'Megan',
'Melanie',
'Michelle',
'Molly',
'Natalie',
'Nicola',
'Olivia',
'Penelope',
'Pippa',
'Rachel',
'Rebecca',
'Rose',
'Ruth',
'Sally',
'Samantha',
'Sarah',
'Sonia',
'Sophie',
'Stephanie',
'Sue',
'Theresa',
'Tracey',
'Una',
'Vanessa',
'Victoria',
'Virginia',
'Wanda',
'Wendy',
'Yvonne',
'Zoe',
'Adam',
'Adrian',
'Alan',
'Alexander',
'Andrew',
'Anthony',
'Austin',
'Benjamin',
'Blake',
'Boris',
'Brandon',
'Brian',
'Cameron',
'Carl',
'Charles',
'Christian',
'Christopher',
'Colin',
'Connor',
'Dan',
'David',
'Dominic',
'Dylan',
'Edward',
'Eric',
'Evan',
'Frank',
'Gavin',
'Gordon',
'Harry',
'Ian',
'Isaac',
'Jack',
'Jacob',
'Jake',
'James',
'Jason',
'Joe',
'John',
'Jonathan',
'Joseph',
'Joshua',
'Julian',
'Justin',
'Keith',
'Kevin',
'Leonard',
'Liam',
'Lucas',
'Luke',
'Matt',
'Max',
'Michael',
'Nathan',
'Neil',
'Nicholas',
'Oliver',
'Owen',
'Paul',
'Peter',
'Phil',
'Piers',
'Richard',
'Robert',
'Ryan',
'Sam',
'Sean',
'Sebastian',
'Simon',
'Stephen',
'Steven',
'Stewart',
'Thomas',
'Tim',
'Trevor',
'Victor',
'Warren',
'William'
];
global.lastNames = [
'Abraham',
'Allan',
'Alsop',
'Anderson',
'Arnold',
'Avery',
'Bailey',
'Baker',
'Ball',
'Bell',
'Berry',
'Black',
'Blake',
'Bond',
'Bower',
'Brown',
'Buckland',
'Burgess',
'Butler',
'Cameron',
'Campbell',
'Carr',
'Chapman',
'Churchill',
'Clark',
'Clarkson',
'Coleman',
'Cornish',
'Davidson',
'Davies',
'Dickens',
'Dowd',
'Duncan',
'Dyer',
'Edmunds',
'Ellison',
'Ferguson',
'Fisher',
'Forsyth',
'Fraser',
'Gibson',
'Gill',
'Glover',
'Graham',
'Grant',
'Gray',
'Greene',
'Hamilton',
'Hardacre',
'Harris',
'Hart',
'Hemmings',
'Henderson',
'Hill',
'Hodges',
'Howard',
'Hudson',
'Hughes',
'Hunter',
'Ince',
'Jackson',
'James',
'Johnston',
'Jones',
'Kelly',
'Kerr',
'King',
'Knox',
'Lambert',
'Langdon',
'Lawrence',
'Lee',
'Lewis',
'Lyman',
'MacDonald',
'Mackay',
'Mackenzie',
'MacLeod',
'Manning',
'Marshall',
'Martin',
'Mathis',
'May',
'McDonald',
'McLean',
'McGrath',
'Metcalfe',
'Miller',
'Mills',
'Mitchell',
'Morgan',
'Morrison',
'Murray',
'Nash',
'Newman',
'Nolan',
'North',
'Ogden',
'Oliver',
'Paige',
'Parr',
'Parsons',
'Paterson',
'Payne',
'Peake',
'Peters',
'Piper',
'Poole',
'Powell',
'Pullman',
'Quinn',
'Rampling',
'Randall',
'Rees',
'Reid',
'Roberts',
'Robertson',
'Ross',
'Russell',
'Rutherford',
'Sanderson',
'Scott',
'Sharp',
'Short',
'Simpson',
'Skinner',
'Slater',
'Smith',
'Springer',
'Stewart',
'Sutherland',
'Taylor',
'Terry',
'Thomson',
'Tucker',
'Turner',
'Underwood',
'Vance',
'Vaughan',
'Walker',
'Wallace',
'Walsh',
'Watson',
'Welch',
'White',
'Wilkins',
'Wilson',
'Wright',
'Young'];
global.cities = ['Wentz',
'Castle Manor',
'Uneedus',
'Birdsboro',
'Fernell Heights',
'Smithfield',
'Smithtown',
'Ziegler Estates',
'Security',
'Harmony Corner',
'Hepners',
'Shirley Grove',
'Richville',
'Wyatt',
'Normal Heights',
'Freeport',
'Terminal Junction',
'East Springbrook',
'Linden',
'Lower Askam',
'Losoya',
'Knights Hill',
'Backoo',
'Toulon',
'Carancahua',
'Luzerne',
'Chickahominy Haven',
'Gnat Hill',
'Gum Tree',
'Deport',
'Foster',
'Kyles',
'Fopal',
'Wharton Furnace',
'Milford',
'Plymouth',
'Eastport',
'Fernandez Village',
'Pullman',
'Greenville',
'West Shoreham',
'Blair Portal',
'Enders',
'Turkey Fork',
'Summit',
'Ledford',
'Weiland',
'Caldwell',
'Red Oak',
'Oakdale']
global.states = ['CT','MA','NJ','TX','VA','IL','IA','NH','NY','VT','CA','UT'];
global.zipCodes = [
33060,
43015,
11418,
43068,
48124,
92307,
06360,
60435,
60466,
13027,
48237,
26554,
11201,
27320,
06066,
06340,
75604,
37122,
20705,
43560,
32566,
36109,
10562,
53402,
49417,
18042,
48167,
60025,
14606,
07065,
08037,
55378,
49015,
20745,
30180,
30741,
19050,
33801,
26101,
11706,
55912];
global.genders = ['M','F'];
global.occupations = ['welder','software engineer','carpenter','engineer','physician','neurosurgeon','laborer','plumber','technician','pilot','nurse','professor','manager'];
|
/*
Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'table', 'sq', {
border: 'Madhësia e kornizave',
caption: 'Titull',
cell: {
menu: 'Qeli',
insertBefore: 'Shto Qeli Para',
insertAfter: 'Shto Qeli Prapa',
deleteCell: 'Gris Qelitë',
merge: 'Bashko Qelitë',
mergeRight: 'Bashko Djathtas',
mergeDown: 'Bashko Poshtë',
splitHorizontal: 'Ndaj Qelinë Horizontalisht',
splitVertical: 'Ndaj Qelinë Vertikalisht',
title: 'Rekuizitat e Qelisë',
cellType: 'Lloji i Qelisë',
rowSpan: 'Bashko Rreshtat',
colSpan: 'Bashko Kolonat',
wordWrap: 'Fund i Fjalës',
hAlign: 'Bashkimi Horizontal',
vAlign: 'Bashkimi Vertikal',
alignBaseline: 'Baza',
bgColor: 'Ngjyra e Prapavijës',
borderColor: 'Ngjyra e Kornizave',
data: 'Të dhënat',
header: 'Koka',
yes: 'Po',
no: 'Jo',
invalidWidth: 'Gjerësia e qelisë duhet të jetë numër.',
invalidHeight: 'Lartësia e qelisë duhet të jetë numër.',
invalidRowSpan: 'Hapësira e rreshtave duhet të jetë numër i plotë.',
invalidColSpan: 'Hapësira e kolonave duhet të jetë numër i plotë.',
chooseColor: 'Përzgjidh'
},
cellPad: 'Mbushja e qelisë',
cellSpace: 'Hapësira e qelisë',
column: {
menu: 'Kolona',
insertBefore: 'Vendos Kolonë Para',
insertAfter: 'Vendos Kolonë Pas',
deleteColumn: 'Gris Kolonat'
},
columns: 'Kolonat',
deleteTable: 'Gris Tabelën',
headers: 'Kokat',
headersBoth: 'Së bashku',
headersColumn: 'Kolona e parë',
headersNone: 'Asnjë',
headersRow: 'Rreshti i Parë',
heightUnit: 'height unit', // MISSING
invalidBorder: 'Madhësia e kufinjve duhet të jetë numër.',
invalidCellPadding: 'Mbushja e qelisë duhet të jetë numër pozitiv.',
invalidCellSpacing: 'Hapësira e qelisë duhet të jetë numër pozitiv.',
invalidCols: 'Numri i kolonave duhet të jetë numër më i madh se 0.',
invalidHeight: 'Lartësia e tabelës duhet të jetë numër.',
invalidRows: 'Numri i rreshtave duhet të jetë numër më i madh se 0.',
invalidWidth: 'Gjerësia e tabelës duhet të jetë numër.',
menu: 'Karakteristikat e Tabelës',
row: {
menu: 'Rreshti',
insertBefore: 'Shto Rresht Para',
insertAfter: 'Shto Rresht Prapa',
deleteRow: 'Gris Rreshtat'
},
rows: 'Rreshtat',
summary: 'Përmbledhje',
title: 'Karakteristikat e Tabelës',
toolbar: 'Tabela',
widthPc: 'përqind',
widthPx: 'piksell',
widthUnit: 'njësia e gjerësisë'
} );
|
import { EMPTY_BYTES32, BIGINT_ZERO } from '../constants'
import { get } from 'svelte/store'
import { user } from '../../stores/main'
import { getAddress, encodeMethodSignature, encodeBytes32, encodeAddress, encodeUint } from '../utils'
import ethSend from '../ethSend'
export default async function withdraw(params) {
let {
amount
} = params;
return ethSend({
address: getAddress('TRADING'),
method: 'withdraw(uint256)',
data: encodeUint(amount)
});
}
|
import React, { PureComponent, Fragment } from 'react';
import PageHeaderWrapper from '../../components/PageHeaderWrapper';
import DatasetDetailsComponent from './Details/DatasetDetailsComponent';
export default class DatasetDetail extends React.PureComponent {
render() {
const datasetId = this.props.match.params.id;
return (
<PageHeaderWrapper
breadcrumbList={[
{
title: '首页',
href: '/',
},
{
title: '数据集列表',
href: '/storage/dataset',
},
{
title: '数据集查看',
},
]}
>
<DatasetDetailsComponent datasetId={datasetId} />
</PageHeaderWrapper>
);
}
}
|
(function() {
var World = Matter.World,
Bodies = Matter.Bodies,
Composites = Matter.Composites,
Common = Matter.Common;
Example.mixedSolid = function(demo) {
var engine = demo.engine,
world = engine.world;
var stack = Composites.stack(50, 50, 12, 3, 0, 0, function(x, y) {
switch (Math.round(Common.random(0, 1))) {
case 0:
if (Common.random() < 0.8) {
return Bodies.rectangle(x, y, Common.random(20, 50), Common.random(20, 50));
} else {
return Bodies.rectangle(x, y, Common.random(80, 120), Common.random(20, 30));
}
break;
case 1:
return Bodies.polygon(x, y, Math.round(Common.random(1, 8)), Common.random(20, 50));
}
});
World.add(world, stack);
var renderOptions = demo.render.options;
renderOptions.wireframes = false;
renderOptions.showAngleIndicator = false;
};
})();
|
import React from 'react'
import PropTypes from 'prop-types';
import { text } from '../../lib/settings'
import CustomProductList from './custom'
const Fragment = React.Fragment;
export default class DealProducts extends React.Component {
static propTypes = {
limit: PropTypes.number.isRequired,
settings: PropTypes.shape({}).isRequired,
addCartItem: PropTypes.func.isRequired
//product: PropTypes.shape({}).isRequired
};
render() {
const { limit, settings, addCartItem, hideDeal, userInfo } = this.props;
return (
<section className="section section-product-related section-gray" style={{paddingTop: '0px'}}>
<div className="container border-section">
<div className="title-section is-4 has-text-centered">{text.currentDeal}</div>
<CustomProductList
on_sale={true}
settings={settings}
addCartItem={addCartItem}
hideDeal={hideDeal}
limit={limit}
isCentered
userInfo={userInfo}
/>
</div>
</section>
)
}
}
|
var path = require('path');
var webpack = require('webpack');
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
'examples': resolve('examples')
}
},
module: {
loaders: [
{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('examples'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter')
}
},
{
test: /\.vue$/,
loader: 'vue-loader',
include: [resolve('src'), resolve('examples'), resolve('test')],
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('examples'), resolve('test')],
},
{
test: /\.css|.less$/,
loader: 'style-loader!css-loader!postcss-loader!less-loader',
include: [resolve('src'), resolve('examples'), resolve('examples')],
}
]
}
};
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 5);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 g;
// This works in non-strict mode
g = function () {
return this;
}();
try {
// This works if eval is allowed (see CSP)
g = g || Function("return this")() || (1, eval)("this");
} catch (e) {
// This works if the window reference is available
if ((typeof window === "undefined" ? "undefined" : _typeof(window)) === "object")
g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_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;}; /*!
* JavaScript Cookie v2.2.0
* https://github.com/js-cookie/js-cookie
*
* Copyright 2006, 2015 Klaus Hartl & Fagner Brack
* Released under the MIT license
*/
;(function (factory) {
var registeredInModuleLoader = false;
if (true) {
!(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
__WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
registeredInModuleLoader = true;
}
if (( false ? 'undefined' : _typeof(exports)) === 'object') {
module.exports = factory();
registeredInModuleLoader = true;
}
if (!registeredInModuleLoader) {
var OldCookies = window.Cookies;
var api = window.Cookies = factory();
api.noConflict = function () {
window.Cookies = OldCookies;
return api;
};
}
})(function () {
function extend() {
var i = 0;
var result = {};
for (; i < arguments.length; i++) {
var attributes = arguments[i];
for (var key in attributes) {
result[key] = attributes[key];
}
}
return result;
}
function init(converter) {
function api(key, value, attributes) {
var result;
if (typeof document === 'undefined') {
return;
}
// Write
if (arguments.length > 1) {
attributes = extend({
path: '/' },
api.defaults, attributes);
if (typeof attributes.expires === 'number') {
var expires = new Date();
expires.setMilliseconds(expires.getMilliseconds() + attributes.expires * 864e+5);
attributes.expires = expires;
}
// We're using "expires" because "max-age" is not supported by IE
attributes.expires = attributes.expires ? attributes.expires.toUTCString() : '';
try {
result = JSON.stringify(value);
if (/^[\{\[]/.test(result)) {
value = result;
}
} catch (e) {}
if (!converter.write) {
value = encodeURIComponent(String(value)).
replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
} else {
value = converter.write(value, key);
}
key = encodeURIComponent(String(key));
key = key.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent);
key = key.replace(/[\(\)]/g, escape);
var stringifiedAttributes = '';
for (var attributeName in attributes) {
if (!attributes[attributeName]) {
continue;
}
stringifiedAttributes += '; ' + attributeName;
if (attributes[attributeName] === true) {
continue;
}
stringifiedAttributes += '=' + attributes[attributeName];
}
return document.cookie = key + '=' + value + stringifiedAttributes;
}
// Read
if (!key) {
result = {};
}
// To prevent the for loop in the first place assign an empty array
// in case there are no cookies at all. Also prevents odd result when
// calling "get()"
var cookies = document.cookie ? document.cookie.split('; ') : [];
var rdecode = /(%[0-9A-Z]{2})+/g;
var i = 0;
for (; i < cookies.length; i++) {
var parts = cookies[i].split('=');
var cookie = parts.slice(1).join('=');
if (!this.json && cookie.charAt(0) === '"') {
cookie = cookie.slice(1, -1);
}
try {
var name = parts[0].replace(rdecode, decodeURIComponent);
cookie = converter.read ?
converter.read(cookie, name) : converter(cookie, name) ||
cookie.replace(rdecode, decodeURIComponent);
if (this.json) {
try {
cookie = JSON.parse(cookie);
} catch (e) {}
}
if (key === name) {
result = cookie;
break;
}
if (!key) {
result[name] = cookie;
}
} catch (e) {}
}
return result;
}
api.set = api;
api.get = function (key) {
return api.call(api, key);
};
api.getJSON = function () {
return api.apply({
json: true },
[].slice.call(arguments));
};
api.defaults = {};
api.remove = function (key, attributes) {
api(key, '', extend(attributes, {
expires: -1 }));
};
api.withConverter = init;
return api;
}
return init(function () {});
});
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_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;}; /*!
* ScrollMagic v2.0.5 (2015-04-29)
* The javascript library for magical scroll interactions.
* (c) 2015 Jan Paepke (@janpaepke)
* Project Website: http://scrollmagic.io
*
* @version 2.0.5
* @license Dual licensed under MIT license and GPL.
* @author Jan Paepke - e-mail@janpaepke.de
*
* @file ScrollMagic main library.
*/
/**
* @namespace ScrollMagic
*/
(function (root, factory) {
if (true) {
// AMD. Register as an anonymous module.
!(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
__WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ((typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) === 'object') {
// CommonJS
module.exports = factory();
} else {
// Browser global
root.ScrollMagic = factory();
}
})(undefined, function () {
"use strict";
var ScrollMagic = function ScrollMagic() {
_util.log(2, '(COMPATIBILITY NOTICE) -> As of ScrollMagic 2.0.0 you need to use \'new ScrollMagic.Controller()\' to create a new controller instance. Use \'new ScrollMagic.Scene()\' to instance a scene.');
};
ScrollMagic.version = "2.0.5";
// TODO: temporary workaround for chrome's scroll jitter bug
window.addEventListener("mousewheel", function () {});
// global const
var PIN_SPACER_ATTRIBUTE = "data-scrollmagic-pin-spacer";
/**
* The main class that is needed once per scroll container.
*
* @class
*
* @example
* // basic initialization
* var controller = new ScrollMagic.Controller();
*
* // passing options
* var controller = new ScrollMagic.Controller({container: "#myContainer", loglevel: 3});
*
* @param {object} [options] - An object containing one or more options for the controller.
* @param {(string|object)} [options.container=window] - A selector, DOM object that references the main container for scrolling.
* @param {boolean} [options.vertical=true] - Sets the scroll mode to vertical (`true`) or horizontal (`false`) scrolling.
* @param {object} [options.globalSceneOptions={}] - These options will be passed to every Scene that is added to the controller using the addScene method. For more information on Scene options see {@link ScrollMagic.Scene}.
* @param {number} [options.loglevel=2] Loglevel for debugging. Note that logging is disabled in the minified version of ScrollMagic.
** `0` => silent
** `1` => errors
** `2` => errors, warnings
** `3` => errors, warnings, debuginfo
* @param {boolean} [options.refreshInterval=100] - Some changes don't call events by default, like changing the container size or moving a scene trigger element.
This interval polls these parameters to fire the necessary events.
If you don't use custom containers, trigger elements or have static layouts, where the positions of the trigger elements don't change, you can set this to 0 disable interval checking and improve performance.
*
*/
ScrollMagic.Controller = function (options) {
/*
* ----------------------------------------------------------------
* settings
* ----------------------------------------------------------------
*/
var
NAMESPACE = 'ScrollMagic.Controller',
SCROLL_DIRECTION_FORWARD = 'FORWARD',
SCROLL_DIRECTION_REVERSE = 'REVERSE',
SCROLL_DIRECTION_PAUSED = 'PAUSED',
DEFAULT_OPTIONS = CONTROLLER_OPTIONS.defaults;
/*
* ----------------------------------------------------------------
* private vars
* ----------------------------------------------------------------
*/
var
Controller = this,
_options = _util.extend({}, DEFAULT_OPTIONS, options),
_sceneObjects = [],
_updateScenesOnNextCycle = false,
// can be boolean (true => all scenes) or an array of scenes to be updated
_scrollPos = 0,
_scrollDirection = SCROLL_DIRECTION_PAUSED,
_isDocument = true,
_viewPortSize = 0,
_enabled = true,
_updateTimeout,_refreshTimeout;
/*
* ----------------------------------------------------------------
* private functions
* ----------------------------------------------------------------
*/
/**
* Internal constructor function of the ScrollMagic Controller
* @private
*/
var construct = function construct() {
for (var key in _options) {
if (!DEFAULT_OPTIONS.hasOwnProperty(key)) {
log(2, "WARNING: Unknown option \"" + key + "\"");
delete _options[key];
}
}
_options.container = _util.get.elements(_options.container)[0];
// check ScrollContainer
if (!_options.container) {
log(1, "ERROR creating object " + NAMESPACE + ": No valid scroll container supplied");
throw NAMESPACE + " init failed."; // cancel
}
_isDocument = _options.container === window || _options.container === document.body || !document.body.contains(_options.container);
// normalize to window
if (_isDocument) {
_options.container = window;
}
// update container size immediately
_viewPortSize = getViewportSize();
// set event handlers
_options.container.addEventListener("resize", onChange);
_options.container.addEventListener("scroll", onChange);
_options.refreshInterval = parseInt(_options.refreshInterval) || DEFAULT_OPTIONS.refreshInterval;
scheduleRefresh();
log(3, "added new " + NAMESPACE + " controller (v" + ScrollMagic.version + ")");
};
/**
* Schedule the next execution of the refresh function
* @private
*/
var scheduleRefresh = function scheduleRefresh() {
if (_options.refreshInterval > 0) {
_refreshTimeout = window.setTimeout(refresh, _options.refreshInterval);
}
};
/**
* Default function to get scroll pos - overwriteable using `Controller.scrollPos(newFunction)`
* @private
*/
var getScrollPos = function getScrollPos() {
return _options.vertical ? _util.get.scrollTop(_options.container) : _util.get.scrollLeft(_options.container);
};
/**
* Returns the current viewport Size (width vor horizontal, height for vertical)
* @private
*/
var getViewportSize = function getViewportSize() {
return _options.vertical ? _util.get.height(_options.container) : _util.get.width(_options.container);
};
/**
* Default function to set scroll pos - overwriteable using `Controller.scrollTo(newFunction)`
* Make available publicly for pinned mousewheel workaround.
* @private
*/
var setScrollPos = this._setScrollPos = function (pos) {
if (_options.vertical) {
if (_isDocument) {
window.scrollTo(_util.get.scrollLeft(), pos);
} else {
_options.container.scrollTop = pos;
}
} else {
if (_isDocument) {
window.scrollTo(pos, _util.get.scrollTop());
} else {
_options.container.scrollLeft = pos;
}
}
};
/**
* Handle updates in cycles instead of on scroll (performance)
* @private
*/
var updateScenes = function updateScenes() {
if (_enabled && _updateScenesOnNextCycle) {
// determine scenes to update
var scenesToUpdate = _util.type.Array(_updateScenesOnNextCycle) ? _updateScenesOnNextCycle : _sceneObjects.slice(0);
// reset scenes
_updateScenesOnNextCycle = false;
var oldScrollPos = _scrollPos;
// update scroll pos now instead of onChange, as it might have changed since scheduling (i.e. in-browser smooth scroll)
_scrollPos = Controller.scrollPos();
var deltaScroll = _scrollPos - oldScrollPos;
if (deltaScroll !== 0) {// scroll position changed?
_scrollDirection = deltaScroll > 0 ? SCROLL_DIRECTION_FORWARD : SCROLL_DIRECTION_REVERSE;
}
// reverse order of scenes if scrolling reverse
if (_scrollDirection === SCROLL_DIRECTION_REVERSE) {
scenesToUpdate.reverse();
}
// update scenes
scenesToUpdate.forEach(function (scene, index) {
log(3, "updating Scene " + (index + 1) + "/" + scenesToUpdate.length + " (" + _sceneObjects.length + " total)");
scene.update(true);
});
if (scenesToUpdate.length === 0 && _options.loglevel >= 3) {
log(3, "updating 0 Scenes (nothing added to controller)");
}
}
};
/**
* Initializes rAF callback
* @private
*/
var debounceUpdate = function debounceUpdate() {
_updateTimeout = _util.rAF(updateScenes);
};
/**
* Handles Container changes
* @private
*/
var onChange = function onChange(e) {
log(3, "event fired causing an update:", e.type);
if (e.type == "resize") {
// resize
_viewPortSize = getViewportSize();
_scrollDirection = SCROLL_DIRECTION_PAUSED;
}
// schedule update
if (_updateScenesOnNextCycle !== true) {
_updateScenesOnNextCycle = true;
debounceUpdate();
}
};
var refresh = function refresh() {
if (!_isDocument) {
// simulate resize event. Only works for viewport relevant param (performance)
if (_viewPortSize != getViewportSize()) {
var resizeEvent;
try {
resizeEvent = new Event('resize', {
bubbles: false,
cancelable: false });
} catch (e) {// stupid IE
resizeEvent = document.createEvent("Event");
resizeEvent.initEvent("resize", false, false);
}
_options.container.dispatchEvent(resizeEvent);
}
}
_sceneObjects.forEach(function (scene, index) {// refresh all scenes
scene.refresh();
});
scheduleRefresh();
};
/**
* Send a debug message to the console.
* provided publicly with _log for plugins
* @private
*
* @param {number} loglevel - The loglevel required to initiate output for the message.
* @param {...mixed} output - One or more variables that should be passed to the console.
*/
var log = this._log = function (loglevel, output) {
if (_options.loglevel >= loglevel) {
Array.prototype.splice.call(arguments, 1, 0, "(" + NAMESPACE + ") ->");
_util.log.apply(window, arguments);
}
};
// for scenes we have getters for each option, but for the controller we don't, so we need to make it available externally for plugins
this._options = _options;
/**
* Sort scenes in ascending order of their start offset.
* @private
*
* @param {array} ScenesArray - an array of ScrollMagic Scenes that should be sorted
* @return {array} The sorted array of Scenes.
*/
var sortScenes = function sortScenes(ScenesArray) {
if (ScenesArray.length <= 1) {
return ScenesArray;
} else {
var scenes = ScenesArray.slice(0);
scenes.sort(function (a, b) {
return a.scrollOffset() > b.scrollOffset() ? 1 : -1;
});
return scenes;
}
};
/**
* ----------------------------------------------------------------
* public functions
* ----------------------------------------------------------------
*/
/**
* Add one ore more scene(s) to the controller.
* This is the equivalent to `Scene.addTo(controller)`.
* @public
* @example
* // with a previously defined scene
* controller.addScene(scene);
*
* // with a newly created scene.
* controller.addScene(new ScrollMagic.Scene({duration : 0}));
*
* // adding multiple scenes
* controller.addScene([scene, scene2, new ScrollMagic.Scene({duration : 0})]);
*
* @param {(ScrollMagic.Scene|array)} newScene - ScrollMagic Scene or Array of Scenes to be added to the controller.
* @return {Controller} Parent object for chaining.
*/
this.addScene = function (newScene) {
if (_util.type.Array(newScene)) {
newScene.forEach(function (scene, index) {
Controller.addScene(scene);
});
} else if (newScene instanceof ScrollMagic.Scene) {
if (newScene.controller() !== Controller) {
newScene.addTo(Controller);
} else if (_sceneObjects.indexOf(newScene) < 0) {
// new scene
_sceneObjects.push(newScene); // add to array
_sceneObjects = sortScenes(_sceneObjects); // sort
newScene.on("shift.controller_sort", function () {// resort whenever scene moves
_sceneObjects = sortScenes(_sceneObjects);
});
// insert Global defaults.
for (var key in _options.globalSceneOptions) {
if (newScene[key]) {
newScene[key].call(newScene, _options.globalSceneOptions[key]);
}
}
log(3, "adding Scene (now " + _sceneObjects.length + " total)");
}
} else {
log(1, "ERROR: invalid argument supplied for '.addScene()'");
}
return Controller;
};
/**
* Remove one ore more scene(s) from the controller.
* This is the equivalent to `Scene.remove()`.
* @public
* @example
* // remove a scene from the controller
* controller.removeScene(scene);
*
* // remove multiple scenes from the controller
* controller.removeScene([scene, scene2, scene3]);
*
* @param {(ScrollMagic.Scene|array)} Scene - ScrollMagic Scene or Array of Scenes to be removed from the controller.
* @returns {Controller} Parent object for chaining.
*/
this.removeScene = function (Scene) {
if (_util.type.Array(Scene)) {
Scene.forEach(function (scene, index) {
Controller.removeScene(scene);
});
} else {
var index = _sceneObjects.indexOf(Scene);
if (index > -1) {
Scene.off("shift.controller_sort");
_sceneObjects.splice(index, 1);
log(3, "removing Scene (now " + _sceneObjects.length + " left)");
Scene.remove();
}
}
return Controller;
};
/**
* Update one ore more scene(s) according to the scroll position of the container.
* This is the equivalent to `Scene.update()`.
* The update method calculates the scene's start and end position (based on the trigger element, trigger hook, duration and offset) and checks it against the current scroll position of the container.
* It then updates the current scene state accordingly (or does nothing, if the state is already correct) – Pins will be set to their correct position and tweens will be updated to their correct progress.
* _**Note:** This method gets called constantly whenever Controller detects a change. The only application for you is if you change something outside of the realm of ScrollMagic, like moving the trigger or changing tween parameters._
* @public
* @example
* // update a specific scene on next cycle
* controller.updateScene(scene);
*
* // update a specific scene immediately
* controller.updateScene(scene, true);
*
* // update multiple scenes scene on next cycle
* controller.updateScene([scene1, scene2, scene3]);
*
* @param {ScrollMagic.Scene} Scene - ScrollMagic Scene or Array of Scenes that is/are supposed to be updated.
* @param {boolean} [immediately=false] - If `true` the update will be instant, if `false` it will wait until next update cycle.
This is useful when changing multiple properties of the scene - this way it will only be updated once all new properties are set (updateScenes).
* @return {Controller} Parent object for chaining.
*/
this.updateScene = function (Scene, immediately) {
if (_util.type.Array(Scene)) {
Scene.forEach(function (scene, index) {
Controller.updateScene(scene, immediately);
});
} else {
if (immediately) {
Scene.update(true);
} else if (_updateScenesOnNextCycle !== true && Scene instanceof ScrollMagic.Scene) {// if _updateScenesOnNextCycle is true, all connected scenes are already scheduled for update
// prep array for next update cycle
_updateScenesOnNextCycle = _updateScenesOnNextCycle || [];
if (_updateScenesOnNextCycle.indexOf(Scene) == -1) {
_updateScenesOnNextCycle.push(Scene);
}
_updateScenesOnNextCycle = sortScenes(_updateScenesOnNextCycle); // sort
debounceUpdate();
}
}
return Controller;
};
/**
* Updates the controller params and calls updateScene on every scene, that is attached to the controller.
* See `Controller.updateScene()` for more information about what this means.
* In most cases you will not need this function, as it is called constantly, whenever ScrollMagic detects a state change event, like resize or scroll.
* The only application for this method is when ScrollMagic fails to detect these events.
* One application is with some external scroll libraries (like iScroll) that move an internal container to a negative offset instead of actually scrolling. In this case the update on the controller needs to be called whenever the child container's position changes.
* For this case there will also be the need to provide a custom function to calculate the correct scroll position. See `Controller.scrollPos()` for details.
* @public
* @example
* // update the controller on next cycle (saves performance due to elimination of redundant updates)
* controller.update();
*
* // update the controller immediately
* controller.update(true);
*
* @param {boolean} [immediately=false] - If `true` the update will be instant, if `false` it will wait until next update cycle (better performance)
* @return {Controller} Parent object for chaining.
*/
this.update = function (immediately) {
onChange({
type: "resize" });
// will update size and set _updateScenesOnNextCycle to true
if (immediately) {
updateScenes();
}
return Controller;
};
/**
* Scroll to a numeric scroll offset, a DOM element, the start of a scene or provide an alternate method for scrolling.
* For vertical controllers it will change the top scroll offset and for horizontal applications it will change the left offset.
* @public
*
* @since 1.1.0
* @example
* // scroll to an offset of 100
* controller.scrollTo(100);
*
* // scroll to a DOM element
* controller.scrollTo("#anchor");
*
* // scroll to the beginning of a scene
* var scene = new ScrollMagic.Scene({offset: 200});
* controller.scrollTo(scene);
*
* // define a new scroll position modification function (jQuery animate instead of jump)
* controller.scrollTo(function (newScrollPos) {
* $("html, body").animate({scrollTop: newScrollPos});
* });
* controller.scrollTo(100); // call as usual, but the new function will be used instead
*
* // define a new scroll function with an additional parameter
* controller.scrollTo(function (newScrollPos, message) {
* console.log(message);
* $(this).animate({scrollTop: newScrollPos});
* });
* // call as usual, but supply an extra parameter to the defined custom function
* controller.scrollTo(100, "my message");
*
* // define a new scroll function with an additional parameter containing multiple variables
* controller.scrollTo(function (newScrollPos, options) {
* someGlobalVar = options.a + options.b;
* $(this).animate({scrollTop: newScrollPos});
* });
* // call as usual, but supply an extra parameter containing multiple options
* controller.scrollTo(100, {a: 1, b: 2});
*
* // define a new scroll function with a callback supplied as an additional parameter
* controller.scrollTo(function (newScrollPos, callback) {
* $(this).animate({scrollTop: newScrollPos}, 400, "swing", callback);
* });
* // call as usual, but supply an extra parameter, which is used as a callback in the previously defined custom scroll function
* controller.scrollTo(100, function() {
* console.log("scroll has finished.");
* });
*
* @param {mixed} scrollTarget - The supplied argument can be one of these types:
* 1. `number` -> The container will scroll to this new scroll offset.
* 2. `string` or `object` -> Can be a selector or a DOM object.
* The container will scroll to the position of this element.
* 3. `ScrollMagic Scene` -> The container will scroll to the start of this scene.
* 4. `function` -> This function will be used for future scroll position modifications.
* This provides a way for you to change the behaviour of scrolling and adding new behaviour like animation. The function receives the new scroll position as a parameter and a reference to the container element using `this`.
* It may also optionally receive an optional additional parameter (see below)
* _**NOTE:**
* All other options will still work as expected, using the new function to scroll._
* @param {mixed} [additionalParameter] - If a custom scroll function was defined (see above 4.), you may want to supply additional parameters to it, when calling it. You can do this using this parameter – see examples for details. Please note, that this parameter will have no effect, if you use the default scrolling function.
* @returns {Controller} Parent object for chaining.
*/
this.scrollTo = function (scrollTarget, additionalParameter) {
if (_util.type.Number(scrollTarget)) {// excecute
setScrollPos.call(_options.container, scrollTarget, additionalParameter);
} else if (scrollTarget instanceof ScrollMagic.Scene) {// scroll to scene
if (scrollTarget.controller() === Controller) {// check if the controller is associated with this scene
Controller.scrollTo(scrollTarget.scrollOffset(), additionalParameter);
} else {
log(2, "scrollTo(): The supplied scene does not belong to this controller. Scroll cancelled.", scrollTarget);
}
} else if (_util.type.Function(scrollTarget)) {// assign new scroll function
setScrollPos = scrollTarget;
} else {// scroll to element
var elem = _util.get.elements(scrollTarget)[0];
if (elem) {
// if parent is pin spacer, use spacer position instead so correct start position is returned for pinned elements.
while (elem.parentNode.hasAttribute(PIN_SPACER_ATTRIBUTE)) {
elem = elem.parentNode;
}
var
param = _options.vertical ? "top" : "left",
// which param is of interest ?
containerOffset = _util.get.offset(_options.container),
// container position is needed because element offset is returned in relation to document, not in relation to container.
elementOffset = _util.get.offset(elem);
if (!_isDocument) {// container is not the document root, so substract scroll Position to get correct trigger element position relative to scrollcontent
containerOffset[param] -= Controller.scrollPos();
}
Controller.scrollTo(elementOffset[param] - containerOffset[param], additionalParameter);
} else {
log(2, "scrollTo(): The supplied argument is invalid. Scroll cancelled.", scrollTarget);
}
}
return Controller;
};
/**
* **Get** the current scrollPosition or **Set** a new method to calculate it.
* -> **GET**:
* When used as a getter this function will return the current scroll position.
* To get a cached value use Controller.info("scrollPos"), which will be updated in the update cycle.
* For vertical controllers it will return the top scroll offset and for horizontal applications it will return the left offset.
*
* -> **SET**:
* When used as a setter this method prodes a way to permanently overwrite the controller's scroll position calculation.
* A typical usecase is when the scroll position is not reflected by the containers scrollTop or scrollLeft values, but for example by the inner offset of a child container.
* Moving a child container inside a parent is a commonly used method for several scrolling frameworks, including iScroll.
* By providing an alternate calculation function you can make sure ScrollMagic receives the correct scroll position.
* Please also bear in mind that your function should return y values for vertical scrolls an x for horizontals.
*
* To change the current scroll position please use `Controller.scrollTo()`.
* @public
*
* @example
* // get the current scroll Position
* var scrollPos = controller.scrollPos();
*
* // set a new scroll position calculation method
* controller.scrollPos(function () {
* return this.info("vertical") ? -mychildcontainer.y : -mychildcontainer.x
* });
*
* @param {function} [scrollPosMethod] - The function to be used for the scroll position calculation of the container.
* @returns {(number|Controller)} Current scroll position or parent object for chaining.
*/
this.scrollPos = function (scrollPosMethod) {
if (!arguments.length) {// get
return getScrollPos.call(Controller);
} else {// set
if (_util.type.Function(scrollPosMethod)) {
getScrollPos = scrollPosMethod;
} else {
log(2, "Provided value for method 'scrollPos' is not a function. To change the current scroll position use 'scrollTo()'.");
}
}
return Controller;
};
/**
* **Get** all infos or one in particular about the controller.
* @public
* @example
* // returns the current scroll position (number)
* var scrollPos = controller.info("scrollPos");
*
* // returns all infos as an object
* var infos = controller.info();
*
* @param {string} [about] - If passed only this info will be returned instead of an object containing all.
Valid options are:
** `"size"` => the current viewport size of the container
** `"vertical"` => true if vertical scrolling, otherwise false
** `"scrollPos"` => the current scroll position
** `"scrollDirection"` => the last known direction of the scroll
** `"container"` => the container element
** `"isDocument"` => true if container element is the document.
* @returns {(mixed|object)} The requested info(s).
*/
this.info = function (about) {
var values = {
size: _viewPortSize,
// contains height or width (in regard to orientation);
vertical: _options.vertical,
scrollPos: _scrollPos,
scrollDirection: _scrollDirection,
container: _options.container,
isDocument: _isDocument };
if (!arguments.length) {// get all as an object
return values;
} else if (values[about] !== undefined) {
return values[about];
} else {
log(1, "ERROR: option \"" + about + "\" is not available");
return;
}
};
/**
* **Get** or **Set** the current loglevel option value.
* @public
*
* @example
* // get the current value
* var loglevel = controller.loglevel();
*
* // set a new value
* controller.loglevel(3);
*
* @param {number} [newLoglevel] - The new loglevel setting of the Controller. `[0-3]`
* @returns {(number|Controller)} Current loglevel or parent object for chaining.
*/
this.loglevel = function (newLoglevel) {
if (!arguments.length) {// get
return _options.loglevel;
} else if (_options.loglevel != newLoglevel) {// set
_options.loglevel = newLoglevel;
}
return Controller;
};
/**
* **Get** or **Set** the current enabled state of the controller.
* This can be used to disable all Scenes connected to the controller without destroying or removing them.
* @public
*
* @example
* // get the current value
* var enabled = controller.enabled();
*
* // disable the controller
* controller.enabled(false);
*
* @param {boolean} [newState] - The new enabled state of the controller `true` or `false`.
* @returns {(boolean|Controller)} Current enabled state or parent object for chaining.
*/
this.enabled = function (newState) {
if (!arguments.length) {// get
return _enabled;
} else if (_enabled != newState) {// set
_enabled = !!newState;
Controller.updateScene(_sceneObjects, true);
}
return Controller;
};
/**
* Destroy the Controller, all Scenes and everything.
* @public
*
* @example
* // without resetting the scenes
* controller = controller.destroy();
*
* // with scene reset
* controller = controller.destroy(true);
*
* @param {boolean} [resetScenes=false] - If `true` the pins and tweens (if existent) of all scenes will be reset.
* @returns {null} Null to unset handler variables.
*/
this.destroy = function (resetScenes) {
window.clearTimeout(_refreshTimeout);
var i = _sceneObjects.length;
while (i--) {
_sceneObjects[i].destroy(resetScenes);
}
_options.container.removeEventListener("resize", onChange);
_options.container.removeEventListener("scroll", onChange);
_util.cAF(_updateTimeout);
log(3, "destroyed " + NAMESPACE + " (reset: " + (resetScenes ? "true" : "false") + ")");
return null;
};
// INIT
construct();
return Controller;
};
// store pagewide controller options
var CONTROLLER_OPTIONS = {
defaults: {
container: window,
vertical: true,
globalSceneOptions: {},
loglevel: 2,
refreshInterval: 100 } };
/*
* method used to add an option to ScrollMagic Scenes.
*/
ScrollMagic.Controller.addOption = function (name, defaultValue) {
CONTROLLER_OPTIONS.defaults[name] = defaultValue;
};
// instance extension function for plugins
ScrollMagic.Controller.extend = function (extension) {
var oldClass = this;
ScrollMagic.Controller = function () {
oldClass.apply(this, arguments);
this.$super = _util.extend({}, this); // copy parent state
return extension.apply(this, arguments) || this;
};
_util.extend(ScrollMagic.Controller, oldClass); // copy properties
ScrollMagic.Controller.prototype = oldClass.prototype; // copy prototype
ScrollMagic.Controller.prototype.constructor = ScrollMagic.Controller; // restore constructor
};
/**
* A Scene defines where the controller should react and how.
*
* @class
*
* @example
* // create a standard scene and add it to a controller
* new ScrollMagic.Scene()
* .addTo(controller);
*
* // create a scene with custom options and assign a handler to it.
* var scene = new ScrollMagic.Scene({
* duration: 100,
* offset: 200,
* triggerHook: "onEnter",
* reverse: false
* });
*
* @param {object} [options] - Options for the Scene. The options can be updated at any time.
Instead of setting the options for each scene individually you can also set them globally in the controller as the controllers `globalSceneOptions` option. The object accepts the same properties as the ones below.
When a scene is added to the controller the options defined using the Scene constructor will be overwritten by those set in `globalSceneOptions`.
* @param {(number|function)} [options.duration=0] - The duration of the scene.
If `0` tweens will auto-play when reaching the scene start point, pins will be pinned indefinetly starting at the start position.
A function retuning the duration value is also supported. Please see `Scene.duration()` for details.
* @param {number} [options.offset=0] - Offset Value for the Trigger Position. If no triggerElement is defined this will be the scroll distance from the start of the page, after which the scene will start.
* @param {(string|object)} [options.triggerElement=null] - Selector or DOM object that defines the start of the scene. If undefined the scene will start right at the start of the page (unless an offset is set).
* @param {(number|string)} [options.triggerHook="onCenter"] - Can be a number between 0 and 1 defining the position of the trigger Hook in relation to the viewport.
Can also be defined using a string:
** `"onEnter"` => `1`
** `"onCenter"` => `0.5`
** `"onLeave"` => `0`
* @param {boolean} [options.reverse=true] - Should the scene reverse, when scrolling up?
* @param {number} [options.loglevel=2] - Loglevel for debugging. Note that logging is disabled in the minified version of ScrollMagic.
** `0` => silent
** `1` => errors
** `2` => errors, warnings
** `3` => errors, warnings, debuginfo
*
*/
ScrollMagic.Scene = function (options) {
/*
* ----------------------------------------------------------------
* settings
* ----------------------------------------------------------------
*/
var
NAMESPACE = 'ScrollMagic.Scene',
SCENE_STATE_BEFORE = 'BEFORE',
SCENE_STATE_DURING = 'DURING',
SCENE_STATE_AFTER = 'AFTER',
DEFAULT_OPTIONS = SCENE_OPTIONS.defaults;
/*
* ----------------------------------------------------------------
* private vars
* ----------------------------------------------------------------
*/
var
Scene = this,
_options = _util.extend({}, DEFAULT_OPTIONS, options),
_state = SCENE_STATE_BEFORE,
_progress = 0,
_scrollOffset = {
start: 0,
end: 0 },
// reflects the controllers's scroll position for the start and end of the scene respectively
_triggerPos = 0,
_enabled = true,
_durationUpdateMethod,_controller;
/**
* Internal constructor function of the ScrollMagic Scene
* @private
*/
var construct = function construct() {
for (var key in _options) {// check supplied options
if (!DEFAULT_OPTIONS.hasOwnProperty(key)) {
log(2, "WARNING: Unknown option \"" + key + "\"");
delete _options[key];
}
}
// add getters/setters for all possible options
for (var optionName in DEFAULT_OPTIONS) {
addSceneOption(optionName);
}
// validate all options
validateOption();
};
/*
* ----------------------------------------------------------------
* Event Management
* ----------------------------------------------------------------
*/
var _listeners = {};
/**
* Scene start event.
* Fires whenever the scroll position its the starting point of the scene.
* It will also fire when scrolling back up going over the start position of the scene. If you want something to happen only when scrolling down/right, use the scrollDirection parameter passed to the callback.
*
* For details on this event and the order in which it is fired, please review the {@link Scene.progress} method.
*
* @event ScrollMagic.Scene#start
*
* @example
* scene.on("start", function (event) {
* console.log("Hit start point of scene.");
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {Scene} event.target - The Scene object that triggered this event
* @property {number} event.progress - Reflects the current progress of the scene
* @property {string} event.state - The current state of the scene `"BEFORE"` or `"DURING"`
* @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"`
*/
/**
* Scene end event.
* Fires whenever the scroll position its the ending point of the scene.
* It will also fire when scrolling back up from after the scene and going over its end position. If you want something to happen only when scrolling down/right, use the scrollDirection parameter passed to the callback.
*
* For details on this event and the order in which it is fired, please review the {@link Scene.progress} method.
*
* @event ScrollMagic.Scene#end
*
* @example
* scene.on("end", function (event) {
* console.log("Hit end point of scene.");
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {Scene} event.target - The Scene object that triggered this event
* @property {number} event.progress - Reflects the current progress of the scene
* @property {string} event.state - The current state of the scene `"DURING"` or `"AFTER"`
* @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"`
*/
/**
* Scene enter event.
* Fires whenever the scene enters the "DURING" state.
* Keep in mind that it doesn't matter if the scene plays forward or backward: This event always fires when the scene enters its active scroll timeframe, regardless of the scroll-direction.
*
* For details on this event and the order in which it is fired, please review the {@link Scene.progress} method.
*
* @event ScrollMagic.Scene#enter
*
* @example
* scene.on("enter", function (event) {
* console.log("Scene entered.");
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {Scene} event.target - The Scene object that triggered this event
* @property {number} event.progress - Reflects the current progress of the scene
* @property {string} event.state - The current state of the scene - always `"DURING"`
* @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"`
*/
/**
* Scene leave event.
* Fires whenever the scene's state goes from "DURING" to either "BEFORE" or "AFTER".
* Keep in mind that it doesn't matter if the scene plays forward or backward: This event always fires when the scene leaves its active scroll timeframe, regardless of the scroll-direction.
*
* For details on this event and the order in which it is fired, please review the {@link Scene.progress} method.
*
* @event ScrollMagic.Scene#leave
*
* @example
* scene.on("leave", function (event) {
* console.log("Scene left.");
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {Scene} event.target - The Scene object that triggered this event
* @property {number} event.progress - Reflects the current progress of the scene
* @property {string} event.state - The current state of the scene `"BEFORE"` or `"AFTER"`
* @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"`
*/
/**
* Scene update event.
* Fires whenever the scene is updated (but not necessarily changes the progress).
*
* @event ScrollMagic.Scene#update
*
* @example
* scene.on("update", function (event) {
* console.log("Scene updated.");
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {Scene} event.target - The Scene object that triggered this event
* @property {number} event.startPos - The starting position of the scene (in relation to the conainer)
* @property {number} event.endPos - The ending position of the scene (in relation to the conainer)
* @property {number} event.scrollPos - The current scroll position of the container
*/
/**
* Scene progress event.
* Fires whenever the progress of the scene changes.
*
* For details on this event and the order in which it is fired, please review the {@link Scene.progress} method.
*
* @event ScrollMagic.Scene#progress
*
* @example
* scene.on("progress", function (event) {
* console.log("Scene progress changed to " + event.progress);
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {Scene} event.target - The Scene object that triggered this event
* @property {number} event.progress - Reflects the current progress of the scene
* @property {string} event.state - The current state of the scene `"BEFORE"`, `"DURING"` or `"AFTER"`
* @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"`
*/
/**
* Scene change event.
* Fires whenvever a property of the scene is changed.
*
* @event ScrollMagic.Scene#change
*
* @example
* scene.on("change", function (event) {
* console.log("Scene Property \"" + event.what + "\" changed to " + event.newval);
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {Scene} event.target - The Scene object that triggered this event
* @property {string} event.what - Indicates what value has been changed
* @property {mixed} event.newval - The new value of the changed property
*/
/**
* Scene shift event.
* Fires whenvever the start or end **scroll offset** of the scene change.
* This happens explicitely, when one of these values change: `offset`, `duration` or `triggerHook`.
* It will fire implicitly when the `triggerElement` changes, if the new element has a different position (most cases).
* It will also fire implicitly when the size of the container changes and the triggerHook is anything other than `onLeave`.
*
* @event ScrollMagic.Scene#shift
* @since 1.1.0
*
* @example
* scene.on("shift", function (event) {
* console.log("Scene moved, because the " + event.reason + " has changed.)");
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {Scene} event.target - The Scene object that triggered this event
* @property {string} event.reason - Indicates why the scene has shifted
*/
/**
* Scene destroy event.
* Fires whenvever the scene is destroyed.
* This can be used to tidy up custom behaviour used in events.
*
* @event ScrollMagic.Scene#destroy
* @since 1.1.0
*
* @example
* scene.on("enter", function (event) {
* // add custom action
* $("#my-elem").left("200");
* })
* .on("destroy", function (event) {
* // reset my element to start position
* if (event.reset) {
* $("#my-elem").left("0");
* }
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {Scene} event.target - The Scene object that triggered this event
* @property {boolean} event.reset - Indicates if the destroy method was called with reset `true` or `false`.
*/
/**
* Scene add event.
* Fires when the scene is added to a controller.
* This is mostly used by plugins to know that change might be due.
*
* @event ScrollMagic.Scene#add
* @since 2.0.0
*
* @example
* scene.on("add", function (event) {
* console.log('Scene was added to a new controller.');
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {Scene} event.target - The Scene object that triggered this event
* @property {boolean} event.controller - The controller object the scene was added to.
*/
/**
* Scene remove event.
* Fires when the scene is removed from a controller.
* This is mostly used by plugins to know that change might be due.
*
* @event ScrollMagic.Scene#remove
* @since 2.0.0
*
* @example
* scene.on("remove", function (event) {
* console.log('Scene was removed from its controller.');
* });
*
* @property {object} event - The event Object passed to each callback
* @property {string} event.type - The name of the event
* @property {Scene} event.target - The Scene object that triggered this event
*/
/**
* Add one ore more event listener.
* The callback function will be fired at the respective event, and an object containing relevant data will be passed to the callback.
* @method ScrollMagic.Scene#on
*
* @example
* function callback (event) {
* console.log("Event fired! (" + event.type + ")");
* }
* // add listeners
* scene.on("change update progress start end enter leave", callback);
*
* @param {string} names - The name or names of the event the callback should be attached to.
* @param {function} callback - A function that should be executed, when the event is dispatched. An event object will be passed to the callback.
* @returns {Scene} Parent object for chaining.
*/
this.on = function (names, callback) {
if (_util.type.Function(callback)) {
names = names.trim().split(' ');
names.forEach(function (fullname) {
var
nameparts = fullname.split('.'),
eventname = nameparts[0],
namespace = nameparts[1];
if (eventname != "*") {// disallow wildcards
if (!_listeners[eventname]) {
_listeners[eventname] = [];
}
_listeners[eventname].push({
namespace: namespace || '',
callback: callback });
}
});
} else {
log(1, "ERROR when calling '.on()': Supplied callback for '" + names + "' is not a valid function!");
}
return Scene;
};
/**
* Remove one or more event listener.
* @method ScrollMagic.Scene#off
*
* @example
* function callback (event) {
* console.log("Event fired! (" + event.type + ")");
* }
* // add listeners
* scene.on("change update", callback);
* // remove listeners
* scene.off("change update", callback);
*
* @param {string} names - The name or names of the event that should be removed.
* @param {function} [callback] - A specific callback function that should be removed. If none is passed all callbacks to the event listener will be removed.
* @returns {Scene} Parent object for chaining.
*/
this.off = function (names, callback) {
if (!names) {
log(1, "ERROR: Invalid event name supplied.");
return Scene;
}
names = names.trim().split(' ');
names.forEach(function (fullname, key) {
var
nameparts = fullname.split('.'),
eventname = nameparts[0],
namespace = nameparts[1] || '',
removeList = eventname === '*' ? Object.keys(_listeners) : [eventname];
removeList.forEach(function (remove) {
var
list = _listeners[remove] || [],
i = list.length;
while (i--) {
var listener = list[i];
if (listener && (namespace === listener.namespace || namespace === '*') && (!callback || callback == listener.callback)) {
list.splice(i, 1);
}
}
if (!list.length) {
delete _listeners[remove];
}
});
});
return Scene;
};
/**
* Trigger an event.
* @method ScrollMagic.Scene#trigger
*
* @example
* this.trigger("change");
*
* @param {string} name - The name of the event that should be triggered.
* @param {object} [vars] - An object containing info that should be passed to the callback.
* @returns {Scene} Parent object for chaining.
*/
this.trigger = function (name, vars) {
if (name) {
var
nameparts = name.trim().split('.'),
eventname = nameparts[0],
namespace = nameparts[1],
listeners = _listeners[eventname];
log(3, 'event fired:', eventname, vars ? "->" : '', vars || '');
if (listeners) {
listeners.forEach(function (listener, key) {
if (!namespace || namespace === listener.namespace) {
listener.callback.call(Scene, new ScrollMagic.Event(eventname, listener.namespace, Scene, vars));
}
});
}
} else {
log(1, "ERROR: Invalid event name supplied.");
}
return Scene;
};
// set event listeners
Scene.on("change.internal", function (e) {
if (e.what !== "loglevel" && e.what !== "tweenChanges") {// no need for a scene update scene with these options...
if (e.what === "triggerElement") {
updateTriggerElementPosition();
} else if (e.what === "reverse") {// the only property left that may have an impact on the current scene state. Everything else is handled by the shift event.
Scene.update();
}
}
}).on("shift.internal", function (e) {
updateScrollOffset();
Scene.update(); // update scene to reflect new position
});
/**
* Send a debug message to the console.
* @private
* but provided publicly with _log for plugins
*
* @param {number} loglevel - The loglevel required to initiate output for the message.
* @param {...mixed} output - One or more variables that should be passed to the console.
*/
var log = this._log = function (loglevel, output) {
if (_options.loglevel >= loglevel) {
Array.prototype.splice.call(arguments, 1, 0, "(" + NAMESPACE + ") ->");
_util.log.apply(window, arguments);
}
};
/**
* Add the scene to a controller.
* This is the equivalent to `Controller.addScene(scene)`.
* @method ScrollMagic.Scene#addTo
*
* @example
* // add a scene to a ScrollMagic Controller
* scene.addTo(controller);
*
* @param {ScrollMagic.Controller} controller - The controller to which the scene should be added.
* @returns {Scene} Parent object for chaining.
*/
this.addTo = function (controller) {
if (!(controller instanceof ScrollMagic.Controller)) {
log(1, "ERROR: supplied argument of 'addTo()' is not a valid ScrollMagic Controller");
} else if (_controller != controller) {
// new controller
if (_controller) {// was associated to a different controller before, so remove it...
_controller.removeScene(Scene);
}
_controller = controller;
validateOption();
updateDuration(true);
updateTriggerElementPosition(true);
updateScrollOffset();
_controller.info("container").addEventListener('resize', onContainerResize);
controller.addScene(Scene);
Scene.trigger("add", {
controller: _controller });
log(3, "added " + NAMESPACE + " to controller");
Scene.update();
}
return Scene;
};
/**
* **Get** or **Set** the current enabled state of the scene.
* This can be used to disable this scene without removing or destroying it.
* @method ScrollMagic.Scene#enabled
*
* @example
* // get the current value
* var enabled = scene.enabled();
*
* // disable the scene
* scene.enabled(false);
*
* @param {boolean} [newState] - The new enabled state of the scene `true` or `false`.
* @returns {(boolean|Scene)} Current enabled state or parent object for chaining.
*/
this.enabled = function (newState) {
if (!arguments.length) {// get
return _enabled;
} else if (_enabled != newState) {// set
_enabled = !!newState;
Scene.update(true);
}
return Scene;
};
/**
* Remove the scene from the controller.
* This is the equivalent to `Controller.removeScene(scene)`.
* The scene will not be updated anymore until you readd it to a controller.
* To remove the pin or the tween you need to call removeTween() or removePin() respectively.
* @method ScrollMagic.Scene#remove
* @example
* // remove the scene from its controller
* scene.remove();
*
* @returns {Scene} Parent object for chaining.
*/
this.remove = function () {
if (_controller) {
_controller.info("container").removeEventListener('resize', onContainerResize);
var tmpParent = _controller;
_controller = undefined;
tmpParent.removeScene(Scene);
Scene.trigger("remove");
log(3, "removed " + NAMESPACE + " from controller");
}
return Scene;
};
/**
* Destroy the scene and everything.
* @method ScrollMagic.Scene#destroy
* @example
* // destroy the scene without resetting the pin and tween to their initial positions
* scene = scene.destroy();
*
* // destroy the scene and reset the pin and tween
* scene = scene.destroy(true);
*
* @param {boolean} [reset=false] - If `true` the pin and tween (if existent) will be reset.
* @returns {null} Null to unset handler variables.
*/
this.destroy = function (reset) {
Scene.trigger("destroy", {
reset: reset });
Scene.remove();
Scene.off("*.*");
log(3, "destroyed " + NAMESPACE + " (reset: " + (reset ? "true" : "false") + ")");
return null;
};
/**
* Updates the Scene to reflect the current state.
* This is the equivalent to `Controller.updateScene(scene, immediately)`.
* The update method calculates the scene's start and end position (based on the trigger element, trigger hook, duration and offset) and checks it against the current scroll position of the container.
* It then updates the current scene state accordingly (or does nothing, if the state is already correct) – Pins will be set to their correct position and tweens will be updated to their correct progress.
* This means an update doesn't necessarily result in a progress change. The `progress` event will be fired if the progress has indeed changed between this update and the last.
* _**NOTE:** This method gets called constantly whenever ScrollMagic detects a change. The only application for you is if you change something outside of the realm of ScrollMagic, like moving the trigger or changing tween parameters._
* @method ScrollMagic.Scene#update
* @example
* // update the scene on next tick
* scene.update();
*
* // update the scene immediately
* scene.update(true);
*
* @fires Scene.update
*
* @param {boolean} [immediately=false] - If `true` the update will be instant, if `false` it will wait until next update cycle (better performance).
* @returns {Scene} Parent object for chaining.
*/
this.update = function (immediately) {
if (_controller) {
if (immediately) {
if (_controller.enabled() && _enabled) {
var
scrollPos = _controller.info("scrollPos"),
newProgress;
if (_options.duration > 0) {
newProgress = (scrollPos - _scrollOffset.start) / (_scrollOffset.end - _scrollOffset.start);
} else {
newProgress = scrollPos >= _scrollOffset.start ? 1 : 0;
}
Scene.trigger("update", {
startPos: _scrollOffset.start,
endPos: _scrollOffset.end,
scrollPos: scrollPos });
Scene.progress(newProgress);
} else if (_pin && _state === SCENE_STATE_DURING) {
updatePinState(true); // unpin in position
}
} else {
_controller.updateScene(Scene, false);
}
}
return Scene;
};
/**
* Updates dynamic scene variables like the trigger element position or the duration.
* This method is automatically called in regular intervals from the controller. See {@link ScrollMagic.Controller} option `refreshInterval`.
*
* You can call it to minimize lag, for example when you intentionally change the position of the triggerElement.
* If you don't it will simply be updated in the next refresh interval of the container, which is usually sufficient.
*
* @method ScrollMagic.Scene#refresh
* @since 1.1.0
* @example
* scene = new ScrollMagic.Scene({triggerElement: "#trigger"});
*
* // change the position of the trigger
* $("#trigger").css("top", 500);
* // immediately let the scene know of this change
* scene.refresh();
*
* @fires {@link Scene.shift}, if the trigger element position or the duration changed
* @fires {@link Scene.change}, if the duration changed
*
* @returns {Scene} Parent object for chaining.
*/
this.refresh = function () {
updateDuration();
updateTriggerElementPosition();
// update trigger element position
return Scene;
};
/**
* **Get** or **Set** the scene's progress.
* Usually it shouldn't be necessary to use this as a setter, as it is set automatically by scene.update().
* The order in which the events are fired depends on the duration of the scene:
* 1. Scenes with `duration == 0`:
* Scenes that have no duration by definition have no ending. Thus the `end` event will never be fired.
* When the trigger position of the scene is passed the events are always fired in this order:
* `enter`, `start`, `progress` when scrolling forward
* and
* `progress`, `start`, `leave` when scrolling in reverse
* 2. Scenes with `duration > 0`:
* Scenes with a set duration have a defined start and end point.
* When scrolling past the start position of the scene it will fire these events in this order:
* `enter`, `start`, `progress`
* When continuing to scroll and passing the end point it will fire these events:
* `progress`, `end`, `leave`
* When reversing through the end point these events are fired:
* `enter`, `end`, `progress`
* And when continuing to scroll past the start position in reverse it will fire:
* `progress`, `start`, `leave`
* In between start and end the `progress` event will be called constantly, whenever the progress changes.
*
* In short:
* `enter` events will always trigger **before** the progress update and `leave` envents will trigger **after** the progress update.
* `start` and `end` will always trigger at their respective position.
*
* Please review the event descriptions for details on the events and the event object that is passed to the callback.
*
* @method ScrollMagic.Scene#progress
* @example
* // get the current scene progress
* var progress = scene.progress();
*
* // set new scene progress
* scene.progress(0.3);
*
* @fires {@link Scene.enter}, when used as setter
* @fires {@link Scene.start}, when used as setter
* @fires {@link Scene.progress}, when used as setter
* @fires {@link Scene.end}, when used as setter
* @fires {@link Scene.leave}, when used as setter
*
* @param {number} [progress] - The new progress value of the scene `[0-1]`.
* @returns {number} `get` - Current scene progress.
* @returns {Scene} `set` - Parent object for chaining.
*/
this.progress = function (progress) {
if (!arguments.length) {// get
return _progress;
} else {// set
var
doUpdate = false,
oldState = _state,
scrollDirection = _controller ? _controller.info("scrollDirection") : 'PAUSED',
reverseOrForward = _options.reverse || progress >= _progress;
if (_options.duration === 0) {
// zero duration scenes
doUpdate = _progress != progress;
_progress = progress < 1 && reverseOrForward ? 0 : 1;
_state = _progress === 0 ? SCENE_STATE_BEFORE : SCENE_STATE_DURING;
} else {
// scenes with start and end
if (progress < 0 && _state !== SCENE_STATE_BEFORE && reverseOrForward) {
// go back to initial state
_progress = 0;
_state = SCENE_STATE_BEFORE;
doUpdate = true;
} else if (progress >= 0 && progress < 1 && reverseOrForward) {
_progress = progress;
_state = SCENE_STATE_DURING;
doUpdate = true;
} else if (progress >= 1 && _state !== SCENE_STATE_AFTER) {
_progress = 1;
_state = SCENE_STATE_AFTER;
doUpdate = true;
} else if (_state === SCENE_STATE_DURING && !reverseOrForward) {
updatePinState(); // in case we scrolled backwards mid-scene and reverse is disabled => update the pin position, so it doesn't move back as well.
}
}
if (doUpdate) {
// fire events
var
eventVars = {
progress: _progress,
state: _state,
scrollDirection: scrollDirection },
stateChanged = _state != oldState;
var trigger = function trigger(eventName) {// tmp helper to simplify code
Scene.trigger(eventName, eventVars);
};
if (stateChanged) {// enter events
if (oldState !== SCENE_STATE_DURING) {
trigger("enter");
trigger(oldState === SCENE_STATE_BEFORE ? "start" : "end");
}
}
trigger("progress");
if (stateChanged) {// leave events
if (_state !== SCENE_STATE_DURING) {
trigger(_state === SCENE_STATE_BEFORE ? "start" : "end");
trigger("leave");
}
}
}
return Scene;
}
};
/**
* Update the start and end scrollOffset of the container.
* The positions reflect what the controller's scroll position will be at the start and end respectively.
* Is called, when:
* - Scene event "change" is called with: offset, triggerHook, duration
* - scroll container event "resize" is called
* - the position of the triggerElement changes
* - the controller changes -> addTo()
* @private
*/
var updateScrollOffset = function updateScrollOffset() {
_scrollOffset = {
start: _triggerPos + _options.offset };
if (_controller && _options.triggerElement) {
// take away triggerHook portion to get relative to top
_scrollOffset.start -= _controller.info("size") * _options.triggerHook;
}
_scrollOffset.end = _scrollOffset.start + _options.duration;
};
/**
* Updates the duration if set to a dynamic function.
* This method is called when the scene is added to a controller and in regular intervals from the controller through scene.refresh().
*
* @fires {@link Scene.change}, if the duration changed
* @fires {@link Scene.shift}, if the duration changed
*
* @param {boolean} [suppressEvents=false] - If true the shift event will be suppressed.
* @private
*/
var updateDuration = function updateDuration(suppressEvents) {
// update duration
if (_durationUpdateMethod) {
var varname = "duration";
if (changeOption(varname, _durationUpdateMethod.call(Scene)) && !suppressEvents) {// set
Scene.trigger("change", {
what: varname,
newval: _options[varname] });
Scene.trigger("shift", {
reason: varname });
}
}
};
/**
* Updates the position of the triggerElement, if present.
* This method is called ...
* - ... when the triggerElement is changed
* - ... when the scene is added to a (new) controller
* - ... in regular intervals from the controller through scene.refresh().
*
* @fires {@link Scene.shift}, if the position changed
*
* @param {boolean} [suppressEvents=false] - If true the shift event will be suppressed.
* @private
*/
var updateTriggerElementPosition = function updateTriggerElementPosition(suppressEvents) {
var
elementPos = 0,
telem = _options.triggerElement;
if (_controller && telem) {
var
controllerInfo = _controller.info(),
containerOffset = _util.get.offset(controllerInfo.container),
// container position is needed because element offset is returned in relation to document, not in relation to container.
param = controllerInfo.vertical ? "top" : "left"; // which param is of interest ?
// if parent is spacer, use spacer position instead so correct start position is returned for pinned elements.
while (telem.parentNode.hasAttribute(PIN_SPACER_ATTRIBUTE)) {
telem = telem.parentNode;
}
var elementOffset = _util.get.offset(telem);
if (!controllerInfo.isDocument) {// container is not the document root, so substract scroll Position to get correct trigger element position relative to scrollcontent
containerOffset[param] -= _controller.scrollPos();
}
elementPos = elementOffset[param] - containerOffset[param];
}
var changed = elementPos != _triggerPos;
_triggerPos = elementPos;
if (changed && !suppressEvents) {
Scene.trigger("shift", {
reason: "triggerElementPosition" });
}
};
/**
* Trigger a shift event, when the container is resized and the triggerHook is > 1.
* @private
*/
var onContainerResize = function onContainerResize(e) {
if (_options.triggerHook > 0) {
Scene.trigger("shift", {
reason: "containerResize" });
}
};
var _validate = _util.extend(SCENE_OPTIONS.validate, {
// validation for duration handled internally for reference to private var _durationMethod
duration: function duration(val) {
if (_util.type.String(val) && val.match(/^(\.|\d)*\d+%$/)) {
// percentage value
var perc = parseFloat(val) / 100;
val = function val() {
return _controller ? _controller.info("size") * perc : 0;
};
}
if (_util.type.Function(val)) {
// function
_durationUpdateMethod = val;
try {
val = parseFloat(_durationUpdateMethod());
} catch (e) {
val = -1; // will cause error below
}
}
// val has to be float
val = parseFloat(val);
if (!_util.type.Number(val) || val < 0) {
if (_durationUpdateMethod) {
_durationUpdateMethod = undefined;
throw ["Invalid return value of supplied function for option \"duration\":", val];
} else {
throw ["Invalid value for option \"duration\":", val];
}
}
return val;
} });
/**
* Checks the validity of a specific or all options and reset to default if neccessary.
* @private
*/
var validateOption = function validateOption(check) {
check = arguments.length ? [check] : Object.keys(_validate);
check.forEach(function (optionName, key) {
var value;
if (_validate[optionName]) {// there is a validation method for this option
try {// validate value
value = _validate[optionName](_options[optionName]);
} catch (e) {// validation failed -> reset to default
value = DEFAULT_OPTIONS[optionName];
var logMSG = _util.type.String(e) ? [e] : e;
if (_util.type.Array(logMSG)) {
logMSG[0] = "ERROR: " + logMSG[0];
logMSG.unshift(1); // loglevel 1 for error msg
log.apply(this, logMSG);
} else {
log(1, "ERROR: Problem executing validation callback for option '" + optionName + "':", e.message);
}
} finally {
_options[optionName] = value;
}
}
});
};
/**
* Helper used by the setter/getters for scene options
* @private
*/
var changeOption = function changeOption(varname, newval) {
var
changed = false,
oldval = _options[varname];
if (_options[varname] != newval) {
_options[varname] = newval;
validateOption(varname); // resets to default if necessary
changed = oldval != _options[varname];
}
return changed;
};
// generate getters/setters for all options
var addSceneOption = function addSceneOption(optionName) {
if (!Scene[optionName]) {
Scene[optionName] = function (newVal) {
if (!arguments.length) {// get
return _options[optionName];
} else {
if (optionName === "duration") {// new duration is set, so any previously set function must be unset
_durationUpdateMethod = undefined;
}
if (changeOption(optionName, newVal)) {// set
Scene.trigger("change", {
what: optionName,
newval: _options[optionName] });
if (SCENE_OPTIONS.shifts.indexOf(optionName) > -1) {
Scene.trigger("shift", {
reason: optionName });
}
}
}
return Scene;
};
}
};
/**
* **Get** or **Set** the duration option value.
* As a setter it also accepts a function returning a numeric value.
* This is particularly useful for responsive setups.
*
* The duration is updated using the supplied function every time `Scene.refresh()` is called, which happens periodically from the controller (see ScrollMagic.Controller option `refreshInterval`).
* _**NOTE:** Be aware that it's an easy way to kill performance, if you supply a function that has high CPU demand.
* Even for size and position calculations it is recommended to use a variable to cache the value. (see example)
* This counts double if you use the same function for multiple scenes._
*
* @method ScrollMagic.Scene#duration
* @example
* // get the current duration value
* var duration = scene.duration();
*
* // set a new duration
* scene.duration(300);
*
* // use a function to automatically adjust the duration to the window height.
* var durationValueCache;
* function getDuration () {
* return durationValueCache;
* }
* function updateDuration (e) {
* durationValueCache = window.innerHeight;
* }
* $(window).on("resize", updateDuration); // update the duration when the window size changes
* $(window).triggerHandler("resize"); // set to initial value
* scene.duration(getDuration); // supply duration method
*
* @fires {@link Scene.change}, when used as setter
* @fires {@link Scene.shift}, when used as setter
* @param {(number|function)} [newDuration] - The new duration of the scene.
* @returns {number} `get` - Current scene duration.
* @returns {Scene} `set` - Parent object for chaining.
*/
/**
* **Get** or **Set** the offset option value.
* @method ScrollMagic.Scene#offset
* @example
* // get the current offset
* var offset = scene.offset();
*
* // set a new offset
* scene.offset(100);
*
* @fires {@link Scene.change}, when used as setter
* @fires {@link Scene.shift}, when used as setter
* @param {number} [newOffset] - The new offset of the scene.
* @returns {number} `get` - Current scene offset.
* @returns {Scene} `set` - Parent object for chaining.
*/
/**
* **Get** or **Set** the triggerElement option value.
* Does **not** fire `Scene.shift`, because changing the trigger Element doesn't necessarily mean the start position changes. This will be determined in `Scene.refresh()`, which is automatically triggered.
* @method ScrollMagic.Scene#triggerElement
* @example
* // get the current triggerElement
* var triggerElement = scene.triggerElement();
*
* // set a new triggerElement using a selector
* scene.triggerElement("#trigger");
* // set a new triggerElement using a DOM object
* scene.triggerElement(document.getElementById("trigger"));
*
* @fires {@link Scene.change}, when used as setter
* @param {(string|object)} [newTriggerElement] - The new trigger element for the scene.
* @returns {(string|object)} `get` - Current triggerElement.
* @returns {Scene} `set` - Parent object for chaining.
*/
/**
* **Get** or **Set** the triggerHook option value.
* @method ScrollMagic.Scene#triggerHook
* @example
* // get the current triggerHook value
* var triggerHook = scene.triggerHook();
*
* // set a new triggerHook using a string
* scene.triggerHook("onLeave");
* // set a new triggerHook using a number
* scene.triggerHook(0.7);
*
* @fires {@link Scene.change}, when used as setter
* @fires {@link Scene.shift}, when used as setter
* @param {(number|string)} [newTriggerHook] - The new triggerHook of the scene. See {@link Scene} parameter description for value options.
* @returns {number} `get` - Current triggerHook (ALWAYS numerical).
* @returns {Scene} `set` - Parent object for chaining.
*/
/**
* **Get** or **Set** the reverse option value.
* @method ScrollMagic.Scene#reverse
* @example
* // get the current reverse option
* var reverse = scene.reverse();
*
* // set new reverse option
* scene.reverse(false);
*
* @fires {@link Scene.change}, when used as setter
* @param {boolean} [newReverse] - The new reverse setting of the scene.
* @returns {boolean} `get` - Current reverse option value.
* @returns {Scene} `set` - Parent object for chaining.
*/
/**
* **Get** or **Set** the loglevel option value.
* @method ScrollMagic.Scene#loglevel
* @example
* // get the current loglevel
* var loglevel = scene.loglevel();
*
* // set new loglevel
* scene.loglevel(3);
*
* @fires {@link Scene.change}, when used as setter
* @param {number} [newLoglevel] - The new loglevel setting of the scene. `[0-3]`
* @returns {number} `get` - Current loglevel.
* @returns {Scene} `set` - Parent object for chaining.
*/
/**
* **Get** the associated controller.
* @method ScrollMagic.Scene#controller
* @example
* // get the controller of a scene
* var controller = scene.controller();
*
* @returns {ScrollMagic.Controller} Parent controller or `undefined`
*/
this.controller = function () {
return _controller;
};
/**
* **Get** the current state.
* @method ScrollMagic.Scene#state
* @example
* // get the current state
* var state = scene.state();
*
* @returns {string} `"BEFORE"`, `"DURING"` or `"AFTER"`
*/
this.state = function () {
return _state;
};
/**
* **Get** the current scroll offset for the start of the scene.
* Mind, that the scrollOffset is related to the size of the container, if `triggerHook` is bigger than `0` (or `"onLeave"`).
* This means, that resizing the container or changing the `triggerHook` will influence the scene's start offset.
* @method ScrollMagic.Scene#scrollOffset
* @example
* // get the current scroll offset for the start and end of the scene.
* var start = scene.scrollOffset();
* var end = scene.scrollOffset() + scene.duration();
* console.log("the scene starts at", start, "and ends at", end);
*
* @returns {number} The scroll offset (of the container) at which the scene will trigger. Y value for vertical and X value for horizontal scrolls.
*/
this.scrollOffset = function () {
return _scrollOffset.start;
};
/**
* **Get** the trigger position of the scene (including the value of the `offset` option).
* @method ScrollMagic.Scene#triggerPosition
* @example
* // get the scene's trigger position
* var triggerPosition = scene.triggerPosition();
*
* @returns {number} Start position of the scene. Top position value for vertical and left position value for horizontal scrolls.
*/
this.triggerPosition = function () {
var pos = _options.offset; // the offset is the basis
if (_controller) {
// get the trigger position
if (_options.triggerElement) {
// Element as trigger
pos += _triggerPos;
} else {
// return the height of the triggerHook to start at the beginning
pos += _controller.info("size") * Scene.triggerHook();
}
}
return pos;
};
var
_pin, _pinOptions;
Scene.on("shift.internal", function (e) {
var durationChanged = e.reason === "duration";
if (_state === SCENE_STATE_AFTER && durationChanged || _state === SCENE_STATE_DURING && _options.duration === 0) {
// if [duration changed after a scene (inside scene progress updates pin position)] or [duration is 0, we are in pin phase and some other value changed].
updatePinState();
}
if (durationChanged) {
updatePinDimensions();
}
}).on("progress.internal", function (e) {
updatePinState();
}).on("add.internal", function (e) {
updatePinDimensions();
}).on("destroy.internal", function (e) {
Scene.removePin(e.reset);
});
/**
* Update the pin state.
* @private
*/
var updatePinState = function updatePinState(forceUnpin) {
if (_pin && _controller) {
var
containerInfo = _controller.info(),
pinTarget = _pinOptions.spacer.firstChild; // may be pin element or another spacer, if cascading pins
if (!forceUnpin && _state === SCENE_STATE_DURING) {// during scene or if duration is 0 and we are past the trigger
// pinned state
if (_util.css(pinTarget, "position") != "fixed") {
// change state before updating pin spacer (position changes due to fixed collapsing might occur.)
_util.css(pinTarget, {
"position": "fixed" });
// update pin spacer
updatePinDimensions();
}
var
fixedPos = _util.get.offset(_pinOptions.spacer, true),
// get viewport position of spacer
scrollDistance = _options.reverse || _options.duration === 0 ? containerInfo.scrollPos - _scrollOffset.start // quicker
: Math.round(_progress * _options.duration * 10) / 10; // if no reverse and during pin the position needs to be recalculated using the progress
// add scrollDistance
fixedPos[containerInfo.vertical ? "top" : "left"] += scrollDistance;
// set new values
_util.css(_pinOptions.spacer.firstChild, {
top: fixedPos.top,
left: fixedPos.left });
} else {
// unpinned state
var
newCSS = {
position: _pinOptions.inFlow ? "relative" : "absolute",
top: 0,
left: 0 },
change = _util.css(pinTarget, "position") != newCSS.position;
if (!_pinOptions.pushFollowers) {
newCSS[containerInfo.vertical ? "top" : "left"] = _options.duration * _progress;
} else if (_options.duration > 0) {// only concerns scenes with duration
if (_state === SCENE_STATE_AFTER && parseFloat(_util.css(_pinOptions.spacer, "padding-top")) === 0) {
change = true; // if in after state but havent updated spacer yet (jumped past pin)
} else if (_state === SCENE_STATE_BEFORE && parseFloat(_util.css(_pinOptions.spacer, "padding-bottom")) === 0) {// before
change = true; // jumped past fixed state upward direction
}
}
// set new values
_util.css(pinTarget, newCSS);
if (change) {
// update pin spacer if state changed
updatePinDimensions();
}
}
}
};
/**
* Update the pin spacer and/or element size.
* The size of the spacer needs to be updated whenever the duration of the scene changes, if it is to push down following elements.
* @private
*/
var updatePinDimensions = function updatePinDimensions() {
if (_pin && _controller && _pinOptions.inFlow) {// no spacerresize, if original position is absolute
var
after = _state === SCENE_STATE_AFTER,
before = _state === SCENE_STATE_BEFORE,
during = _state === SCENE_STATE_DURING,
vertical = _controller.info("vertical"),
pinTarget = _pinOptions.spacer.firstChild,
// usually the pined element but can also be another spacer (cascaded pins)
marginCollapse = _util.isMarginCollapseType(_util.css(_pinOptions.spacer, "display")),
css = {};
// set new size
// if relsize: spacer -> pin | else: pin -> spacer
if (_pinOptions.relSize.width || _pinOptions.relSize.autoFullWidth) {
if (during) {
_util.css(_pin, {
"width": _util.get.width(_pinOptions.spacer) });
} else {
_util.css(_pin, {
"width": "100%" });
}
} else {
// minwidth is needed for cascaded pins.
css["min-width"] = _util.get.width(vertical ? _pin : pinTarget, true, true);
css.width = during ? css["min-width"] : "auto";
}
if (_pinOptions.relSize.height) {
if (during) {
// the only padding the spacer should ever include is the duration (if pushFollowers = true), so we need to substract that.
_util.css(_pin, {
"height": _util.get.height(_pinOptions.spacer) - (_pinOptions.pushFollowers ? _options.duration : 0) });
} else {
_util.css(_pin, {
"height": "100%" });
}
} else {
// margin is only included if it's a cascaded pin to resolve an IE9 bug
css["min-height"] = _util.get.height(vertical ? pinTarget : _pin, true, !marginCollapse); // needed for cascading pins
css.height = during ? css["min-height"] : "auto";
}
// add space for duration if pushFollowers is true
if (_pinOptions.pushFollowers) {
css["padding" + (vertical ? "Top" : "Left")] = _options.duration * _progress;
css["padding" + (vertical ? "Bottom" : "Right")] = _options.duration * (1 - _progress);
}
_util.css(_pinOptions.spacer, css);
}
};
/**
* Updates the Pin state (in certain scenarios)
* If the controller container is not the document and we are mid-pin-phase scrolling or resizing the main document can result to wrong pin positions.
* So this function is called on resize and scroll of the document.
* @private
*/
var updatePinInContainer = function updatePinInContainer() {
if (_controller && _pin && _state === SCENE_STATE_DURING && !_controller.info("isDocument")) {
updatePinState();
}
};
/**
* Updates the Pin spacer size state (in certain scenarios)
* If container is resized during pin and relatively sized the size of the pin might need to be updated...
* So this function is called on resize of the container.
* @private
*/
var updateRelativePinSpacer = function updateRelativePinSpacer() {
if (_controller && _pin && // well, duh
_state === SCENE_STATE_DURING && ( // element in pinned state?
// is width or height relatively sized, but not in relation to body? then we need to recalc.
(_pinOptions.relSize.width || _pinOptions.relSize.autoFullWidth) && _util.get.width(window) != _util.get.width(_pinOptions.spacer.parentNode) || _pinOptions.relSize.height && _util.get.height(window) != _util.get.height(_pinOptions.spacer.parentNode))) {
updatePinDimensions();
}
};
/**
* Is called, when the mousewhel is used while over a pinned element inside a div container.
* If the scene is in fixed state scroll events would be counted towards the body. This forwards the event to the scroll container.
* @private
*/
var onMousewheelOverPin = function onMousewheelOverPin(e) {
if (_controller && _pin && _state === SCENE_STATE_DURING && !_controller.info("isDocument")) {// in pin state
e.preventDefault();
_controller._setScrollPos(_controller.info("scrollPos") - ((e.wheelDelta || e[_controller.info("vertical") ? "wheelDeltaY" : "wheelDeltaX"]) / 3 || -e.detail * 30));
}
};
/**
* Pin an element for the duration of the tween.
* If the scene duration is 0 the element will only be unpinned, if the user scrolls back past the start position.
* Make sure only one pin is applied to an element at the same time.
* An element can be pinned multiple times, but only successively.
* _**NOTE:** The option `pushFollowers` has no effect, when the scene duration is 0._
* @method ScrollMagic.Scene#setPin
* @example
* // pin element and push all following elements down by the amount of the pin duration.
* scene.setPin("#pin");
*
* // pin element and keeping all following elements in their place. The pinned element will move past them.
* scene.setPin("#pin", {pushFollowers: false});
*
* @param {(string|object)} element - A Selector targeting an element or a DOM object that is supposed to be pinned.
* @param {object} [settings] - settings for the pin
* @param {boolean} [settings.pushFollowers=true] - If `true` following elements will be "pushed" down for the duration of the pin, if `false` the pinned element will just scroll past them.
Ignored, when duration is `0`.
* @param {string} [settings.spacerClass="scrollmagic-pin-spacer"] - Classname of the pin spacer element, which is used to replace the element.
*
* @returns {Scene} Parent object for chaining.
*/
this.setPin = function (element, settings) {
var
defaultSettings = {
pushFollowers: true,
spacerClass: "scrollmagic-pin-spacer" };
settings = _util.extend({}, defaultSettings, settings);
// validate Element
element = _util.get.elements(element)[0];
if (!element) {
log(1, "ERROR calling method 'setPin()': Invalid pin element supplied.");
return Scene; // cancel
} else if (_util.css(element, "position") === "fixed") {
log(1, "ERROR calling method 'setPin()': Pin does not work with elements that are positioned 'fixed'.");
return Scene; // cancel
}
if (_pin) {// preexisting pin?
if (_pin === element) {
// same pin we already have -> do nothing
return Scene; // cancel
} else {
// kill old pin
Scene.removePin();
}
}
_pin = element;
var
parentDisplay = _pin.parentNode.style.display,
boundsParams = ["top", "left", "bottom", "right", "margin", "marginLeft", "marginRight", "marginTop", "marginBottom"];
_pin.parentNode.style.display = 'none'; // hack start to force css to return stylesheet values instead of calculated px values.
var
inFlow = _util.css(_pin, "position") != "absolute",
pinCSS = _util.css(_pin, boundsParams.concat(["display"])),
sizeCSS = _util.css(_pin, ["width", "height"]);
_pin.parentNode.style.display = parentDisplay; // hack end.
if (!inFlow && settings.pushFollowers) {
log(2, "WARNING: If the pinned element is positioned absolutely pushFollowers will be disabled.");
settings.pushFollowers = false;
}
window.setTimeout(function () {// wait until all finished, because with responsive duration it will only be set after scene is added to controller
if (_pin && _options.duration === 0 && settings.pushFollowers) {
log(2, "WARNING: pushFollowers =", true, "has no effect, when scene duration is 0.");
}
}, 0);
// create spacer and insert
var
spacer = _pin.parentNode.insertBefore(document.createElement('div'), _pin),
spacerCSS = _util.extend(pinCSS, {
position: inFlow ? "relative" : "absolute",
boxSizing: "content-box",
mozBoxSizing: "content-box",
webkitBoxSizing: "content-box" });
if (!inFlow) {// copy size if positioned absolutely, to work for bottom/right positioned elements.
_util.extend(spacerCSS, _util.css(_pin, ["width", "height"]));
}
_util.css(spacer, spacerCSS);
spacer.setAttribute(PIN_SPACER_ATTRIBUTE, "");
_util.addClass(spacer, settings.spacerClass);
// set the pin Options
_pinOptions = {
spacer: spacer,
relSize: { // save if size is defined using % values. if so, handle spacer resize differently...
width: sizeCSS.width.slice(-1) === "%",
height: sizeCSS.height.slice(-1) === "%",
autoFullWidth: sizeCSS.width === "auto" && inFlow && _util.isMarginCollapseType(pinCSS.display) },
pushFollowers: settings.pushFollowers,
inFlow: inFlow
// stores if the element takes up space in the document flow
};
if (!_pin.___origStyle) {
_pin.___origStyle = {};
var
pinInlineCSS = _pin.style,
copyStyles = boundsParams.concat(["width", "height", "position", "boxSizing", "mozBoxSizing", "webkitBoxSizing"]);
copyStyles.forEach(function (val) {
_pin.___origStyle[val] = pinInlineCSS[val] || "";
});
}
// if relative size, transfer it to spacer and make pin calculate it...
if (_pinOptions.relSize.width) {
_util.css(spacer, {
width: sizeCSS.width });
}
if (_pinOptions.relSize.height) {
_util.css(spacer, {
height: sizeCSS.height });
}
// now place the pin element inside the spacer
spacer.appendChild(_pin);
// and set new css
_util.css(_pin, {
position: inFlow ? "relative" : "absolute",
margin: "auto",
top: "auto",
left: "auto",
bottom: "auto",
right: "auto" });
if (_pinOptions.relSize.width || _pinOptions.relSize.autoFullWidth) {
_util.css(_pin, {
boxSizing: "border-box",
mozBoxSizing: "border-box",
webkitBoxSizing: "border-box" });
}
// add listener to document to update pin position in case controller is not the document.
window.addEventListener('scroll', updatePinInContainer);
window.addEventListener('resize', updatePinInContainer);
window.addEventListener('resize', updateRelativePinSpacer);
// add mousewheel listener to catch scrolls over fixed elements
_pin.addEventListener("mousewheel", onMousewheelOverPin);
_pin.addEventListener("DOMMouseScroll", onMousewheelOverPin);
log(3, "added pin");
// finally update the pin to init
updatePinState();
return Scene;
};
/**
* Remove the pin from the scene.
* @method ScrollMagic.Scene#removePin
* @example
* // remove the pin from the scene without resetting it (the spacer is not removed)
* scene.removePin();
*
* // remove the pin from the scene and reset the pin element to its initial position (spacer is removed)
* scene.removePin(true);
*
* @param {boolean} [reset=false] - If `false` the spacer will not be removed and the element's position will not be reset.
* @returns {Scene} Parent object for chaining.
*/
this.removePin = function (reset) {
if (_pin) {
if (_state === SCENE_STATE_DURING) {
updatePinState(true); // force unpin at position
}
if (reset || !_controller) {// if there's no controller no progress was made anyway...
var pinTarget = _pinOptions.spacer.firstChild; // usually the pin element, but may be another spacer (cascaded pins)...
if (pinTarget.hasAttribute(PIN_SPACER_ATTRIBUTE)) {// copy margins to child spacer
var
style = _pinOptions.spacer.style,
values = ["margin", "marginLeft", "marginRight", "marginTop", "marginBottom"];
margins = {};
values.forEach(function (val) {
margins[val] = style[val] || "";
});
_util.css(pinTarget, margins);
}
_pinOptions.spacer.parentNode.insertBefore(pinTarget, _pinOptions.spacer);
_pinOptions.spacer.parentNode.removeChild(_pinOptions.spacer);
if (!_pin.parentNode.hasAttribute(PIN_SPACER_ATTRIBUTE)) {// if it's the last pin for this element -> restore inline styles
// TODO: only correctly set for first pin (when cascading) - how to fix?
_util.css(_pin, _pin.___origStyle);
delete _pin.___origStyle;
}
}
window.removeEventListener('scroll', updatePinInContainer);
window.removeEventListener('resize', updatePinInContainer);
window.removeEventListener('resize', updateRelativePinSpacer);
_pin.removeEventListener("mousewheel", onMousewheelOverPin);
_pin.removeEventListener("DOMMouseScroll", onMousewheelOverPin);
_pin = undefined;
log(3, "removed pin (reset: " + (reset ? "true" : "false") + ")");
}
return Scene;
};
var
_cssClasses,_cssClassElems = [];
Scene.on("destroy.internal", function (e) {
Scene.removeClassToggle(e.reset);
});
/**
* Define a css class modification while the scene is active.
* When the scene triggers the classes will be added to the supplied element and removed, when the scene is over.
* If the scene duration is 0 the classes will only be removed if the user scrolls back past the start position.
* @method ScrollMagic.Scene#setClassToggle
* @example
* // add the class 'myclass' to the element with the id 'my-elem' for the duration of the scene
* scene.setClassToggle("#my-elem", "myclass");
*
* // add multiple classes to multiple elements defined by the selector '.classChange'
* scene.setClassToggle(".classChange", "class1 class2 class3");
*
* @param {(string|object)} element - A Selector targeting one or more elements or a DOM object that is supposed to be modified.
* @param {string} classes - One or more Classnames (separated by space) that should be added to the element during the scene.
*
* @returns {Scene} Parent object for chaining.
*/
this.setClassToggle = function (element, classes) {
var elems = _util.get.elements(element);
if (elems.length === 0 || !_util.type.String(classes)) {
log(1, "ERROR calling method 'setClassToggle()': Invalid " + (elems.length === 0 ? "element" : "classes") + " supplied.");
return Scene;
}
if (_cssClassElems.length > 0) {
// remove old ones
Scene.removeClassToggle();
}
_cssClasses = classes;
_cssClassElems = elems;
Scene.on("enter.internal_class leave.internal_class", function (e) {
var toggle = e.type === "enter" ? _util.addClass : _util.removeClass;
_cssClassElems.forEach(function (elem, key) {
toggle(elem, _cssClasses);
});
});
return Scene;
};
/**
* Remove the class binding from the scene.
* @method ScrollMagic.Scene#removeClassToggle
* @example
* // remove class binding from the scene without reset
* scene.removeClassToggle();
*
* // remove class binding and remove the changes it caused
* scene.removeClassToggle(true);
*
* @param {boolean} [reset=false] - If `false` and the classes are currently active, they will remain on the element. If `true` they will be removed.
* @returns {Scene} Parent object for chaining.
*/
this.removeClassToggle = function (reset) {
if (reset) {
_cssClassElems.forEach(function (elem, key) {
_util.removeClass(elem, _cssClasses);
});
}
Scene.off("start.internal_class end.internal_class");
_cssClasses = undefined;
_cssClassElems = [];
return Scene;
};
// INIT
construct();
return Scene;
};
// store pagewide scene options
var SCENE_OPTIONS = {
defaults: {
duration: 0,
offset: 0,
triggerElement: undefined,
triggerHook: 0.5,
reverse: true,
loglevel: 2 },
validate: {
offset: function offset(val) {
val = parseFloat(val);
if (!_util.type.Number(val)) {
throw ["Invalid value for option \"offset\":", val];
}
return val;
},
triggerElement: function triggerElement(val) {
val = val || undefined;
if (val) {
var elem = _util.get.elements(val)[0];
if (elem) {
val = elem;
} else {
throw ["Element defined in option \"triggerElement\" was not found:", val];
}
}
return val;
},
triggerHook: function triggerHook(val) {
var translate = {
"onCenter": 0.5,
"onEnter": 1,
"onLeave": 0 };
if (_util.type.Number(val)) {
val = Math.max(0, Math.min(parseFloat(val), 1)); // make sure its betweeen 0 and 1
} else if (val in translate) {
val = translate[val];
} else {
throw ["Invalid value for option \"triggerHook\": ", val];
}
return val;
},
reverse: function reverse(val) {
return !!val; // force boolean
},
loglevel: function loglevel(val) {
val = parseInt(val);
if (!_util.type.Number(val) || val < 0 || val > 3) {
throw ["Invalid value for option \"loglevel\":", val];
}
return val;
} },
// holder for validation methods. duration validation is handled in 'getters-setters.js'
shifts: ["duration", "offset", "triggerHook"]
// list of options that trigger a `shift` event
};
/*
* method used to add an option to ScrollMagic Scenes.
* TODO: DOC (private for dev)
*/
ScrollMagic.Scene.addOption = function (name, defaultValue, validationCallback, shifts) {
if (!(name in SCENE_OPTIONS.defaults)) {
SCENE_OPTIONS.defaults[name] = defaultValue;
SCENE_OPTIONS.validate[name] = validationCallback;
if (shifts) {
SCENE_OPTIONS.shifts.push(name);
}
} else {
ScrollMagic._util.log(1, "[static] ScrollMagic.Scene -> Cannot add Scene option '" + name + "', because it already exists.");
}
};
// instance extension function for plugins
// TODO: DOC (private for dev)
ScrollMagic.Scene.extend = function (extension) {
var oldClass = this;
ScrollMagic.Scene = function () {
oldClass.apply(this, arguments);
this.$super = _util.extend({}, this); // copy parent state
return extension.apply(this, arguments) || this;
};
_util.extend(ScrollMagic.Scene, oldClass); // copy properties
ScrollMagic.Scene.prototype = oldClass.prototype; // copy prototype
ScrollMagic.Scene.prototype.constructor = ScrollMagic.Scene; // restore constructor
};
/**
* TODO: DOCS (private for dev)
* @class
* @private
*/
ScrollMagic.Event = function (type, namespace, target, vars) {
vars = vars || {};
for (var key in vars) {
this[key] = vars[key];
}
this.type = type;
this.target = this.currentTarget = target;
this.namespace = namespace || '';
this.timeStamp = this.timestamp = Date.now();
return this;
};
/*
* TODO: DOCS (private for dev)
*/
var _util = ScrollMagic._util = function (window) {
var U = {},
i;
/**
* ------------------------------
* internal helpers
* ------------------------------
*/
// parse float and fall back to 0.
var floatval = function floatval(number) {
return parseFloat(number) || 0;
};
// get current style IE safe (otherwise IE would return calculated values for 'auto')
var _getComputedStyle = function _getComputedStyle(elem) {
return elem.currentStyle ? elem.currentStyle : window.getComputedStyle(elem);
};
// get element dimension (width or height)
var _dimension = function _dimension(which, elem, outer, includeMargin) {
elem = elem === document ? window : elem;
if (elem === window) {
includeMargin = false;
} else if (!_type.DomElement(elem)) {
return 0;
}
which = which.charAt(0).toUpperCase() + which.substr(1).toLowerCase();
var dimension = (outer ? elem['offset' + which] || elem['outer' + which] : elem['client' + which] || elem['inner' + which]) || 0;
if (outer && includeMargin) {
var style = _getComputedStyle(elem);
dimension += which === 'Height' ? floatval(style.marginTop) + floatval(style.marginBottom) : floatval(style.marginLeft) + floatval(style.marginRight);
}
return dimension;
};
// converts 'margin-top' into 'marginTop'
var _camelCase = function _camelCase(str) {
return str.replace(/^[^a-z]+([a-z])/g, '$1').replace(/-([a-z])/g, function (g) {
return g[1].toUpperCase();
});
};
/**
* ------------------------------
* external helpers
* ------------------------------
*/
// extend obj – same as jQuery.extend({}, objA, objB)
U.extend = function (obj) {
obj = obj || {};
for (i = 1; i < arguments.length; i++) {
if (!arguments[i]) {
continue;
}
for (var key in arguments[i]) {
if (arguments[i].hasOwnProperty(key)) {
obj[key] = arguments[i][key];
}
}
}
return obj;
};
// check if a css display type results in margin-collapse or not
U.isMarginCollapseType = function (str) {
return ["block", "flex", "list-item", "table", "-webkit-box"].indexOf(str) > -1;
};
// implementation of requestAnimationFrame
// based on https://gist.github.com/paulirish/1579671
var
lastTime = 0,
vendors = ['ms', 'moz', 'webkit', 'o'];
var _requestAnimationFrame = window.requestAnimationFrame;
var _cancelAnimationFrame = window.cancelAnimationFrame;
// try vendor prefixes if the above doesn't work
for (i = 0; !_requestAnimationFrame && i < vendors.length; ++i) {
_requestAnimationFrame = window[vendors[i] + 'RequestAnimationFrame'];
_cancelAnimationFrame = window[vendors[i] + 'CancelAnimationFrame'] || window[vendors[i] + 'CancelRequestAnimationFrame'];
}
// fallbacks
if (!_requestAnimationFrame) {
_requestAnimationFrame = function _requestAnimationFrame(callback) {
var
currTime = new Date().getTime(),
timeToCall = Math.max(0, 16 - (currTime - lastTime)),
id = window.setTimeout(function () {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!_cancelAnimationFrame) {
_cancelAnimationFrame = function _cancelAnimationFrame(id) {
window.clearTimeout(id);
};
}
U.rAF = _requestAnimationFrame.bind(window);
U.cAF = _cancelAnimationFrame.bind(window);
var
loglevels = ["error", "warn", "log"],
console = window.console || {};
console.log = console.log ||
function () {}; // no console log, well - do nothing then...
// make sure methods for all levels exist.
for (i = 0; i < loglevels.length; i++) {
var method = loglevels[i];
if (!console[method]) {
console[method] = console.log; // prefer .log over nothing
}
}
U.log = function (loglevel) {
if (loglevel > loglevels.length || loglevel <= 0) loglevel = loglevels.length;
var now = new Date(),
time = ("0" + now.getHours()).slice(-2) + ":" + ("0" + now.getMinutes()).slice(-2) + ":" + ("0" + now.getSeconds()).slice(-2) + ":" + ("00" + now.getMilliseconds()).slice(-3),
method = loglevels[loglevel - 1],
args = Array.prototype.splice.call(arguments, 1),
func = Function.prototype.bind.call(console[method], console);
args.unshift(time);
func.apply(console, args);
};
/**
* ------------------------------
* type testing
* ------------------------------
*/
var _type = U.type = function (v) {
return Object.prototype.toString.call(v).replace(/^\[object (.+)\]$/, "$1").toLowerCase();
};
_type.String = function (v) {
return _type(v) === 'string';
};
_type.Function = function (v) {
return _type(v) === 'function';
};
_type.Array = function (v) {
return Array.isArray(v);
};
_type.Number = function (v) {
return !_type.Array(v) && v - parseFloat(v) + 1 >= 0;
};
_type.DomElement = function (o) {
return (
(typeof HTMLElement === 'undefined' ? 'undefined' : _typeof(HTMLElement)) === "object" ? o instanceof HTMLElement : //DOM2
o && (typeof o === 'undefined' ? 'undefined' : _typeof(o)) === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName === "string");
};
/**
* ------------------------------
* DOM Element info
* ------------------------------
*/
// always returns a list of matching DOM elements, from a selector, a DOM element or an list of elements or even an array of selectors
var _get = U.get = {};
_get.elements = function (selector) {
var arr = [];
if (_type.String(selector)) {
try {
selector = document.querySelectorAll(selector);
} catch (e) {// invalid selector
return arr;
}
}
if (_type(selector) === 'nodelist' || _type.Array(selector)) {
for (var i = 0, ref = arr.length = selector.length; i < ref; i++) {// list of elements
var elem = selector[i];
arr[i] = _type.DomElement(elem) ? elem : _get.elements(elem); // if not an element, try to resolve recursively
}
} else if (_type.DomElement(selector) || selector === document || selector === window) {
arr = [selector]; // only the element
}
return arr;
};
// get scroll top value
_get.scrollTop = function (elem) {
return elem && typeof elem.scrollTop === 'number' ? elem.scrollTop : window.pageYOffset || 0;
};
// get scroll left value
_get.scrollLeft = function (elem) {
return elem && typeof elem.scrollLeft === 'number' ? elem.scrollLeft : window.pageXOffset || 0;
};
// get element height
_get.width = function (elem, outer, includeMargin) {
return _dimension('width', elem, outer, includeMargin);
};
// get element width
_get.height = function (elem, outer, includeMargin) {
return _dimension('height', elem, outer, includeMargin);
};
// get element position (optionally relative to viewport)
_get.offset = function (elem, relativeToViewport) {
var offset = {
top: 0,
left: 0 };
if (elem && elem.getBoundingClientRect) {// check if available
var rect = elem.getBoundingClientRect();
offset.top = rect.top;
offset.left = rect.left;
if (!relativeToViewport) {// clientRect is by default relative to viewport...
offset.top += _get.scrollTop();
offset.left += _get.scrollLeft();
}
}
return offset;
};
/**
* ------------------------------
* DOM Element manipulation
* ------------------------------
*/
U.addClass = function (elem, classname) {
if (classname) {
if (elem.classList) elem.classList.add(classname);else
elem.className += ' ' + classname;
}
};
U.removeClass = function (elem, classname) {
if (classname) {
if (elem.classList) elem.classList.remove(classname);else
elem.className = elem.className.replace(new RegExp('(^|\\b)' + classname.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
}
};
// if options is string -> returns css value
// if options is array -> returns object with css value pairs
// if options is object -> set new css values
U.css = function (elem, options) {
if (_type.String(options)) {
return _getComputedStyle(elem)[_camelCase(options)];
} else if (_type.Array(options)) {
var
obj = {},
style = _getComputedStyle(elem);
options.forEach(function (option, key) {
obj[option] = style[_camelCase(option)];
});
return obj;
} else {
for (var option in options) {
var val = options[option];
if (val == parseFloat(val)) {// assume pixel for seemingly numerical values
val += 'px';
}
elem.style[_camelCase(option)] = val;
}
}
};
return U;
}(window || {});
ScrollMagic.Scene.prototype.addIndicators = function () {
ScrollMagic._util.log(1, '(ScrollMagic.Scene) -> ERROR calling addIndicators() due to missing Plugin \'debug.addIndicators\'. Please make sure to include plugins/debug.addIndicators.js');
return this;
};
ScrollMagic.Scene.prototype.removeIndicators = function () {
ScrollMagic._util.log(1, '(ScrollMagic.Scene) -> ERROR calling removeIndicators() due to missing Plugin \'debug.addIndicators\'. Please make sure to include plugins/debug.addIndicators.js');
return this;
};
ScrollMagic.Scene.prototype.setTween = function () {
ScrollMagic._util.log(1, '(ScrollMagic.Scene) -> ERROR calling setTween() due to missing Plugin \'animation.gsap\'. Please make sure to include plugins/animation.gsap.js');
return this;
};
ScrollMagic.Scene.prototype.removeTween = function () {
ScrollMagic._util.log(1, '(ScrollMagic.Scene) -> ERROR calling removeTween() due to missing Plugin \'animation.gsap\'. Please make sure to include plugins/animation.gsap.js');
return this;
};
ScrollMagic.Scene.prototype.setVelocity = function () {
ScrollMagic._util.log(1, '(ScrollMagic.Scene) -> ERROR calling setVelocity() due to missing Plugin \'animation.velocity\'. Please make sure to include plugins/animation.velocity.js');
return this;
};
ScrollMagic.Scene.prototype.removeVelocity = function () {
ScrollMagic._util.log(1, '(ScrollMagic.Scene) -> ERROR calling removeVelocity() due to missing Plugin \'animation.velocity\'. Please make sure to include plugins/animation.velocity.js');
return this;
};
return ScrollMagic;
});
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_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;}; /*!
* VERSION: 1.20.4
* DATE: 2018-02-15
* UPDATES AND DOCS AT: http://greensock.com
*
* Includes all of the following: TweenLite, TweenMax, TimelineLite, TimelineMax, EasePack, CSSPlugin, RoundPropsPlugin, BezierPlugin, AttrPlugin, DirectionalRotationPlugin
*
* @license Copyright (c) 2008-2018, GreenSock. All rights reserved.
* This work is subject to the terms at http://greensock.com/standard-license or for
* Club GreenSock members, the software agreement that was issued with your membership.
*
* @author: Jack Doyle, jack@greensock.com
**/
var _gsScope = typeof module !== "undefined" && module.exports && typeof global !== "undefined" ? global : undefined || window; //helps ensure compatibility with AMD/RequireJS and CommonJS/Node
(_gsScope._gsQueue || (_gsScope._gsQueue = [])).push(function () {
"use strict";
_gsScope._gsDefine("TweenMax", ["core.Animation", "core.SimpleTimeline", "TweenLite"], function (Animation, SimpleTimeline, TweenLite) {
var _slice = function _slice(a) {//don't use [].slice because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll()
var b = [],
l = a.length,
i;
for (i = 0; i !== l; b.push(a[i++])) {}
return b;
},
_applyCycle = function _applyCycle(vars, targets, i) {
var alt = vars.cycle,
p,val;
for (p in alt) {
val = alt[p];
vars[p] = typeof val === "function" ? val(i, targets[i]) : val[i % val.length];
}
delete vars.cycle;
},
TweenMax = function TweenMax(target, duration, vars) {
TweenLite.call(this, target, duration, vars);
this._cycle = 0;
this._yoyo = this.vars.yoyo === true || !!this.vars.yoyoEase;
this._repeat = this.vars.repeat || 0;
this._repeatDelay = this.vars.repeatDelay || 0;
if (this._repeat) {
this._uncache(true); //ensures that if there is any repeat, the totalDuration will get recalculated to accurately report it.
}
this.render = TweenMax.prototype.render; //speed optimization (avoid prototype lookup on this "hot" method)
},
_tinyNum = 0.0000000001,
TweenLiteInternals = TweenLite._internals,
_isSelector = TweenLiteInternals.isSelector,
_isArray = TweenLiteInternals.isArray,
p = TweenMax.prototype = TweenLite.to({}, 0.1, {}),
_blankArray = [];
TweenMax.version = "1.20.4";
p.constructor = TweenMax;
p.kill()._gc = false;
TweenMax.killTweensOf = TweenMax.killDelayedCallsTo = TweenLite.killTweensOf;
TweenMax.getTweensOf = TweenLite.getTweensOf;
TweenMax.lagSmoothing = TweenLite.lagSmoothing;
TweenMax.ticker = TweenLite.ticker;
TweenMax.render = TweenLite.render;
p.invalidate = function () {
this._yoyo = this.vars.yoyo === true || !!this.vars.yoyoEase;
this._repeat = this.vars.repeat || 0;
this._repeatDelay = this.vars.repeatDelay || 0;
this._yoyoEase = null;
this._uncache(true);
return TweenLite.prototype.invalidate.call(this);
};
p.updateTo = function (vars, resetDuration) {
var curRatio = this.ratio,
immediate = this.vars.immediateRender || vars.immediateRender,
p;
if (resetDuration && this._startTime < this._timeline._time) {
this._startTime = this._timeline._time;
this._uncache(false);
if (this._gc) {
this._enabled(true, false);
} else {
this._timeline.insert(this, this._startTime - this._delay); //ensures that any necessary re-sequencing of Animations in the timeline occurs to make sure the rendering order is correct.
}
}
for (p in vars) {
this.vars[p] = vars[p];
}
if (this._initted || immediate) {
if (resetDuration) {
this._initted = false;
if (immediate) {
this.render(0, true, true);
}
} else {
if (this._gc) {
this._enabled(true, false);
}
if (this._notifyPluginsOfEnabled && this._firstPT) {
TweenLite._onPluginEvent("_onDisable", this); //in case a plugin like MotionBlur must perform some cleanup tasks
}
if (this._time / this._duration > 0.998) {//if the tween has finished (or come extremely close to finishing), we just need to rewind it to 0 and then render it again at the end which forces it to re-initialize (parsing the new vars). We allow tweens that are close to finishing (but haven't quite finished) to work this way too because otherwise, the values are so small when determining where to project the starting values that binary math issues creep in and can make the tween appear to render incorrectly when run backwards.
var prevTime = this._totalTime;
this.render(0, true, false);
this._initted = false;
this.render(prevTime, true, false);
} else {
this._initted = false;
this._init();
if (this._time > 0 || immediate) {
var inv = 1 / (1 - curRatio),
pt = this._firstPT,endValue;
while (pt) {
endValue = pt.s + pt.c;
pt.c *= inv;
pt.s = endValue - pt.c;
pt = pt._next;
}
}
}
}
}
return this;
};
p.render = function (time, suppressEvents, force) {
if (!this._initted) if (this._duration === 0 && this.vars.repeat) {//zero duration tweens that render immediately have render() called from TweenLite's constructor, before TweenMax's constructor has finished setting _repeat, _repeatDelay, and _yoyo which are critical in determining totalDuration() so we need to call invalidate() which is a low-kb way to get those set properly.
this.invalidate();
}
var totalDur = !this._dirty ? this._totalDuration : this.totalDuration(),
prevTime = this._time,
prevTotalTime = this._totalTime,
prevCycle = this._cycle,
duration = this._duration,
prevRawPrevTime = this._rawPrevTime,
isComplete,callback,pt,cycleDuration,r,type,pow,rawPrevTime,yoyoEase;
if (time >= totalDur - 0.0000001 && time >= 0) {//to work around occasional floating point math artifacts.
this._totalTime = totalDur;
this._cycle = this._repeat;
if (this._yoyo && (this._cycle & 1) !== 0) {
this._time = 0;
this.ratio = this._ease._calcEnd ? this._ease.getRatio(0) : 0;
} else {
this._time = duration;
this.ratio = this._ease._calcEnd ? this._ease.getRatio(1) : 1;
}
if (!this._reversed) {
isComplete = true;
callback = "onComplete";
force = force || this._timeline.autoRemoveChildren; //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline.
}
if (duration === 0) if (this._initted || !this.vars.lazy || force) {//zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered.
if (this._startTime === this._timeline._duration) {//if a zero-duration tween is at the VERY end of a timeline and that timeline renders at its end, it will typically add a tiny bit of cushion to the render time to prevent rounding errors from getting in the way of tweens rendering their VERY end. If we then reverse() that timeline, the zero-duration tween will trigger its onReverseComplete even though technically the playhead didn't pass over it again. It's a very specific edge case we must accommodate.
time = 0;
}
if (prevRawPrevTime < 0 || time <= 0 && time >= -0.0000001 || prevRawPrevTime === _tinyNum && this.data !== "isPause") if (prevRawPrevTime !== time) {//note: when this.data is "isPause", it's a callback added by addPause() on a timeline that we should not be triggered when LEAVING its exact start time. In other words, tl.addPause(1).play(1) shouldn't pause.
force = true;
if (prevRawPrevTime > _tinyNum) {
callback = "onReverseComplete";
}
}
this._rawPrevTime = rawPrevTime = !suppressEvents || time || prevRawPrevTime === time ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
}
} else if (time < 0.0000001) {//to work around occasional floating point math artifacts, round super small values to 0.
this._totalTime = this._time = this._cycle = 0;
this.ratio = this._ease._calcEnd ? this._ease.getRatio(0) : 0;
if (prevTotalTime !== 0 || duration === 0 && prevRawPrevTime > 0) {
callback = "onReverseComplete";
isComplete = this._reversed;
}
if (time < 0) {
this._active = false;
if (duration === 0) if (this._initted || !this.vars.lazy || force) {//zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered.
if (prevRawPrevTime >= 0) {
force = true;
}
this._rawPrevTime = rawPrevTime = !suppressEvents || time || prevRawPrevTime === time ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
}
}
if (!this._initted) {//if we render the very beginning (time == 0) of a fromTo(), we must force the render (normal tweens wouldn't need to render at a time of 0 when the prevTime was also 0). This is also mandatory to make sure overwriting kicks in immediately.
force = true;
}
} else {
this._totalTime = this._time = time;
if (this._repeat !== 0) {
cycleDuration = duration + this._repeatDelay;
this._cycle = this._totalTime / cycleDuration >> 0; //originally _totalTime % cycleDuration but floating point errors caused problems, so I normalized it. (4 % 0.8 should be 0 but some browsers report it as 0.79999999!)
if (this._cycle !== 0) if (this._cycle === this._totalTime / cycleDuration && prevTotalTime <= time) {
this._cycle--; //otherwise when rendered exactly at the end time, it will act as though it is repeating (at the beginning)
}
this._time = this._totalTime - this._cycle * cycleDuration;
if (this._yoyo) if ((this._cycle & 1) !== 0) {
this._time = duration - this._time;
yoyoEase = this._yoyoEase || this.vars.yoyoEase; //note: we don't set this._yoyoEase in _init() like we do other properties because it's TweenMax-specific and doing it here allows us to optimize performance (most tweens don't have a yoyoEase). Note that we also must skip the this.ratio calculation further down right after we _init() in this function, because we're doing it here.
if (yoyoEase) {
if (!this._yoyoEase) {
if (yoyoEase === true && !this._initted) {//if it's not initted and yoyoEase is true, this._ease won't have been populated yet so we must discern it here.
yoyoEase = this.vars.ease;
this._yoyoEase = yoyoEase = !yoyoEase ? TweenLite.defaultEase : yoyoEase instanceof Ease ? yoyoEase : typeof yoyoEase === "function" ? new Ease(yoyoEase, this.vars.easeParams) : Ease.map[yoyoEase] || TweenLite.defaultEase;
} else {
this._yoyoEase = yoyoEase = yoyoEase === true ? this._ease : yoyoEase instanceof Ease ? yoyoEase : Ease.map[yoyoEase];
}
}
this.ratio = yoyoEase ? 1 - yoyoEase.getRatio((duration - this._time) / duration) : 0;
}
}
if (this._time > duration) {
this._time = duration;
} else if (this._time < 0) {
this._time = 0;
}
}
if (this._easeType && !yoyoEase) {
r = this._time / duration;
type = this._easeType;
pow = this._easePower;
if (type === 1 || type === 3 && r >= 0.5) {
r = 1 - r;
}
if (type === 3) {
r *= 2;
}
if (pow === 1) {
r *= r;
} else if (pow === 2) {
r *= r * r;
} else if (pow === 3) {
r *= r * r * r;
} else if (pow === 4) {
r *= r * r * r * r;
}
if (type === 1) {
this.ratio = 1 - r;
} else if (type === 2) {
this.ratio = r;
} else if (this._time / duration < 0.5) {
this.ratio = r / 2;
} else {
this.ratio = 1 - r / 2;
}
} else if (!yoyoEase) {
this.ratio = this._ease.getRatio(this._time / duration);
}
}
if (prevTime === this._time && !force && prevCycle === this._cycle) {
if (prevTotalTime !== this._totalTime) if (this._onUpdate) if (!suppressEvents) {//so that onUpdate fires even during the repeatDelay - as long as the totalTime changed, we should trigger onUpdate.
this._callback("onUpdate");
}
return;
} else if (!this._initted) {
this._init();
if (!this._initted || this._gc) {//immediateRender tweens typically won't initialize until the playhead advances (_time is greater than 0) in order to ensure that overwriting occurs properly. Also, if all of the tweening properties have been overwritten (which would cause _gc to be true, as set in _init()), we shouldn't continue otherwise an onStart callback could be called for example.
return;
} else if (!force && this._firstPT && (this.vars.lazy !== false && this._duration || this.vars.lazy && !this._duration)) {//we stick it in the queue for rendering at the very end of the tick - this is a performance optimization because browsers invalidate styles and force a recalculation if you read, write, and then read style data (so it's better to read/read/read/write/write/write than read/write/read/write/read/write). The down side, of course, is that usually you WANT things to render immediately because you may have code running right after that which depends on the change. Like imagine running TweenLite.set(...) and then immediately after that, creating a nother tween that animates the same property to another value; the starting values of that 2nd tween wouldn't be accurate if lazy is true.
this._time = prevTime;
this._totalTime = prevTotalTime;
this._rawPrevTime = prevRawPrevTime;
this._cycle = prevCycle;
TweenLiteInternals.lazyTweens.push(this);
this._lazy = [time, suppressEvents];
return;
}
//_ease is initially set to defaultEase, so now that init() has run, _ease is set properly and we need to recalculate the ratio. Overall this is faster than using conditional logic earlier in the method to avoid having to set ratio twice because we only init() once but renderTime() gets called VERY frequently.
if (this._time && !isComplete && !yoyoEase) {
this.ratio = this._ease.getRatio(this._time / duration);
} else if (isComplete && this._ease._calcEnd && !yoyoEase) {
this.ratio = this._ease.getRatio(this._time === 0 ? 0 : 1);
}
}
if (this._lazy !== false) {
this._lazy = false;
}
if (!this._active) if (!this._paused && this._time !== prevTime && time >= 0) {
this._active = true; //so that if the user renders a tween (as opposed to the timeline rendering it), the timeline is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the tween already finished but the user manually re-renders it as halfway done.
}
if (prevTotalTime === 0) {
if (this._initted === 2 && time > 0) {
//this.invalidate();
this._init(); //will just apply overwriting since _initted of (2) means it was a from() tween that had immediateRender:true
}
if (this._startAt) {
if (time >= 0) {
this._startAt.render(time, true, force);
} else if (!callback) {
callback = "_dummyGS"; //if no callback is defined, use a dummy value just so that the condition at the end evaluates as true because _startAt should render AFTER the normal render loop when the time is negative. We could handle this in a more intuitive way, of course, but the render loop is the MOST important thing to optimize, so this technique allows us to avoid adding extra conditional logic in a high-frequency area.
}
}
if (this.vars.onStart) if (this._totalTime !== 0 || duration === 0) if (!suppressEvents) {
this._callback("onStart");
}
}
pt = this._firstPT;
while (pt) {
if (pt.f) {
pt.t[pt.p](pt.c * this.ratio + pt.s);
} else {
pt.t[pt.p] = pt.c * this.ratio + pt.s;
}
pt = pt._next;
}
if (this._onUpdate) {
if (time < 0) if (this._startAt && this._startTime) {//if the tween is positioned at the VERY beginning (_startTime 0) of its parent timeline, it's illegal for the playhead to go back further, so we should not render the recorded startAt values.
this._startAt.render(time, true, force); //note: for performance reasons, we tuck this conditional logic inside less traveled areas (most tweens don't have an onUpdate). We'd just have it at the end before the onComplete, but the values should be updated before any onUpdate is called, so we ALSO put it here and then if it's not called, we do so later near the onComplete.
}
if (!suppressEvents) if (this._totalTime !== prevTotalTime || callback) {
this._callback("onUpdate");
}
}
if (this._cycle !== prevCycle) if (!suppressEvents) if (!this._gc) if (this.vars.onRepeat) {
this._callback("onRepeat");
}
if (callback) if (!this._gc || force) {//check gc because there's a chance that kill() could be called in an onUpdate
if (time < 0 && this._startAt && !this._onUpdate && this._startTime) {//if the tween is positioned at the VERY beginning (_startTime 0) of its parent timeline, it's illegal for the playhead to go back further, so we should not render the recorded startAt values.
this._startAt.render(time, true, force);
}
if (isComplete) {
if (this._timeline.autoRemoveChildren) {
this._enabled(false, false);
}
this._active = false;
}
if (!suppressEvents && this.vars[callback]) {
this._callback(callback);
}
if (duration === 0 && this._rawPrevTime === _tinyNum && rawPrevTime !== _tinyNum) {//the onComplete or onReverseComplete could trigger movement of the playhead and for zero-duration tweens (which must discern direction) that land directly back on their start time, we don't want to fire again on the next render. Think of several addPause()'s in a timeline that forces the playhead to a certain spot, but what if it's already paused and another tween is tweening the "time" of the timeline? Each time it moves [forward] past that spot, it would move back, and since suppressEvents is true, it'd reset _rawPrevTime to _tinyNum so that when it begins again, the callback would fire (so ultimately it could bounce back and forth during that tween). Again, this is a very uncommon scenario, but possible nonetheless.
this._rawPrevTime = 0;
}
}
};
//---- STATIC FUNCTIONS -----------------------------------------------------------------------------------------------------------
TweenMax.to = function (target, duration, vars) {
return new TweenMax(target, duration, vars);
};
TweenMax.from = function (target, duration, vars) {
vars.runBackwards = true;
vars.immediateRender = vars.immediateRender != false;
return new TweenMax(target, duration, vars);
};
TweenMax.fromTo = function (target, duration, fromVars, toVars) {
toVars.startAt = fromVars;
toVars.immediateRender = toVars.immediateRender != false && fromVars.immediateRender != false;
return new TweenMax(target, duration, toVars);
};
TweenMax.staggerTo = TweenMax.allTo = function (targets, duration, vars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
stagger = stagger || 0;
var delay = 0,
a = [],
finalComplete = function finalComplete() {
if (vars.onComplete) {
vars.onComplete.apply(vars.onCompleteScope || this, arguments);
}
onCompleteAll.apply(onCompleteAllScope || vars.callbackScope || this, onCompleteAllParams || _blankArray);
},
cycle = vars.cycle,
fromCycle = vars.startAt && vars.startAt.cycle,
l,copy,i,p;
if (!_isArray(targets)) {
if (typeof targets === "string") {
targets = TweenLite.selector(targets) || targets;
}
if (_isSelector(targets)) {
targets = _slice(targets);
}
}
targets = targets || [];
if (stagger < 0) {
targets = _slice(targets);
targets.reverse();
stagger *= -1;
}
l = targets.length - 1;
for (i = 0; i <= l; i++) {
copy = {};
for (p in vars) {
copy[p] = vars[p];
}
if (cycle) {
_applyCycle(copy, targets, i);
if (copy.duration != null) {
duration = copy.duration;
delete copy.duration;
}
}
if (fromCycle) {
fromCycle = copy.startAt = {};
for (p in vars.startAt) {
fromCycle[p] = vars.startAt[p];
}
_applyCycle(copy.startAt, targets, i);
}
copy.delay = delay + (copy.delay || 0);
if (i === l && onCompleteAll) {
copy.onComplete = finalComplete;
}
a[i] = new TweenMax(targets[i], duration, copy);
delay += stagger;
}
return a;
};
TweenMax.staggerFrom = TweenMax.allFrom = function (targets, duration, vars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
vars.runBackwards = true;
vars.immediateRender = vars.immediateRender != false;
return TweenMax.staggerTo(targets, duration, vars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope);
};
TweenMax.staggerFromTo = TweenMax.allFromTo = function (targets, duration, fromVars, toVars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
toVars.startAt = fromVars;
toVars.immediateRender = toVars.immediateRender != false && fromVars.immediateRender != false;
return TweenMax.staggerTo(targets, duration, toVars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope);
};
TweenMax.delayedCall = function (delay, callback, params, scope, useFrames) {
return new TweenMax(callback, 0, { delay: delay, onComplete: callback, onCompleteParams: params, callbackScope: scope, onReverseComplete: callback, onReverseCompleteParams: params, immediateRender: false, useFrames: useFrames, overwrite: 0 });
};
TweenMax.set = function (target, vars) {
return new TweenMax(target, 0, vars);
};
TweenMax.isTweening = function (target) {
return TweenLite.getTweensOf(target, true).length > 0;
};
var _getChildrenOf = function _getChildrenOf(timeline, includeTimelines) {
var a = [],
cnt = 0,
tween = timeline._first;
while (tween) {
if (tween instanceof TweenLite) {
a[cnt++] = tween;
} else {
if (includeTimelines) {
a[cnt++] = tween;
}
a = a.concat(_getChildrenOf(tween, includeTimelines));
cnt = a.length;
}
tween = tween._next;
}
return a;
},
getAllTweens = TweenMax.getAllTweens = function (includeTimelines) {
return _getChildrenOf(Animation._rootTimeline, includeTimelines).concat(_getChildrenOf(Animation._rootFramesTimeline, includeTimelines));
};
TweenMax.killAll = function (complete, tweens, delayedCalls, timelines) {
if (tweens == null) {
tweens = true;
}
if (delayedCalls == null) {
delayedCalls = true;
}
var a = getAllTweens(timelines != false),
l = a.length,
allTrue = tweens && delayedCalls && timelines,
isDC,tween,i;
for (i = 0; i < l; i++) {
tween = a[i];
if (allTrue || tween instanceof SimpleTimeline || (isDC = tween.target === tween.vars.onComplete) && delayedCalls || tweens && !isDC) {
if (complete) {
tween.totalTime(tween._reversed ? 0 : tween.totalDuration());
} else {
tween._enabled(false, false);
}
}
}
};
TweenMax.killChildTweensOf = function (parent, complete) {
if (parent == null) {
return;
}
var tl = TweenLiteInternals.tweenLookup,
a,curParent,p,i,l;
if (typeof parent === "string") {
parent = TweenLite.selector(parent) || parent;
}
if (_isSelector(parent)) {
parent = _slice(parent);
}
if (_isArray(parent)) {
i = parent.length;
while (--i > -1) {
TweenMax.killChildTweensOf(parent[i], complete);
}
return;
}
a = [];
for (p in tl) {
curParent = tl[p].target.parentNode;
while (curParent) {
if (curParent === parent) {
a = a.concat(tl[p].tweens);
}
curParent = curParent.parentNode;
}
}
l = a.length;
for (i = 0; i < l; i++) {
if (complete) {
a[i].totalTime(a[i].totalDuration());
}
a[i]._enabled(false, false);
}
};
var _changePause = function _changePause(pause, tweens, delayedCalls, timelines) {
tweens = tweens !== false;
delayedCalls = delayedCalls !== false;
timelines = timelines !== false;
var a = getAllTweens(timelines),
allTrue = tweens && delayedCalls && timelines,
i = a.length,
isDC,tween;
while (--i > -1) {
tween = a[i];
if (allTrue || tween instanceof SimpleTimeline || (isDC = tween.target === tween.vars.onComplete) && delayedCalls || tweens && !isDC) {
tween.paused(pause);
}
}
};
TweenMax.pauseAll = function (tweens, delayedCalls, timelines) {
_changePause(true, tweens, delayedCalls, timelines);
};
TweenMax.resumeAll = function (tweens, delayedCalls, timelines) {
_changePause(false, tweens, delayedCalls, timelines);
};
TweenMax.globalTimeScale = function (value) {
var tl = Animation._rootTimeline,
t = TweenLite.ticker.time;
if (!arguments.length) {
return tl._timeScale;
}
value = value || _tinyNum; //can't allow zero because it'll throw the math off
tl._startTime = t - (t - tl._startTime) * tl._timeScale / value;
tl = Animation._rootFramesTimeline;
t = TweenLite.ticker.frame;
tl._startTime = t - (t - tl._startTime) * tl._timeScale / value;
tl._timeScale = Animation._rootTimeline._timeScale = value;
return value;
};
//---- GETTERS / SETTERS ----------------------------------------------------------------------------------------------------------
p.progress = function (value, suppressEvents) {
return !arguments.length ? this._time / this.duration() : this.totalTime(this.duration() * (this._yoyo && (this._cycle & 1) !== 0 ? 1 - value : value) + this._cycle * (this._duration + this._repeatDelay), suppressEvents);
};
p.totalProgress = function (value, suppressEvents) {
return !arguments.length ? this._totalTime / this.totalDuration() : this.totalTime(this.totalDuration() * value, suppressEvents);
};
p.time = function (value, suppressEvents) {
if (!arguments.length) {
return this._time;
}
if (this._dirty) {
this.totalDuration();
}
if (value > this._duration) {
value = this._duration;
}
if (this._yoyo && (this._cycle & 1) !== 0) {
value = this._duration - value + this._cycle * (this._duration + this._repeatDelay);
} else if (this._repeat !== 0) {
value += this._cycle * (this._duration + this._repeatDelay);
}
return this.totalTime(value, suppressEvents);
};
p.duration = function (value) {
if (!arguments.length) {
return this._duration; //don't set _dirty = false because there could be repeats that haven't been factored into the _totalDuration yet. Otherwise, if you create a repeated TweenMax and then immediately check its duration(), it would cache the value and the totalDuration would not be correct, thus repeats wouldn't take effect.
}
return Animation.prototype.duration.call(this, value);
};
p.totalDuration = function (value) {
if (!arguments.length) {
if (this._dirty) {
//instead of Infinity, we use 999999999999 so that we can accommodate reverses
this._totalDuration = this._repeat === -1 ? 999999999999 : this._duration * (this._repeat + 1) + this._repeatDelay * this._repeat;
this._dirty = false;
}
return this._totalDuration;
}
return this._repeat === -1 ? this : this.duration((value - this._repeat * this._repeatDelay) / (this._repeat + 1));
};
p.repeat = function (value) {
if (!arguments.length) {
return this._repeat;
}
this._repeat = value;
return this._uncache(true);
};
p.repeatDelay = function (value) {
if (!arguments.length) {
return this._repeatDelay;
}
this._repeatDelay = value;
return this._uncache(true);
};
p.yoyo = function (value) {
if (!arguments.length) {
return this._yoyo;
}
this._yoyo = value;
return this;
};
return TweenMax;
}, true);
/*
* ----------------------------------------------------------------
* TimelineLite
* ----------------------------------------------------------------
*/
_gsScope._gsDefine("TimelineLite", ["core.Animation", "core.SimpleTimeline", "TweenLite"], function (Animation, SimpleTimeline, TweenLite) {
var TimelineLite = function TimelineLite(vars) {
SimpleTimeline.call(this, vars);
this._labels = {};
this.autoRemoveChildren = this.vars.autoRemoveChildren === true;
this.smoothChildTiming = this.vars.smoothChildTiming === true;
this._sortChildren = true;
this._onUpdate = this.vars.onUpdate;
var v = this.vars,
val,p;
for (p in v) {
val = v[p];
if (_isArray(val)) if (val.join("").indexOf("{self}") !== -1) {
v[p] = this._swapSelfInParams(val);
}
}
if (_isArray(v.tweens)) {
this.add(v.tweens, 0, v.align, v.stagger);
}
},
_tinyNum = 0.0000000001,
TweenLiteInternals = TweenLite._internals,
_internals = TimelineLite._internals = {},
_isSelector = TweenLiteInternals.isSelector,
_isArray = TweenLiteInternals.isArray,
_lazyTweens = TweenLiteInternals.lazyTweens,
_lazyRender = TweenLiteInternals.lazyRender,
_globals = _gsScope._gsDefine.globals,
_copy = function _copy(vars) {
var copy = {},p;
for (p in vars) {
copy[p] = vars[p];
}
return copy;
},
_applyCycle = function _applyCycle(vars, targets, i) {
var alt = vars.cycle,
p,val;
for (p in alt) {
val = alt[p];
vars[p] = typeof val === "function" ? val(i, targets[i]) : val[i % val.length];
}
delete vars.cycle;
},
_pauseCallback = _internals.pauseCallback = function () {},
_slice = function _slice(a) {//don't use [].slice because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll()
var b = [],
l = a.length,
i;
for (i = 0; i !== l; b.push(a[i++])) {}
return b;
},
p = TimelineLite.prototype = new SimpleTimeline();
TimelineLite.version = "1.20.4";
p.constructor = TimelineLite;
p.kill()._gc = p._forcingPlayhead = p._hasPause = false;
/* might use later...
//translates a local time inside an animation to the corresponding time on the root/global timeline, factoring in all nesting and timeScales.
function localToGlobal(time, animation) {
while (animation) {
time = (time / animation._timeScale) + animation._startTime;
animation = animation.timeline;
}
return time;
}
//translates the supplied time on the root/global timeline into the corresponding local time inside a particular animation, factoring in all nesting and timeScales
function globalToLocal(time, animation) {
var scale = 1;
time -= localToGlobal(0, animation);
while (animation) {
scale *= animation._timeScale;
animation = animation.timeline;
}
return time * scale;
}
*/
p.to = function (target, duration, vars, position) {
var Engine = vars.repeat && _globals.TweenMax || TweenLite;
return duration ? this.add(new Engine(target, duration, vars), position) : this.set(target, vars, position);
};
p.from = function (target, duration, vars, position) {
return this.add((vars.repeat && _globals.TweenMax || TweenLite).from(target, duration, vars), position);
};
p.fromTo = function (target, duration, fromVars, toVars, position) {
var Engine = toVars.repeat && _globals.TweenMax || TweenLite;
return duration ? this.add(Engine.fromTo(target, duration, fromVars, toVars), position) : this.set(target, toVars, position);
};
p.staggerTo = function (targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
var tl = new TimelineLite({ onComplete: onCompleteAll, onCompleteParams: onCompleteAllParams, callbackScope: onCompleteAllScope, smoothChildTiming: this.smoothChildTiming }),
cycle = vars.cycle,
copy,i;
if (typeof targets === "string") {
targets = TweenLite.selector(targets) || targets;
}
targets = targets || [];
if (_isSelector(targets)) {//senses if the targets object is a selector. If it is, we should translate it into an array.
targets = _slice(targets);
}
stagger = stagger || 0;
if (stagger < 0) {
targets = _slice(targets);
targets.reverse();
stagger *= -1;
}
for (i = 0; i < targets.length; i++) {
copy = _copy(vars);
if (copy.startAt) {
copy.startAt = _copy(copy.startAt);
if (copy.startAt.cycle) {
_applyCycle(copy.startAt, targets, i);
}
}
if (cycle) {
_applyCycle(copy, targets, i);
if (copy.duration != null) {
duration = copy.duration;
delete copy.duration;
}
}
tl.to(targets[i], duration, copy, i * stagger);
}
return this.add(tl, position);
};
p.staggerFrom = function (targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
vars.immediateRender = vars.immediateRender != false;
vars.runBackwards = true;
return this.staggerTo(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope);
};
p.staggerFromTo = function (targets, duration, fromVars, toVars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
toVars.startAt = fromVars;
toVars.immediateRender = toVars.immediateRender != false && fromVars.immediateRender != false;
return this.staggerTo(targets, duration, toVars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope);
};
p.call = function (callback, params, scope, position) {
return this.add(TweenLite.delayedCall(0, callback, params, scope), position);
};
p.set = function (target, vars, position) {
position = this._parseTimeOrLabel(position, 0, true);
if (vars.immediateRender == null) {
vars.immediateRender = position === this._time && !this._paused;
}
return this.add(new TweenLite(target, 0, vars), position);
};
TimelineLite.exportRoot = function (vars, ignoreDelayedCalls) {
vars = vars || {};
if (vars.smoothChildTiming == null) {
vars.smoothChildTiming = true;
}
var tl = new TimelineLite(vars),
root = tl._timeline,
hasNegativeStart,time,tween,next;
if (ignoreDelayedCalls == null) {
ignoreDelayedCalls = true;
}
root._remove(tl, true);
tl._startTime = 0;
tl._rawPrevTime = tl._time = tl._totalTime = root._time;
tween = root._first;
while (tween) {
next = tween._next;
if (!ignoreDelayedCalls || !(tween instanceof TweenLite && tween.target === tween.vars.onComplete)) {
time = tween._startTime - tween._delay;
if (time < 0) {
hasNegativeStart = 1;
}
tl.add(tween, time);
}
tween = next;
}
root.add(tl, 0);
if (hasNegativeStart) {//calling totalDuration() will force the adjustment necessary to shift the children forward so none of them start before zero, and moves the timeline backwards the same amount, so the playhead is still aligned where it should be globally, but the timeline doesn't have illegal children that start before zero.
tl.totalDuration();
}
return tl;
};
p.add = function (value, position, align, stagger) {
var curTime, l, i, child, tl, beforeRawTime;
if (typeof position !== "number") {
position = this._parseTimeOrLabel(position, 0, true, value);
}
if (!(value instanceof Animation)) {
if (value instanceof Array || value && value.push && _isArray(value)) {
align = align || "normal";
stagger = stagger || 0;
curTime = position;
l = value.length;
for (i = 0; i < l; i++) {
if (_isArray(child = value[i])) {
child = new TimelineLite({ tweens: child });
}
this.add(child, curTime);
if (typeof child !== "string" && typeof child !== "function") {
if (align === "sequence") {
curTime = child._startTime + child.totalDuration() / child._timeScale;
} else if (align === "start") {
child._startTime -= child.delay();
}
}
curTime += stagger;
}
return this._uncache(true);
} else if (typeof value === "string") {
return this.addLabel(value, position);
} else if (typeof value === "function") {
value = TweenLite.delayedCall(0, value);
} else {
throw "Cannot add " + value + " into the timeline; it is not a tween, timeline, function, or string.";
}
}
SimpleTimeline.prototype.add.call(this, value, position);
if (value._time) {//in case, for example, the _startTime is moved on a tween that has already rendered. Imagine it's at its end state, then the startTime is moved WAY later (after the end of this timeline), it should render at its beginning.
value.render((this.rawTime() - value._startTime) * value._timeScale, false, false);
}
//if the timeline has already ended but the inserted tween/timeline extends the duration, we should enable this timeline again so that it renders properly. We should also align the playhead with the parent timeline's when appropriate.
if (this._gc || this._time === this._duration) if (!this._paused) if (this._duration < this.duration()) {
//in case any of the ancestors had completed but should now be enabled...
tl = this;
beforeRawTime = tl.rawTime() > value._startTime; //if the tween is placed on the timeline so that it starts BEFORE the current rawTime, we should align the playhead (move the timeline). This is because sometimes users will create a timeline, let it finish, and much later append a tween and expect it to run instead of jumping to its end state. While technically one could argue that it should jump to its end state, that's not what users intuitively expect.
while (tl._timeline) {
if (beforeRawTime && tl._timeline.smoothChildTiming) {
tl.totalTime(tl._totalTime, true); //moves the timeline (shifts its startTime) if necessary, and also enables it.
} else if (tl._gc) {
tl._enabled(true, false);
}
tl = tl._timeline;
}
}
return this;
};
p.remove = function (value) {
if (value instanceof Animation) {
this._remove(value, false);
var tl = value._timeline = value.vars.useFrames ? Animation._rootFramesTimeline : Animation._rootTimeline; //now that it's removed, default it to the root timeline so that if it gets played again, it doesn't jump back into this timeline.
value._startTime = (value._paused ? value._pauseTime : tl._time) - (!value._reversed ? value._totalTime : value.totalDuration() - value._totalTime) / value._timeScale; //ensure that if it gets played again, the timing is correct.
return this;
} else if (value instanceof Array || value && value.push && _isArray(value)) {
var i = value.length;
while (--i > -1) {
this.remove(value[i]);
}
return this;
} else if (typeof value === "string") {
return this.removeLabel(value);
}
return this.kill(null, value);
};
p._remove = function (tween, skipDisable) {
SimpleTimeline.prototype._remove.call(this, tween, skipDisable);
var last = this._last;
if (!last) {
this._time = this._totalTime = this._duration = this._totalDuration = 0;
} else if (this._time > this.duration()) {
this._time = this._duration;
this._totalTime = this._totalDuration;
}
return this;
};
p.append = function (value, offsetOrLabel) {
return this.add(value, this._parseTimeOrLabel(null, offsetOrLabel, true, value));
};
p.insert = p.insertMultiple = function (value, position, align, stagger) {
return this.add(value, position || 0, align, stagger);
};
p.appendMultiple = function (tweens, offsetOrLabel, align, stagger) {
return this.add(tweens, this._parseTimeOrLabel(null, offsetOrLabel, true, tweens), align, stagger);
};
p.addLabel = function (label, position) {
this._labels[label] = this._parseTimeOrLabel(position);
return this;
};
p.addPause = function (position, callback, params, scope) {
var t = TweenLite.delayedCall(0, _pauseCallback, params, scope || this);
t.vars.onComplete = t.vars.onReverseComplete = callback;
t.data = "isPause";
this._hasPause = true;
return this.add(t, position);
};
p.removeLabel = function (label) {
delete this._labels[label];
return this;
};
p.getLabelTime = function (label) {
return this._labels[label] != null ? this._labels[label] : -1;
};
p._parseTimeOrLabel = function (timeOrLabel, offsetOrLabel, appendIfAbsent, ignore) {
var clippedDuration, i;
//if we're about to add a tween/timeline (or an array of them) that's already a child of this timeline, we should remove it first so that it doesn't contaminate the duration().
if (ignore instanceof Animation && ignore.timeline === this) {
this.remove(ignore);
} else if (ignore && (ignore instanceof Array || ignore.push && _isArray(ignore))) {
i = ignore.length;
while (--i > -1) {
if (ignore[i] instanceof Animation && ignore[i].timeline === this) {
this.remove(ignore[i]);
}
}
}
clippedDuration = typeof timeOrLabel === "number" && !offsetOrLabel ? 0 : this.duration() > 99999999999 ? this.recent().endTime(false) : this._duration; //in case there's a child that infinitely repeats, users almost never intend for the insertion point of a new child to be based on a SUPER long value like that so we clip it and assume the most recently-added child's endTime should be used instead.
if (typeof offsetOrLabel === "string") {
return this._parseTimeOrLabel(offsetOrLabel, appendIfAbsent && typeof timeOrLabel === "number" && this._labels[offsetOrLabel] == null ? timeOrLabel - clippedDuration : 0, appendIfAbsent);
}
offsetOrLabel = offsetOrLabel || 0;
if (typeof timeOrLabel === "string" && (isNaN(timeOrLabel) || this._labels[timeOrLabel] != null)) {//if the string is a number like "1", check to see if there's a label with that name, otherwise interpret it as a number (absolute value).
i = timeOrLabel.indexOf("=");
if (i === -1) {
if (this._labels[timeOrLabel] == null) {
return appendIfAbsent ? this._labels[timeOrLabel] = clippedDuration + offsetOrLabel : offsetOrLabel;
}
return this._labels[timeOrLabel] + offsetOrLabel;
}
offsetOrLabel = parseInt(timeOrLabel.charAt(i - 1) + "1", 10) * Number(timeOrLabel.substr(i + 1));
timeOrLabel = i > 1 ? this._parseTimeOrLabel(timeOrLabel.substr(0, i - 1), 0, appendIfAbsent) : clippedDuration;
} else if (timeOrLabel == null) {
timeOrLabel = clippedDuration;
}
return Number(timeOrLabel) + offsetOrLabel;
};
p.seek = function (position, suppressEvents) {
return this.totalTime(typeof position === "number" ? position : this._parseTimeOrLabel(position), suppressEvents !== false);
};
p.stop = function () {
return this.paused(true);
};
p.gotoAndPlay = function (position, suppressEvents) {
return this.play(position, suppressEvents);
};
p.gotoAndStop = function (position, suppressEvents) {
return this.pause(position, suppressEvents);
};
p.render = function (time, suppressEvents, force) {
if (this._gc) {
this._enabled(true, false);
}
var prevTime = this._time,
totalDur = !this._dirty ? this._totalDuration : this.totalDuration(),
prevStart = this._startTime,
prevTimeScale = this._timeScale,
prevPaused = this._paused,
tween,isComplete,next,callback,internalForce,pauseTween,curTime;
if (prevTime !== this._time) {//if totalDuration() finds a child with a negative startTime and smoothChildTiming is true, things get shifted around internally so we need to adjust the time accordingly. For example, if a tween starts at -30 we must shift EVERYTHING forward 30 seconds and move this timeline's startTime backward by 30 seconds so that things align with the playhead (no jump).
time += this._time - prevTime;
}
if (time >= totalDur - 0.0000001 && time >= 0) {//to work around occasional floating point math artifacts.
this._totalTime = this._time = totalDur;
if (!this._reversed) if (!this._hasPausedChild()) {
isComplete = true;
callback = "onComplete";
internalForce = !!this._timeline.autoRemoveChildren; //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline.
if (this._duration === 0) if (time <= 0 && time >= -0.0000001 || this._rawPrevTime < 0 || this._rawPrevTime === _tinyNum) if (this._rawPrevTime !== time && this._first) {
internalForce = true;
if (this._rawPrevTime > _tinyNum) {
callback = "onReverseComplete";
}
}
}
this._rawPrevTime = this._duration || !suppressEvents || time || this._rawPrevTime === time ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
time = totalDur + 0.0001; //to avoid occasional floating point rounding errors - sometimes child tweens/timelines were not being fully completed (their progress might be 0.999999999999998 instead of 1 because when _time - tween._startTime is performed, floating point errors would return a value that was SLIGHTLY off). Try (999999999999.7 - 999999999999) * 1 = 0.699951171875 instead of 0.7.
} else if (time < 0.0000001) {//to work around occasional floating point math artifacts, round super small values to 0.
this._totalTime = this._time = 0;
if (prevTime !== 0 || this._duration === 0 && this._rawPrevTime !== _tinyNum && (this._rawPrevTime > 0 || time < 0 && this._rawPrevTime >= 0)) {
callback = "onReverseComplete";
isComplete = this._reversed;
}
if (time < 0) {
this._active = false;
if (this._timeline.autoRemoveChildren && this._reversed) {//ensures proper GC if a timeline is resumed after it's finished reversing.
internalForce = isComplete = true;
callback = "onReverseComplete";
} else if (this._rawPrevTime >= 0 && this._first) {//when going back beyond the start, force a render so that zero-duration tweens that sit at the very beginning render their start values properly. Otherwise, if the parent timeline's playhead lands exactly at this timeline's startTime, and then moves backwards, the zero-duration tweens at the beginning would still be at their end state.
internalForce = true;
}
this._rawPrevTime = time;
} else {
this._rawPrevTime = this._duration || !suppressEvents || time || this._rawPrevTime === time ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
if (time === 0 && isComplete) {//if there's a zero-duration tween at the very beginning of a timeline and the playhead lands EXACTLY at time 0, that tween will correctly render its end values, but we need to keep the timeline alive for one more render so that the beginning values render properly as the parent's playhead keeps moving beyond the begining. Imagine obj.x starts at 0 and then we do tl.set(obj, {x:100}).to(obj, 1, {x:200}) and then later we tl.reverse()...the goal is to have obj.x revert to 0. If the playhead happens to land on exactly 0, without this chunk of code, it'd complete the timeline and remove it from the rendering queue (not good).
tween = this._first;
while (tween && tween._startTime === 0) {
if (!tween._duration) {
isComplete = false;
}
tween = tween._next;
}
}
time = 0; //to avoid occasional floating point rounding errors (could cause problems especially with zero-duration tweens at the very beginning of the timeline)
if (!this._initted) {
internalForce = true;
}
}
} else {
if (this._hasPause && !this._forcingPlayhead && !suppressEvents) {
if (time >= prevTime) {
tween = this._first;
while (tween && tween._startTime <= time && !pauseTween) {
if (!tween._duration) if (tween.data === "isPause" && !tween.ratio && !(tween._startTime === 0 && this._rawPrevTime === 0)) {
pauseTween = tween;
}
tween = tween._next;
}
} else {
tween = this._last;
while (tween && tween._startTime >= time && !pauseTween) {
if (!tween._duration) if (tween.data === "isPause" && tween._rawPrevTime > 0) {
pauseTween = tween;
}
tween = tween._prev;
}
}
if (pauseTween) {
this._time = time = pauseTween._startTime;
this._totalTime = time + this._cycle * (this._totalDuration + this._repeatDelay);
}
}
this._totalTime = this._time = this._rawPrevTime = time;
}
if ((this._time === prevTime || !this._first) && !force && !internalForce && !pauseTween) {
return;
} else if (!this._initted) {
this._initted = true;
}
if (!this._active) if (!this._paused && this._time !== prevTime && time > 0) {
this._active = true; //so that if the user renders the timeline (as opposed to the parent timeline rendering it), it is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the timeline already finished but the user manually re-renders it as halfway done, for example.
}
if (prevTime === 0) if (this.vars.onStart) if (this._time !== 0 || !this._duration) if (!suppressEvents) {
this._callback("onStart");
}
curTime = this._time;
if (curTime >= prevTime) {
tween = this._first;
while (tween) {
next = tween._next; //record it here because the value could change after rendering...
if (curTime !== this._time || this._paused && !prevPaused) {//in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
break;
} else if (tween._active || tween._startTime <= curTime && !tween._paused && !tween._gc) {
if (pauseTween === tween) {
this.pause();
}
if (!tween._reversed) {
tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
} else {
tween.render((!tween._dirty ? tween._totalDuration : tween.totalDuration()) - (time - tween._startTime) * tween._timeScale, suppressEvents, force);
}
}
tween = next;
}
} else {
tween = this._last;
while (tween) {
next = tween._prev; //record it here because the value could change after rendering...
if (curTime !== this._time || this._paused && !prevPaused) {//in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
break;
} else if (tween._active || tween._startTime <= prevTime && !tween._paused && !tween._gc) {
if (pauseTween === tween) {
pauseTween = tween._prev; //the linked list is organized by _startTime, thus it's possible that a tween could start BEFORE the pause and end after it, in which case it would be positioned before the pause tween in the linked list, but we should render it before we pause() the timeline and cease rendering. This is only a concern when going in reverse.
while (pauseTween && pauseTween.endTime() > this._time) {
pauseTween.render(pauseTween._reversed ? pauseTween.totalDuration() - (time - pauseTween._startTime) * pauseTween._timeScale : (time - pauseTween._startTime) * pauseTween._timeScale, suppressEvents, force);
pauseTween = pauseTween._prev;
}
pauseTween = null;
this.pause();
}
if (!tween._reversed) {
tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
} else {
tween.render((!tween._dirty ? tween._totalDuration : tween.totalDuration()) - (time - tween._startTime) * tween._timeScale, suppressEvents, force);
}
}
tween = next;
}
}
if (this._onUpdate) if (!suppressEvents) {
if (_lazyTweens.length) {//in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onUpdate on a timeline that reports/checks tweened values.
_lazyRender();
}
this._callback("onUpdate");
}
if (callback) if (!this._gc) if (prevStart === this._startTime || prevTimeScale !== this._timeScale) if (this._time === 0 || totalDur >= this.totalDuration()) {//if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline), it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would complete if it was necessary at the new time. The only exception is the timeScale property. Also check _gc because there's a chance that kill() could be called in an onUpdate
if (isComplete) {
if (_lazyTweens.length) {//in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onComplete on a timeline that reports/checks tweened values.
_lazyRender();
}
if (this._timeline.autoRemoveChildren) {
this._enabled(false, false);
}
this._active = false;
}
if (!suppressEvents && this.vars[callback]) {
this._callback(callback);
}
}
};
p._hasPausedChild = function () {
var tween = this._first;
while (tween) {
if (tween._paused || tween instanceof TimelineLite && tween._hasPausedChild()) {
return true;
}
tween = tween._next;
}
return false;
};
p.getChildren = function (nested, tweens, timelines, ignoreBeforeTime) {
ignoreBeforeTime = ignoreBeforeTime || -9999999999;
var a = [],
tween = this._first,
cnt = 0;
while (tween) {
if (tween._startTime < ignoreBeforeTime) {
//do nothing
} else if (tween instanceof TweenLite) {
if (tweens !== false) {
a[cnt++] = tween;
}
} else {
if (timelines !== false) {
a[cnt++] = tween;
}
if (nested !== false) {
a = a.concat(tween.getChildren(true, tweens, timelines));
cnt = a.length;
}
}
tween = tween._next;
}
return a;
};
p.getTweensOf = function (target, nested) {
var disabled = this._gc,
a = [],
cnt = 0,
tweens,i;
if (disabled) {
this._enabled(true, true); //getTweensOf() filters out disabled tweens, and we have to mark them as _gc = true when the timeline completes in order to allow clean garbage collection, so temporarily re-enable the timeline here.
}
tweens = TweenLite.getTweensOf(target);
i = tweens.length;
while (--i > -1) {
if (tweens[i].timeline === this || nested && this._contains(tweens[i])) {
a[cnt++] = tweens[i];
}
}
if (disabled) {
this._enabled(false, true);
}
return a;
};
p.recent = function () {
return this._recent;
};
p._contains = function (tween) {
var tl = tween.timeline;
while (tl) {
if (tl === this) {
return true;
}
tl = tl.timeline;
}
return false;
};
p.shiftChildren = function (amount, adjustLabels, ignoreBeforeTime) {
ignoreBeforeTime = ignoreBeforeTime || 0;
var tween = this._first,
labels = this._labels,
p;
while (tween) {
if (tween._startTime >= ignoreBeforeTime) {
tween._startTime += amount;
}
tween = tween._next;
}
if (adjustLabels) {
for (p in labels) {
if (labels[p] >= ignoreBeforeTime) {
labels[p] += amount;
}
}
}
return this._uncache(true);
};
p._kill = function (vars, target) {
if (!vars && !target) {
return this._enabled(false, false);
}
var tweens = !target ? this.getChildren(true, true, false) : this.getTweensOf(target),
i = tweens.length,
changed = false;
while (--i > -1) {
if (tweens[i]._kill(vars, target)) {
changed = true;
}
}
return changed;
};
p.clear = function (labels) {
var tweens = this.getChildren(false, true, true),
i = tweens.length;
this._time = this._totalTime = 0;
while (--i > -1) {
tweens[i]._enabled(false, false);
}
if (labels !== false) {
this._labels = {};
}
return this._uncache(true);
};
p.invalidate = function () {
var tween = this._first;
while (tween) {
tween.invalidate();
tween = tween._next;
}
return Animation.prototype.invalidate.call(this);;
};
p._enabled = function (enabled, ignoreTimeline) {
if (enabled === this._gc) {
var tween = this._first;
while (tween) {
tween._enabled(enabled, true);
tween = tween._next;
}
}
return SimpleTimeline.prototype._enabled.call(this, enabled, ignoreTimeline);
};
p.totalTime = function (time, suppressEvents, uncapped) {
this._forcingPlayhead = true;
var val = Animation.prototype.totalTime.apply(this, arguments);
this._forcingPlayhead = false;
return val;
};
p.duration = function (value) {
if (!arguments.length) {
if (this._dirty) {
this.totalDuration(); //just triggers recalculation
}
return this._duration;
}
if (this.duration() !== 0 && value !== 0) {
this.timeScale(this._duration / value);
}
return this;
};
p.totalDuration = function (value) {
if (!arguments.length) {
if (this._dirty) {
var max = 0,
tween = this._last,
prevStart = 999999999999,
prev,end;
while (tween) {
prev = tween._prev; //record it here in case the tween changes position in the sequence...
if (tween._dirty) {
tween.totalDuration(); //could change the tween._startTime, so make sure the tween's cache is clean before analyzing it.
}
if (tween._startTime > prevStart && this._sortChildren && !tween._paused && !this._calculatingDuration) {//in case one of the tweens shifted out of order, it needs to be re-inserted into the correct position in the sequence
this._calculatingDuration = 1; //prevent endless recursive calls - there are methods that get triggered that check duration/totalDuration when we add(), like _parseTimeOrLabel().
this.add(tween, tween._startTime - tween._delay);
this._calculatingDuration = 0;
} else {
prevStart = tween._startTime;
}
if (tween._startTime < 0 && !tween._paused) {//children aren't allowed to have negative startTimes unless smoothChildTiming is true, so adjust here if one is found.
max -= tween._startTime;
if (this._timeline.smoothChildTiming) {
this._startTime += tween._startTime / this._timeScale;
this._time -= tween._startTime;
this._totalTime -= tween._startTime;
this._rawPrevTime -= tween._startTime;
}
this.shiftChildren(-tween._startTime, false, -9999999999);
prevStart = 0;
}
end = tween._startTime + tween._totalDuration / tween._timeScale;
if (end > max) {
max = end;
}
tween = prev;
}
this._duration = this._totalDuration = max;
this._dirty = false;
}
return this._totalDuration;
}
return value && this.totalDuration() ? this.timeScale(this._totalDuration / value) : this;
};
p.paused = function (value) {
if (!value) {//if there's a pause directly at the spot from where we're unpausing, skip it.
var tween = this._first,
time = this._time;
while (tween) {
if (tween._startTime === time && tween.data === "isPause") {
tween._rawPrevTime = 0; //remember, _rawPrevTime is how zero-duration tweens/callbacks sense directionality and determine whether or not to fire. If _rawPrevTime is the same as _startTime on the next render, it won't fire.
}
tween = tween._next;
}
}
return Animation.prototype.paused.apply(this, arguments);
};
p.usesFrames = function () {
var tl = this._timeline;
while (tl._timeline) {
tl = tl._timeline;
}
return tl === Animation._rootFramesTimeline;
};
p.rawTime = function (wrapRepeats) {
return wrapRepeats && (this._paused || this._repeat && this.time() > 0 && this.totalProgress() < 1) ? this._totalTime % (this._duration + this._repeatDelay) : this._paused ? this._totalTime : (this._timeline.rawTime(wrapRepeats) - this._startTime) * this._timeScale;
};
return TimelineLite;
}, true);
/*
* ----------------------------------------------------------------
* TimelineMax
* ----------------------------------------------------------------
*/
_gsScope._gsDefine("TimelineMax", ["TimelineLite", "TweenLite", "easing.Ease"], function (TimelineLite, TweenLite, Ease) {
var TimelineMax = function TimelineMax(vars) {
TimelineLite.call(this, vars);
this._repeat = this.vars.repeat || 0;
this._repeatDelay = this.vars.repeatDelay || 0;
this._cycle = 0;
this._yoyo = this.vars.yoyo === true;
this._dirty = true;
},
_tinyNum = 0.0000000001,
TweenLiteInternals = TweenLite._internals,
_lazyTweens = TweenLiteInternals.lazyTweens,
_lazyRender = TweenLiteInternals.lazyRender,
_globals = _gsScope._gsDefine.globals,
_easeNone = new Ease(null, null, 1, 0),
p = TimelineMax.prototype = new TimelineLite();
p.constructor = TimelineMax;
p.kill()._gc = false;
TimelineMax.version = "1.20.4";
p.invalidate = function () {
this._yoyo = this.vars.yoyo === true;
this._repeat = this.vars.repeat || 0;
this._repeatDelay = this.vars.repeatDelay || 0;
this._uncache(true);
return TimelineLite.prototype.invalidate.call(this);
};
p.addCallback = function (callback, position, params, scope) {
return this.add(TweenLite.delayedCall(0, callback, params, scope), position);
};
p.removeCallback = function (callback, position) {
if (callback) {
if (position == null) {
this._kill(null, callback);
} else {
var a = this.getTweensOf(callback, false),
i = a.length,
time = this._parseTimeOrLabel(position);
while (--i > -1) {
if (a[i]._startTime === time) {
a[i]._enabled(false, false);
}
}
}
}
return this;
};
p.removePause = function (position) {
return this.removeCallback(TimelineLite._internals.pauseCallback, position);
};
p.tweenTo = function (position, vars) {
vars = vars || {};
var copy = { ease: _easeNone, useFrames: this.usesFrames(), immediateRender: false, lazy: false },
Engine = vars.repeat && _globals.TweenMax || TweenLite,
duration,p,t;
for (p in vars) {
copy[p] = vars[p];
}
copy.time = this._parseTimeOrLabel(position);
duration = Math.abs(Number(copy.time) - this._time) / this._timeScale || 0.001;
t = new Engine(this, duration, copy);
copy.onStart = function () {
t.target.paused(true);
if (t.vars.time !== t.target.time() && duration === t.duration() && !t.isFromTo) {//don't make the duration zero - if it's supposed to be zero, don't worry because it's already initting the tween and will complete immediately, effectively making the duration zero anyway. If we make duration zero, the tween won't run at all.
t.duration(Math.abs(t.vars.time - t.target.time()) / t.target._timeScale).render(t.time(), true, true); //render() right away to ensure that things look right, especially in the case of .tweenTo(0).
}
if (vars.onStart) {//in case the user had an onStart in the vars - we don't want to overwrite it.
vars.onStart.apply(vars.onStartScope || vars.callbackScope || t, vars.onStartParams || []); //don't use t._callback("onStart") or it'll point to the copy.onStart and we'll get a recursion error.
}
};
return t;
};
p.tweenFromTo = function (fromPosition, toPosition, vars) {
vars = vars || {};
fromPosition = this._parseTimeOrLabel(fromPosition);
vars.startAt = { onComplete: this.seek, onCompleteParams: [fromPosition], callbackScope: this };
vars.immediateRender = vars.immediateRender !== false;
var t = this.tweenTo(toPosition, vars);
t.isFromTo = 1; //to ensure we don't mess with the duration in the onStart (we've got the start and end values here, so lock it in)
return t.duration(Math.abs(t.vars.time - fromPosition) / this._timeScale || 0.001);
};
p.render = function (time, suppressEvents, force) {
if (this._gc) {
this._enabled(true, false);
}
var prevTime = this._time,
totalDur = !this._dirty ? this._totalDuration : this.totalDuration(),
dur = this._duration,
prevTotalTime = this._totalTime,
prevStart = this._startTime,
prevTimeScale = this._timeScale,
prevRawPrevTime = this._rawPrevTime,
prevPaused = this._paused,
prevCycle = this._cycle,
tween,isComplete,next,callback,internalForce,cycleDuration,pauseTween,curTime;
if (prevTime !== this._time) {//if totalDuration() finds a child with a negative startTime and smoothChildTiming is true, things get shifted around internally so we need to adjust the time accordingly. For example, if a tween starts at -30 we must shift EVERYTHING forward 30 seconds and move this timeline's startTime backward by 30 seconds so that things align with the playhead (no jump).
time += this._time - prevTime;
}
if (time >= totalDur - 0.0000001 && time >= 0) {//to work around occasional floating point math artifacts.
if (!this._locked) {
this._totalTime = totalDur;
this._cycle = this._repeat;
}
if (!this._reversed) if (!this._hasPausedChild()) {
isComplete = true;
callback = "onComplete";
internalForce = !!this._timeline.autoRemoveChildren; //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline.
if (this._duration === 0) if (time <= 0 && time >= -0.0000001 || prevRawPrevTime < 0 || prevRawPrevTime === _tinyNum) if (prevRawPrevTime !== time && this._first) {
internalForce = true;
if (prevRawPrevTime > _tinyNum) {
callback = "onReverseComplete";
}
}
}
this._rawPrevTime = this._duration || !suppressEvents || time || this._rawPrevTime === time ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
if (this._yoyo && (this._cycle & 1) !== 0) {
this._time = time = 0;
} else {
this._time = dur;
time = dur + 0.0001; //to avoid occasional floating point rounding errors - sometimes child tweens/timelines were not being fully completed (their progress might be 0.999999999999998 instead of 1 because when _time - tween._startTime is performed, floating point errors would return a value that was SLIGHTLY off). Try (999999999999.7 - 999999999999) * 1 = 0.699951171875 instead of 0.7. We cannot do less then 0.0001 because the same issue can occur when the duration is extremely large like 999999999999 in which case adding 0.00000001, for example, causes it to act like nothing was added.
}
} else if (time < 0.0000001) {//to work around occasional floating point math artifacts, round super small values to 0.
if (!this._locked) {
this._totalTime = this._cycle = 0;
}
this._time = 0;
if (prevTime !== 0 || dur === 0 && prevRawPrevTime !== _tinyNum && (prevRawPrevTime > 0 || time < 0 && prevRawPrevTime >= 0) && !this._locked) {//edge case for checking time < 0 && prevRawPrevTime >= 0: a zero-duration fromTo() tween inside a zero-duration timeline (yeah, very rare)
callback = "onReverseComplete";
isComplete = this._reversed;
}
if (time < 0) {
this._active = false;
if (this._timeline.autoRemoveChildren && this._reversed) {
internalForce = isComplete = true;
callback = "onReverseComplete";
} else if (prevRawPrevTime >= 0 && this._first) {//when going back beyond the start, force a render so that zero-duration tweens that sit at the very beginning render their start values properly. Otherwise, if the parent timeline's playhead lands exactly at this timeline's startTime, and then moves backwards, the zero-duration tweens at the beginning would still be at their end state.
internalForce = true;
}
this._rawPrevTime = time;
} else {
this._rawPrevTime = dur || !suppressEvents || time || this._rawPrevTime === time ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
if (time === 0 && isComplete) {//if there's a zero-duration tween at the very beginning of a timeline and the playhead lands EXACTLY at time 0, that tween will correctly render its end values, but we need to keep the timeline alive for one more render so that the beginning values render properly as the parent's playhead keeps moving beyond the begining. Imagine obj.x starts at 0 and then we do tl.set(obj, {x:100}).to(obj, 1, {x:200}) and then later we tl.reverse()...the goal is to have obj.x revert to 0. If the playhead happens to land on exactly 0, without this chunk of code, it'd complete the timeline and remove it from the rendering queue (not good).
tween = this._first;
while (tween && tween._startTime === 0) {
if (!tween._duration) {
isComplete = false;
}
tween = tween._next;
}
}
time = 0; //to avoid occasional floating point rounding errors (could cause problems especially with zero-duration tweens at the very beginning of the timeline)
if (!this._initted) {
internalForce = true;
}
}
} else {
if (dur === 0 && prevRawPrevTime < 0) {//without this, zero-duration repeating timelines (like with a simple callback nested at the very beginning and a repeatDelay) wouldn't render the first time through.
internalForce = true;
}
this._time = this._rawPrevTime = time;
if (!this._locked) {
this._totalTime = time;
if (this._repeat !== 0) {
cycleDuration = dur + this._repeatDelay;
this._cycle = this._totalTime / cycleDuration >> 0; //originally _totalTime % cycleDuration but floating point errors caused problems, so I normalized it. (4 % 0.8 should be 0 but it gets reported as 0.79999999!)
if (this._cycle !== 0) if (this._cycle === this._totalTime / cycleDuration && prevTotalTime <= time) {
this._cycle--; //otherwise when rendered exactly at the end time, it will act as though it is repeating (at the beginning)
}
this._time = this._totalTime - this._cycle * cycleDuration;
if (this._yoyo) if ((this._cycle & 1) !== 0) {
this._time = dur - this._time;
}
if (this._time > dur) {
this._time = dur;
time = dur + 0.0001; //to avoid occasional floating point rounding error
} else if (this._time < 0) {
this._time = time = 0;
} else {
time = this._time;
}
}
}
if (this._hasPause && !this._forcingPlayhead && !suppressEvents) {
time = this._time;
if (time >= prevTime || this._repeat && prevCycle !== this._cycle) {
tween = this._first;
while (tween && tween._startTime <= time && !pauseTween) {
if (!tween._duration) if (tween.data === "isPause" && !tween.ratio && !(tween._startTime === 0 && this._rawPrevTime === 0)) {
pauseTween = tween;
}
tween = tween._next;
}
} else {
tween = this._last;
while (tween && tween._startTime >= time && !pauseTween) {
if (!tween._duration) if (tween.data === "isPause" && tween._rawPrevTime > 0) {
pauseTween = tween;
}
tween = tween._prev;
}
}
if (pauseTween && pauseTween._startTime < dur) {
this._time = time = pauseTween._startTime;
this._totalTime = time + this._cycle * (this._totalDuration + this._repeatDelay);
}
}
}
if (this._cycle !== prevCycle) if (!this._locked) {
/*
make sure children at the end/beginning of the timeline are rendered properly. If, for example,
a 3-second long timeline rendered at 2.9 seconds previously, and now renders at 3.2 seconds (which
would get transated to 2.8 seconds if the timeline yoyos or 0.2 seconds if it just repeats), there
could be a callback or a short tween that's at 2.95 or 3 seconds in which wouldn't render. So
we need to push the timeline to the end (and/or beginning depending on its yoyo value). Also we must
ensure that zero-duration tweens at the very beginning or end of the TimelineMax work.
*/
var backwards = this._yoyo && (prevCycle & 1) !== 0,
wrap = backwards === (this._yoyo && (this._cycle & 1) !== 0),
recTotalTime = this._totalTime,
recCycle = this._cycle,
recRawPrevTime = this._rawPrevTime,
recTime = this._time;
this._totalTime = prevCycle * dur;
if (this._cycle < prevCycle) {
backwards = !backwards;
} else {
this._totalTime += dur;
}
this._time = prevTime; //temporarily revert _time so that render() renders the children in the correct order. Without this, tweens won't rewind correctly. We could arhictect things in a "cleaner" way by splitting out the rendering queue into a separate method but for performance reasons, we kept it all inside this method.
this._rawPrevTime = dur === 0 ? prevRawPrevTime - 0.0001 : prevRawPrevTime;
this._cycle = prevCycle;
this._locked = true; //prevents changes to totalTime and skips repeat/yoyo behavior when we recursively call render()
prevTime = backwards ? 0 : dur;
this.render(prevTime, suppressEvents, dur === 0);
if (!suppressEvents) if (!this._gc) {
if (this.vars.onRepeat) {
this._cycle = recCycle; //in case the onRepeat alters the playhead or invalidates(), we shouldn't stay locked or use the previous cycle.
this._locked = false;
this._callback("onRepeat");
}
}
if (prevTime !== this._time) {//in case there's a callback like onComplete in a nested tween/timeline that changes the playhead position, like via seek(), we should just abort.
return;
}
if (wrap) {
this._cycle = prevCycle; //if there's an onRepeat, we reverted this above, so make sure it's set properly again. We also unlocked in that scenario, so reset that too.
this._locked = true;
prevTime = backwards ? dur + 0.0001 : -0.0001;
this.render(prevTime, true, false);
}
this._locked = false;
if (this._paused && !prevPaused) {//if the render() triggered callback that paused this timeline, we should abort (very rare, but possible)
return;
}
this._time = recTime;
this._totalTime = recTotalTime;
this._cycle = recCycle;
this._rawPrevTime = recRawPrevTime;
}
if ((this._time === prevTime || !this._first) && !force && !internalForce && !pauseTween) {
if (prevTotalTime !== this._totalTime) if (this._onUpdate) if (!suppressEvents) {//so that onUpdate fires even during the repeatDelay - as long as the totalTime changed, we should trigger onUpdate.
this._callback("onUpdate");
}
return;
} else if (!this._initted) {
this._initted = true;
}
if (!this._active) if (!this._paused && this._totalTime !== prevTotalTime && time > 0) {
this._active = true; //so that if the user renders the timeline (as opposed to the parent timeline rendering it), it is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the timeline already finished but the user manually re-renders it as halfway done, for example.
}
if (prevTotalTime === 0) if (this.vars.onStart) if (this._totalTime !== 0 || !this._totalDuration) if (!suppressEvents) {
this._callback("onStart");
}
curTime = this._time;
if (curTime >= prevTime) {
tween = this._first;
while (tween) {
next = tween._next; //record it here because the value could change after rendering...
if (curTime !== this._time || this._paused && !prevPaused) {//in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
break;
} else if (tween._active || tween._startTime <= this._time && !tween._paused && !tween._gc) {
if (pauseTween === tween) {
this.pause();
}
if (!tween._reversed) {
tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
} else {
tween.render((!tween._dirty ? tween._totalDuration : tween.totalDuration()) - (time - tween._startTime) * tween._timeScale, suppressEvents, force);
}
}
tween = next;
}
} else {
tween = this._last;
while (tween) {
next = tween._prev; //record it here because the value could change after rendering...
if (curTime !== this._time || this._paused && !prevPaused) {//in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
break;
} else if (tween._active || tween._startTime <= prevTime && !tween._paused && !tween._gc) {
if (pauseTween === tween) {
pauseTween = tween._prev; //the linked list is organized by _startTime, thus it's possible that a tween could start BEFORE the pause and end after it, in which case it would be positioned before the pause tween in the linked list, but we should render it before we pause() the timeline and cease rendering. This is only a concern when going in reverse.
while (pauseTween && pauseTween.endTime() > this._time) {
pauseTween.render(pauseTween._reversed ? pauseTween.totalDuration() - (time - pauseTween._startTime) * pauseTween._timeScale : (time - pauseTween._startTime) * pauseTween._timeScale, suppressEvents, force);
pauseTween = pauseTween._prev;
}
pauseTween = null;
this.pause();
}
if (!tween._reversed) {
tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
} else {
tween.render((!tween._dirty ? tween._totalDuration : tween.totalDuration()) - (time - tween._startTime) * tween._timeScale, suppressEvents, force);
}
}
tween = next;
}
}
if (this._onUpdate) if (!suppressEvents) {
if (_lazyTweens.length) {//in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onUpdate on a timeline that reports/checks tweened values.
_lazyRender();
}
this._callback("onUpdate");
}
if (callback) if (!this._locked) if (!this._gc) if (prevStart === this._startTime || prevTimeScale !== this._timeScale) if (this._time === 0 || totalDur >= this.totalDuration()) {//if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline), it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would complete if it was necessary at the new time. The only exception is the timeScale property. Also check _gc because there's a chance that kill() could be called in an onUpdate
if (isComplete) {
if (_lazyTweens.length) {//in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onComplete on a timeline that reports/checks tweened values.
_lazyRender();
}
if (this._timeline.autoRemoveChildren) {
this._enabled(false, false);
}
this._active = false;
}
if (!suppressEvents && this.vars[callback]) {
this._callback(callback);
}
}
};
p.getActive = function (nested, tweens, timelines) {
if (nested == null) {
nested = true;
}
if (tweens == null) {
tweens = true;
}
if (timelines == null) {
timelines = false;
}
var a = [],
all = this.getChildren(nested, tweens, timelines),
cnt = 0,
l = all.length,
i,tween;
for (i = 0; i < l; i++) {
tween = all[i];
if (tween.isActive()) {
a[cnt++] = tween;
}
}
return a;
};
p.getLabelAfter = function (time) {
if (!time) if (time !== 0) {//faster than isNan()
time = this._time;
}
var labels = this.getLabelsArray(),
l = labels.length,
i;
for (i = 0; i < l; i++) {
if (labels[i].time > time) {
return labels[i].name;
}
}
return null;
};
p.getLabelBefore = function (time) {
if (time == null) {
time = this._time;
}
var labels = this.getLabelsArray(),
i = labels.length;
while (--i > -1) {
if (labels[i].time < time) {
return labels[i].name;
}
}
return null;
};
p.getLabelsArray = function () {
var a = [],
cnt = 0,
p;
for (p in this._labels) {
a[cnt++] = { time: this._labels[p], name: p };
}
a.sort(function (a, b) {
return a.time - b.time;
});
return a;
};
p.invalidate = function () {
this._locked = false; //unlock and set cycle in case invalidate() is called from inside an onRepeat
return TimelineLite.prototype.invalidate.call(this);
};
//---- GETTERS / SETTERS -------------------------------------------------------------------------------------------------------
p.progress = function (value, suppressEvents) {
return !arguments.length ? this._time / this.duration() || 0 : this.totalTime(this.duration() * (this._yoyo && (this._cycle & 1) !== 0 ? 1 - value : value) + this._cycle * (this._duration + this._repeatDelay), suppressEvents);
};
p.totalProgress = function (value, suppressEvents) {
return !arguments.length ? this._totalTime / this.totalDuration() || 0 : this.totalTime(this.totalDuration() * value, suppressEvents);
};
p.totalDuration = function (value) {
if (!arguments.length) {
if (this._dirty) {
TimelineLite.prototype.totalDuration.call(this); //just forces refresh
//Instead of Infinity, we use 999999999999 so that we can accommodate reverses.
this._totalDuration = this._repeat === -1 ? 999999999999 : this._duration * (this._repeat + 1) + this._repeatDelay * this._repeat;
}
return this._totalDuration;
}
return this._repeat === -1 || !value ? this : this.timeScale(this.totalDuration() / value);
};
p.time = function (value, suppressEvents) {
if (!arguments.length) {
return this._time;
}
if (this._dirty) {
this.totalDuration();
}
if (value > this._duration) {
value = this._duration;
}
if (this._yoyo && (this._cycle & 1) !== 0) {
value = this._duration - value + this._cycle * (this._duration + this._repeatDelay);
} else if (this._repeat !== 0) {
value += this._cycle * (this._duration + this._repeatDelay);
}
return this.totalTime(value, suppressEvents);
};
p.repeat = function (value) {
if (!arguments.length) {
return this._repeat;
}
this._repeat = value;
return this._uncache(true);
};
p.repeatDelay = function (value) {
if (!arguments.length) {
return this._repeatDelay;
}
this._repeatDelay = value;
return this._uncache(true);
};
p.yoyo = function (value) {
if (!arguments.length) {
return this._yoyo;
}
this._yoyo = value;
return this;
};
p.currentLabel = function (value) {
if (!arguments.length) {
return this.getLabelBefore(this._time + 0.00000001);
}
return this.seek(value, true);
};
return TimelineMax;
}, true);
/*
* ----------------------------------------------------------------
* BezierPlugin
* ----------------------------------------------------------------
*/
(function () {
var _RAD2DEG = 180 / Math.PI,
_r1 = [],
_r2 = [],
_r3 = [],
_corProps = {},
_globals = _gsScope._gsDefine.globals,
Segment = function Segment(a, b, c, d) {
if (c === d) {//if c and d match, the final autoRotate value could lock at -90 degrees, so differentiate them slightly.
c = d - (d - b) / 1000000;
}
if (a === b) {//if a and b match, the starting autoRotate value could lock at -90 degrees, so differentiate them slightly.
b = a + (c - a) / 1000000;
}
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.da = d - a;
this.ca = c - a;
this.ba = b - a;
},
_correlate = ",x,y,z,left,top,right,bottom,marginTop,marginLeft,marginRight,marginBottom,paddingLeft,paddingTop,paddingRight,paddingBottom,backgroundPosition,backgroundPosition_y,",
cubicToQuadratic = function cubicToQuadratic(a, b, c, d) {
var q1 = { a: a },
q2 = {},
q3 = {},
q4 = { c: d },
mab = (a + b) / 2,
mbc = (b + c) / 2,
mcd = (c + d) / 2,
mabc = (mab + mbc) / 2,
mbcd = (mbc + mcd) / 2,
m8 = (mbcd - mabc) / 8;
q1.b = mab + (a - mab) / 4;
q2.b = mabc + m8;
q1.c = q2.a = (q1.b + q2.b) / 2;
q2.c = q3.a = (mabc + mbcd) / 2;
q3.b = mbcd - m8;
q4.b = mcd + (d - mcd) / 4;
q3.c = q4.a = (q3.b + q4.b) / 2;
return [q1, q2, q3, q4];
},
_calculateControlPoints = function _calculateControlPoints(a, curviness, quad, basic, correlate) {
var l = a.length - 1,
ii = 0,
cp1 = a[0].a,
i,p1,p2,p3,seg,m1,m2,mm,cp2,qb,r1,r2,tl;
for (i = 0; i < l; i++) {
seg = a[ii];
p1 = seg.a;
p2 = seg.d;
p3 = a[ii + 1].d;
if (correlate) {
r1 = _r1[i];
r2 = _r2[i];
tl = (r2 + r1) * curviness * 0.25 / (basic ? 0.5 : _r3[i] || 0.5);
m1 = p2 - (p2 - p1) * (basic ? curviness * 0.5 : r1 !== 0 ? tl / r1 : 0);
m2 = p2 + (p3 - p2) * (basic ? curviness * 0.5 : r2 !== 0 ? tl / r2 : 0);
mm = p2 - (m1 + ((m2 - m1) * (r1 * 3 / (r1 + r2) + 0.5) / 4 || 0));
} else {
m1 = p2 - (p2 - p1) * curviness * 0.5;
m2 = p2 + (p3 - p2) * curviness * 0.5;
mm = p2 - (m1 + m2) / 2;
}
m1 += mm;
m2 += mm;
seg.c = cp2 = m1;
if (i !== 0) {
seg.b = cp1;
} else {
seg.b = cp1 = seg.a + (seg.c - seg.a) * 0.6; //instead of placing b on a exactly, we move it inline with c so that if the user specifies an ease like Back.easeIn or Elastic.easeIn which goes BEYOND the beginning, it will do so smoothly.
}
seg.da = p2 - p1;
seg.ca = cp2 - p1;
seg.ba = cp1 - p1;
if (quad) {
qb = cubicToQuadratic(p1, cp1, cp2, p2);
a.splice(ii, 1, qb[0], qb[1], qb[2], qb[3]);
ii += 4;
} else {
ii++;
}
cp1 = m2;
}
seg = a[ii];
seg.b = cp1;
seg.c = cp1 + (seg.d - cp1) * 0.4; //instead of placing c on d exactly, we move it inline with b so that if the user specifies an ease like Back.easeOut or Elastic.easeOut which goes BEYOND the end, it will do so smoothly.
seg.da = seg.d - seg.a;
seg.ca = seg.c - seg.a;
seg.ba = cp1 - seg.a;
if (quad) {
qb = cubicToQuadratic(seg.a, cp1, seg.c, seg.d);
a.splice(ii, 1, qb[0], qb[1], qb[2], qb[3]);
}
},
_parseAnchors = function _parseAnchors(values, p, correlate, prepend) {
var a = [],
l,i,p1,p2,p3,tmp;
if (prepend) {
values = [prepend].concat(values);
i = values.length;
while (--i > -1) {
if (typeof (tmp = values[i][p]) === "string") if (tmp.charAt(1) === "=") {
values[i][p] = prepend[p] + Number(tmp.charAt(0) + tmp.substr(2)); //accommodate relative values. Do it inline instead of breaking it out into a function for speed reasons
}
}
}
l = values.length - 2;
if (l < 0) {
a[0] = new Segment(values[0][p], 0, 0, values[0][p]);
return a;
}
for (i = 0; i < l; i++) {
p1 = values[i][p];
p2 = values[i + 1][p];
a[i] = new Segment(p1, 0, 0, p2);
if (correlate) {
p3 = values[i + 2][p];
_r1[i] = (_r1[i] || 0) + (p2 - p1) * (p2 - p1);
_r2[i] = (_r2[i] || 0) + (p3 - p2) * (p3 - p2);
}
}
a[i] = new Segment(values[i][p], 0, 0, values[i + 1][p]);
return a;
},
bezierThrough = function bezierThrough(values, curviness, quadratic, basic, correlate, prepend) {
var obj = {},
props = [],
first = prepend || values[0],
i,p,a,j,r,l,seamless,last;
correlate = typeof correlate === "string" ? "," + correlate + "," : _correlate;
if (curviness == null) {
curviness = 1;
}
for (p in values[0]) {
props.push(p);
}
//check to see if the last and first values are identical (well, within 0.05). If so, make seamless by appending the second element to the very end of the values array and the 2nd-to-last element to the very beginning (we'll remove those segments later)
if (values.length > 1) {
last = values[values.length - 1];
seamless = true;
i = props.length;
while (--i > -1) {
p = props[i];
if (Math.abs(first[p] - last[p]) > 0.05) {//build in a tolerance of +/-0.05 to accommodate rounding errors.
seamless = false;
break;
}
}
if (seamless) {
values = values.concat(); //duplicate the array to avoid contaminating the original which the user may be reusing for other tweens
if (prepend) {
values.unshift(prepend);
}
values.push(values[1]);
prepend = values[values.length - 3];
}
}
_r1.length = _r2.length = _r3.length = 0;
i = props.length;
while (--i > -1) {
p = props[i];
_corProps[p] = correlate.indexOf("," + p + ",") !== -1;
obj[p] = _parseAnchors(values, p, _corProps[p], prepend);
}
i = _r1.length;
while (--i > -1) {
_r1[i] = Math.sqrt(_r1[i]);
_r2[i] = Math.sqrt(_r2[i]);
}
if (!basic) {
i = props.length;
while (--i > -1) {
if (_corProps[p]) {
a = obj[props[i]];
l = a.length - 1;
for (j = 0; j < l; j++) {
r = a[j + 1].da / _r2[j] + a[j].da / _r1[j] || 0;
_r3[j] = (_r3[j] || 0) + r * r;
}
}
}
i = _r3.length;
while (--i > -1) {
_r3[i] = Math.sqrt(_r3[i]);
}
}
i = props.length;
j = quadratic ? 4 : 1;
while (--i > -1) {
p = props[i];
a = obj[p];
_calculateControlPoints(a, curviness, quadratic, basic, _corProps[p]); //this method requires that _parseAnchors() and _setSegmentRatios() ran first so that _r1, _r2, and _r3 values are populated for all properties
if (seamless) {
a.splice(0, j);
a.splice(a.length - j, j);
}
}
return obj;
},
_parseBezierData = function _parseBezierData(values, type, prepend) {
type = type || "soft";
var obj = {},
inc = type === "cubic" ? 3 : 2,
soft = type === "soft",
props = [],
a,b,c,d,cur,i,j,l,p,cnt,tmp;
if (soft && prepend) {
values = [prepend].concat(values);
}
if (values == null || values.length < inc + 1) {throw "invalid Bezier data";}
for (p in values[0]) {
props.push(p);
}
i = props.length;
while (--i > -1) {
p = props[i];
obj[p] = cur = [];
cnt = 0;
l = values.length;
for (j = 0; j < l; j++) {
a = prepend == null ? values[j][p] : typeof (tmp = values[j][p]) === "string" && tmp.charAt(1) === "=" ? prepend[p] + Number(tmp.charAt(0) + tmp.substr(2)) : Number(tmp);
if (soft) if (j > 1) if (j < l - 1) {
cur[cnt++] = (a + cur[cnt - 2]) / 2;
}
cur[cnt++] = a;
}
l = cnt - inc + 1;
cnt = 0;
for (j = 0; j < l; j += inc) {
a = cur[j];
b = cur[j + 1];
c = cur[j + 2];
d = inc === 2 ? 0 : cur[j + 3];
cur[cnt++] = tmp = inc === 3 ? new Segment(a, b, c, d) : new Segment(a, (2 * b + a) / 3, (2 * b + c) / 3, c);
}
cur.length = cnt;
}
return obj;
},
_addCubicLengths = function _addCubicLengths(a, steps, resolution) {
var inc = 1 / resolution,
j = a.length,
d,d1,s,da,ca,ba,p,i,inv,bez,index;
while (--j > -1) {
bez = a[j];
s = bez.a;
da = bez.d - s;
ca = bez.c - s;
ba = bez.b - s;
d = d1 = 0;
for (i = 1; i <= resolution; i++) {
p = inc * i;
inv = 1 - p;
d = d1 - (d1 = (p * p * da + 3 * inv * (p * ca + inv * ba)) * p);
index = j * resolution + i - 1;
steps[index] = (steps[index] || 0) + d * d;
}
}
},
_parseLengthData = function _parseLengthData(obj, resolution) {
resolution = resolution >> 0 || 6;
var a = [],
lengths = [],
d = 0,
total = 0,
threshold = resolution - 1,
segments = [],
curLS = [], //current length segments array
p,i,l,index;
for (p in obj) {
_addCubicLengths(obj[p], a, resolution);
}
l = a.length;
for (i = 0; i < l; i++) {
d += Math.sqrt(a[i]);
index = i % resolution;
curLS[index] = d;
if (index === threshold) {
total += d;
index = i / resolution >> 0;
segments[index] = curLS;
lengths[index] = total;
d = 0;
curLS = [];
}
}
return { length: total, lengths: lengths, segments: segments };
},
BezierPlugin = _gsScope._gsDefine.plugin({
propName: "bezier",
priority: -1,
version: "1.3.8",
API: 2,
global: true,
//gets called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run.
init: function init(target, vars, tween) {
this._target = target;
if (vars instanceof Array) {
vars = { values: vars };
}
this._func = {};
this._mod = {};
this._props = [];
this._timeRes = vars.timeResolution == null ? 6 : parseInt(vars.timeResolution, 10);
var values = vars.values || [],
first = {},
second = values[0],
autoRotate = vars.autoRotate || tween.vars.orientToBezier,
p,isFunc,i,j,prepend;
this._autoRotate = autoRotate ? autoRotate instanceof Array ? autoRotate : [["x", "y", "rotation", autoRotate === true ? 0 : Number(autoRotate) || 0]] : null;
for (p in second) {
this._props.push(p);
}
i = this._props.length;
while (--i > -1) {
p = this._props[i];
this._overwriteProps.push(p);
isFunc = this._func[p] = typeof target[p] === "function";
first[p] = !isFunc ? parseFloat(target[p]) : target[p.indexOf("set") || typeof target["get" + p.substr(3)] !== "function" ? p : "get" + p.substr(3)]();
if (!prepend) if (first[p] !== values[0][p]) {
prepend = first;
}
}
this._beziers = vars.type !== "cubic" && vars.type !== "quadratic" && vars.type !== "soft" ? bezierThrough(values, isNaN(vars.curviness) ? 1 : vars.curviness, false, vars.type === "thruBasic", vars.correlate, prepend) : _parseBezierData(values, vars.type, first);
this._segCount = this._beziers[p].length;
if (this._timeRes) {
var ld = _parseLengthData(this._beziers, this._timeRes);
this._length = ld.length;
this._lengths = ld.lengths;
this._segments = ld.segments;
this._l1 = this._li = this._s1 = this._si = 0;
this._l2 = this._lengths[0];
this._curSeg = this._segments[0];
this._s2 = this._curSeg[0];
this._prec = 1 / this._curSeg.length;
}
if (autoRotate = this._autoRotate) {
this._initialRotations = [];
if (!(autoRotate[0] instanceof Array)) {
this._autoRotate = autoRotate = [autoRotate];
}
i = autoRotate.length;
while (--i > -1) {
for (j = 0; j < 3; j++) {
p = autoRotate[i][j];
this._func[p] = typeof target[p] === "function" ? target[p.indexOf("set") || typeof target["get" + p.substr(3)] !== "function" ? p : "get" + p.substr(3)] : false;
}
p = autoRotate[i][2];
this._initialRotations[i] = (this._func[p] ? this._func[p].call(this._target) : this._target[p]) || 0;
this._overwriteProps.push(p);
}
}
this._startRatio = tween.vars.runBackwards ? 1 : 0; //we determine the starting ratio when the tween inits which is always 0 unless the tween has runBackwards:true (indicating it's a from() tween) in which case it's 1.
return true;
},
//called each time the values should be updated, and the ratio gets passed as the only parameter (typically it's a value between 0 and 1, but it can exceed those when using an ease like Elastic.easeOut or Back.easeOut, etc.)
set: function set(v) {
var segments = this._segCount,
func = this._func,
target = this._target,
notStart = v !== this._startRatio,
curIndex,inv,i,p,b,t,val,l,lengths,curSeg;
if (!this._timeRes) {
curIndex = v < 0 ? 0 : v >= 1 ? segments - 1 : segments * v >> 0;
t = (v - curIndex * (1 / segments)) * segments;
} else {
lengths = this._lengths;
curSeg = this._curSeg;
v *= this._length;
i = this._li;
//find the appropriate segment (if the currently cached one isn't correct)
if (v > this._l2 && i < segments - 1) {
l = segments - 1;
while (i < l && (this._l2 = lengths[++i]) <= v) {}
this._l1 = lengths[i - 1];
this._li = i;
this._curSeg = curSeg = this._segments[i];
this._s2 = curSeg[this._s1 = this._si = 0];
} else if (v < this._l1 && i > 0) {
while (i > 0 && (this._l1 = lengths[--i]) >= v) {}
if (i === 0 && v < this._l1) {
this._l1 = 0;
} else {
i++;
}
this._l2 = lengths[i];
this._li = i;
this._curSeg = curSeg = this._segments[i];
this._s1 = curSeg[(this._si = curSeg.length - 1) - 1] || 0;
this._s2 = curSeg[this._si];
}
curIndex = i;
//now find the appropriate sub-segment (we split it into the number of pieces that was defined by "precision" and measured each one)
v -= this._l1;
i = this._si;
if (v > this._s2 && i < curSeg.length - 1) {
l = curSeg.length - 1;
while (i < l && (this._s2 = curSeg[++i]) <= v) {}
this._s1 = curSeg[i - 1];
this._si = i;
} else if (v < this._s1 && i > 0) {
while (i > 0 && (this._s1 = curSeg[--i]) >= v) {}
if (i === 0 && v < this._s1) {
this._s1 = 0;
} else {
i++;
}
this._s2 = curSeg[i];
this._si = i;
}
t = (i + (v - this._s1) / (this._s2 - this._s1)) * this._prec || 0;
}
inv = 1 - t;
i = this._props.length;
while (--i > -1) {
p = this._props[i];
b = this._beziers[p][curIndex];
val = (t * t * b.da + 3 * inv * (t * b.ca + inv * b.ba)) * t + b.a;
if (this._mod[p]) {
val = this._mod[p](val, target);
}
if (func[p]) {
target[p](val);
} else {
target[p] = val;
}
}
if (this._autoRotate) {
var ar = this._autoRotate,
b2,x1,y1,x2,y2,add,conv;
i = ar.length;
while (--i > -1) {
p = ar[i][2];
add = ar[i][3] || 0;
conv = ar[i][4] === true ? 1 : _RAD2DEG;
b = this._beziers[ar[i][0]];
b2 = this._beziers[ar[i][1]];
if (b && b2) {//in case one of the properties got overwritten.
b = b[curIndex];
b2 = b2[curIndex];
x1 = b.a + (b.b - b.a) * t;
x2 = b.b + (b.c - b.b) * t;
x1 += (x2 - x1) * t;
x2 += (b.c + (b.d - b.c) * t - x2) * t;
y1 = b2.a + (b2.b - b2.a) * t;
y2 = b2.b + (b2.c - b2.b) * t;
y1 += (y2 - y1) * t;
y2 += (b2.c + (b2.d - b2.c) * t - y2) * t;
val = notStart ? Math.atan2(y2 - y1, x2 - x1) * conv + add : this._initialRotations[i];
if (this._mod[p]) {
val = this._mod[p](val, target); //for modProps
}
if (func[p]) {
target[p](val);
} else {
target[p] = val;
}
}
}
}
} }),
p = BezierPlugin.prototype;
BezierPlugin.bezierThrough = bezierThrough;
BezierPlugin.cubicToQuadratic = cubicToQuadratic;
BezierPlugin._autoCSS = true; //indicates that this plugin can be inserted into the "css" object using the autoCSS feature of TweenLite
BezierPlugin.quadraticToCubic = function (a, b, c) {
return new Segment(a, (2 * b + a) / 3, (2 * b + c) / 3, c);
};
BezierPlugin._cssRegister = function () {
var CSSPlugin = _globals.CSSPlugin;
if (!CSSPlugin) {
return;
}
var _internals = CSSPlugin._internals,
_parseToProxy = _internals._parseToProxy,
_setPluginRatio = _internals._setPluginRatio,
CSSPropTween = _internals.CSSPropTween;
_internals._registerComplexSpecialProp("bezier", { parser: function parser(t, e, prop, cssp, pt, plugin) {
if (e instanceof Array) {
e = { values: e };
}
plugin = new BezierPlugin();
var values = e.values,
l = values.length - 1,
pluginValues = [],
v = {},
i,p,data;
if (l < 0) {
return pt;
}
for (i = 0; i <= l; i++) {
data = _parseToProxy(t, values[i], cssp, pt, plugin, l !== i);
pluginValues[i] = data.end;
}
for (p in e) {
v[p] = e[p]; //duplicate the vars object because we need to alter some things which would cause problems if the user plans to reuse the same vars object for another tween.
}
v.values = pluginValues;
pt = new CSSPropTween(t, "bezier", 0, 0, data.pt, 2);
pt.data = data;
pt.plugin = plugin;
pt.setRatio = _setPluginRatio;
if (v.autoRotate === 0) {
v.autoRotate = true;
}
if (v.autoRotate && !(v.autoRotate instanceof Array)) {
i = v.autoRotate === true ? 0 : Number(v.autoRotate);
v.autoRotate = data.end.left != null ? [["left", "top", "rotation", i, false]] : data.end.x != null ? [["x", "y", "rotation", i, false]] : false;
}
if (v.autoRotate) {
if (!cssp._transform) {
cssp._enableTransforms(false);
}
data.autoRotate = cssp._target._gsTransform;
data.proxy.rotation = data.autoRotate.rotation || 0;
cssp._overwriteProps.push("rotation");
}
plugin._onInitTween(data.proxy, v, cssp._tween);
return pt;
} });
};
p._mod = function (lookup) {
var op = this._overwriteProps,
i = op.length,
val;
while (--i > -1) {
val = lookup[op[i]];
if (val && typeof val === "function") {
this._mod[op[i]] = val;
}
}
};
p._kill = function (lookup) {
var a = this._props,
p,i;
for (p in this._beziers) {
if (p in lookup) {
delete this._beziers[p];
delete this._func[p];
i = a.length;
while (--i > -1) {
if (a[i] === p) {
a.splice(i, 1);
}
}
}
}
a = this._autoRotate;
if (a) {
i = a.length;
while (--i > -1) {
if (lookup[a[i][2]]) {
a.splice(i, 1);
}
}
}
return this._super._kill.call(this, lookup);
};
})();
/*
* ----------------------------------------------------------------
* CSSPlugin
* ----------------------------------------------------------------
*/
_gsScope._gsDefine("plugins.CSSPlugin", ["plugins.TweenPlugin", "TweenLite"], function (TweenPlugin, TweenLite) {
/** @constructor **/
var CSSPlugin = function CSSPlugin() {
TweenPlugin.call(this, "css");
this._overwriteProps.length = 0;
this.setRatio = CSSPlugin.prototype.setRatio; //speed optimization (avoid prototype lookup on this "hot" method)
},
_globals = _gsScope._gsDefine.globals,
_hasPriority, //turns true whenever a CSSPropTween instance is created that has a priority other than 0. This helps us discern whether or not we should spend the time organizing the linked list or not after a CSSPlugin's _onInitTween() method is called.
_suffixMap, //we set this in _onInitTween() each time as a way to have a persistent variable we can use in other methods like _parse() without having to pass it around as a parameter and we keep _parse() decoupled from a particular CSSPlugin instance
_cs, //computed style (we store this in a shared variable to conserve memory and make minification tighter
_overwriteProps, //alias to the currently instantiating CSSPlugin's _overwriteProps array. We use this closure in order to avoid having to pass a reference around from method to method and aid in minification.
_specialProps = {},
p = CSSPlugin.prototype = new TweenPlugin("css");
p.constructor = CSSPlugin;
CSSPlugin.version = "1.20.4";
CSSPlugin.API = 2;
CSSPlugin.defaultTransformPerspective = 0;
CSSPlugin.defaultSkewType = "compensated";
CSSPlugin.defaultSmoothOrigin = true;
p = "px"; //we'll reuse the "p" variable to keep file size down
CSSPlugin.suffixMap = { top: p, right: p, bottom: p, left: p, width: p, height: p, fontSize: p, padding: p, margin: p, perspective: p, lineHeight: "" };
var _numExp = /(?:\-|\.|\b)(\d|\.|e\-)+/g,
_relNumExp = /(?:\d|\-\d|\.\d|\-\.\d|\+=\d|\-=\d|\+=.\d|\-=\.\d)+/g,
_valuesExp = /(?:\+=|\-=|\-|\b)[\d\-\.]+[a-zA-Z0-9]*(?:%|\b)/gi, //finds all the values that begin with numbers or += or -= and then a number. Includes suffixes. We use this to split complex values apart like "1px 5px 20px rgb(255,102,51)"
_NaNExp = /(?![+-]?\d*\.?\d+|[+-]|e[+-]\d+)[^0-9]/g, //also allows scientific notation and doesn't kill the leading -/+ in -= and +=
_suffixExp = /(?:\d|\-|\+|=|#|\.)*/g,
_opacityExp = /opacity *= *([^)]*)/i,
_opacityValExp = /opacity:([^;]*)/i,
_alphaFilterExp = /alpha\(opacity *=.+?\)/i,
_rgbhslExp = /^(rgb|hsl)/,
_capsExp = /([A-Z])/g,
_camelExp = /-([a-z])/gi,
_urlExp = /(^(?:url\(\"|url\())|(?:(\"\))$|\)$)/gi, //for pulling out urls from url(...) or url("...") strings (some browsers wrap urls in quotes, some don't when reporting things like backgroundImage)
_camelFunc = function _camelFunc(s, g) {return g.toUpperCase();},
_horizExp = /(?:Left|Right|Width)/i,
_ieGetMatrixExp = /(M11|M12|M21|M22)=[\d\-\.e]+/gi,
_ieSetMatrixExp = /progid\:DXImageTransform\.Microsoft\.Matrix\(.+?\)/i,
_commasOutsideParenExp = /,(?=[^\)]*(?:\(|$))/gi, //finds any commas that are not within parenthesis
_complexExp = /[\s,\(]/i, //for testing a string to find if it has a space, comma, or open parenthesis (clues that it's a complex value)
_DEG2RAD = Math.PI / 180,
_RAD2DEG = 180 / Math.PI,
_forcePT = {},
_dummyElement = { style: {} },
_doc = _gsScope.document || { createElement: function createElement() {return _dummyElement;} },
_createElement = function _createElement(type, ns) {
return _doc.createElementNS ? _doc.createElementNS(ns || "http://www.w3.org/1999/xhtml", type) : _doc.createElement(type);
},
_tempDiv = _createElement("div"),
_tempImg = _createElement("img"),
_internals = CSSPlugin._internals = { _specialProps: _specialProps }, //provides a hook to a few internal methods that we need to access from inside other plugins
_agent = (_gsScope.navigator || {}).userAgent || "",
_autoRound,
_reqSafariFix, //we won't apply the Safari transform fix until we actually come across a tween that affects a transform property (to maintain best performance).
_isSafari,
_isFirefox, //Firefox has a bug that causes 3D transformed elements to randomly disappear unless a repaint is forced after each update on each element.
_isSafariLT6, //Safari (and Android 4 which uses a flavor of Safari) has a bug that prevents changes to "top" and "left" properties from rendering properly if changed on the same frame as a transform UNLESS we set the element's WebkitBackfaceVisibility to hidden (weird, I know). Doing this for Android 3 and earlier seems to actually cause other problems, though (fun!)
_ieVers,
_supportsOpacity = function () {//we set _isSafari, _ieVers, _isFirefox, and _supportsOpacity all in one function here to reduce file size slightly, especially in the minified version.
var i = _agent.indexOf("Android"),
a = _createElement("a");
_isSafari = _agent.indexOf("Safari") !== -1 && _agent.indexOf("Chrome") === -1 && (i === -1 || parseFloat(_agent.substr(i + 8, 2)) > 3);
_isSafariLT6 = _isSafari && parseFloat(_agent.substr(_agent.indexOf("Version/") + 8, 2)) < 6;
_isFirefox = _agent.indexOf("Firefox") !== -1;
if (/MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(_agent) || /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(_agent)) {
_ieVers = parseFloat(RegExp.$1);
}
if (!a) {
return false;
}
a.style.cssText = "top:1px;opacity:.55;";
return (/^0.55/.test(a.style.opacity));
}(),
_getIEOpacity = function _getIEOpacity(v) {
return _opacityExp.test(typeof v === "string" ? v : (v.currentStyle ? v.currentStyle.filter : v.style.filter) || "") ? parseFloat(RegExp.$1) / 100 : 1;
},
_log = function _log(s) {//for logging messages, but in a way that won't throw errors in old versions of IE.
if (_gsScope.console) {
console.log(s);
}
},
_target, //when initting a CSSPlugin, we set this variable so that we can access it from within many other functions without having to pass it around as params
_index, //when initting a CSSPlugin, we set this variable so that we can access it from within many other functions without having to pass it around as params
_prefixCSS = "", //the non-camelCase vendor prefix like "-o-", "-moz-", "-ms-", or "-webkit-"
_prefix = "", //camelCase vendor prefix like "O", "ms", "Webkit", or "Moz".
// @private feed in a camelCase property name like "transform" and it will check to see if it is valid as-is or if it needs a vendor prefix. It returns the corrected camelCase property name (i.e. "WebkitTransform" or "MozTransform" or "transform" or null if no such property is found, like if the browser is IE8 or before, "transform" won't be found at all)
_checkPropPrefix = function _checkPropPrefix(p, e) {
e = e || _tempDiv;
var s = e.style,
a,i;
if (s[p] !== undefined) {
return p;
}
p = p.charAt(0).toUpperCase() + p.substr(1);
a = ["O", "Moz", "ms", "Ms", "Webkit"];
i = 5;
while (--i > -1 && s[a[i] + p] === undefined) {}
if (i >= 0) {
_prefix = i === 3 ? "ms" : a[i];
_prefixCSS = "-" + _prefix.toLowerCase() + "-";
return _prefix + p;
}
return null;
},
_getComputedStyle = _doc.defaultView ? _doc.defaultView.getComputedStyle : function () {},
/**
* @private Returns the css style for a particular property of an element. For example, to get whatever the current "left" css value for an element with an ID of "myElement", you could do:
* var currentLeft = CSSPlugin.getStyle( document.getElementById("myElement"), "left");
*
* @param {!Object} t Target element whose style property you want to query
* @param {!string} p Property name (like "left" or "top" or "marginTop", etc.)
* @param {Object=} cs Computed style object. This just provides a way to speed processing if you're going to get several properties on the same element in quick succession - you can reuse the result of the getComputedStyle() call.
* @param {boolean=} calc If true, the value will not be read directly from the element's "style" property (if it exists there), but instead the getComputedStyle() result will be used. This can be useful when you want to ensure that the browser itself is interpreting the value.
* @param {string=} dflt Default value that should be returned in the place of null, "none", "auto" or "auto auto".
* @return {?string} The current property value
*/
_getStyle = CSSPlugin.getStyle = function (t, p, cs, calc, dflt) {
var rv;
if (!_supportsOpacity) if (p === "opacity") {//several versions of IE don't use the standard "opacity" property - they use things like filter:alpha(opacity=50), so we parse that here.
return _getIEOpacity(t);
}
if (!calc && t.style[p]) {
rv = t.style[p];
} else if (cs = cs || _getComputedStyle(t)) {
rv = cs[p] || cs.getPropertyValue(p) || cs.getPropertyValue(p.replace(_capsExp, "-$1").toLowerCase());
} else if (t.currentStyle) {
rv = t.currentStyle[p];
}
return dflt != null && (!rv || rv === "none" || rv === "auto" || rv === "auto auto") ? dflt : rv;
},
/**
* @private Pass the target element, the property name, the numeric value, and the suffix (like "%", "em", "px", etc.) and it will spit back the equivalent pixel number.
* @param {!Object} t Target element
* @param {!string} p Property name (like "left", "top", "marginLeft", etc.)
* @param {!number} v Value
* @param {string=} sfx Suffix (like "px" or "%" or "em")
* @param {boolean=} recurse If true, the call is a recursive one. In some browsers (like IE7/8), occasionally the value isn't accurately reported initially, but if we run the function again it will take effect.
* @return {number} value in pixels
*/
_convertToPixels = _internals.convertToPixels = function (t, p, v, sfx, recurse) {
if (sfx === "px" || !sfx && p !== "lineHeight") {return v;}
if (sfx === "auto" || !v) {return 0;}
var horiz = _horizExp.test(p),
node = t,
style = _tempDiv.style,
neg = v < 0,
precise = v === 1,
pix,cache,time;
if (neg) {
v = -v;
}
if (precise) {
v *= 100;
}
if (p === "lineHeight" && !sfx) {//special case of when a simple lineHeight (without a unit) is used. Set it to the value, read back the computed value, and then revert.
cache = _getComputedStyle(t).lineHeight;
t.style.lineHeight = v;
pix = parseFloat(_getComputedStyle(t).lineHeight);
t.style.lineHeight = cache;
} else if (sfx === "%" && p.indexOf("border") !== -1) {
pix = v / 100 * (horiz ? t.clientWidth : t.clientHeight);
} else {
style.cssText = "border:0 solid red;position:" + _getStyle(t, "position") + ";line-height:0;";
if (sfx === "%" || !node.appendChild || sfx.charAt(0) === "v" || sfx === "rem") {
node = t.parentNode || _doc.body;
if (_getStyle(node, "display").indexOf("flex") !== -1) {//Edge and IE11 have a bug that causes offsetWidth to report as 0 if the container has display:flex and the child is position:relative. Switching to position: absolute solves it.
style.position = "absolute";
}
cache = node._gsCache;
time = TweenLite.ticker.frame;
if (cache && horiz && cache.time === time) {//performance optimization: we record the width of elements along with the ticker frame so that we can quickly get it again on the same tick (seems relatively safe to assume it wouldn't change on the same tick)
return cache.width * v / 100;
}
style[horiz ? "width" : "height"] = v + sfx;
} else {
style[horiz ? "borderLeftWidth" : "borderTopWidth"] = v + sfx;
}
node.appendChild(_tempDiv);
pix = parseFloat(_tempDiv[horiz ? "offsetWidth" : "offsetHeight"]);
node.removeChild(_tempDiv);
if (horiz && sfx === "%" && CSSPlugin.cacheWidths !== false) {
cache = node._gsCache = node._gsCache || {};
cache.time = time;
cache.width = pix / v * 100;
}
if (pix === 0 && !recurse) {
pix = _convertToPixels(t, p, v, sfx, true);
}
}
if (precise) {
pix /= 100;
}
return neg ? -pix : pix;
},
_calculateOffset = _internals.calculateOffset = function (t, p, cs) {//for figuring out "top" or "left" in px when it's "auto". We need to factor in margin with the offsetLeft/offsetTop
if (_getStyle(t, "position", cs) !== "absolute") {return 0;}
var dim = p === "left" ? "Left" : "Top",
v = _getStyle(t, "margin" + dim, cs);
return t["offset" + dim] - (_convertToPixels(t, p, parseFloat(v), v.replace(_suffixExp, "")) || 0);
},
// @private returns at object containing ALL of the style properties in camelCase and their associated values.
_getAllStyles = function _getAllStyles(t, cs) {
var s = {},
i,tr,p;
if (cs = cs || _getComputedStyle(t, null)) {
if (i = cs.length) {
while (--i > -1) {
p = cs[i];
if (p.indexOf("-transform") === -1 || _transformPropCSS === p) {//Some webkit browsers duplicate transform values, one non-prefixed and one prefixed ("transform" and "WebkitTransform"), so we must weed out the extra one here.
s[p.replace(_camelExp, _camelFunc)] = cs.getPropertyValue(p);
}
}
} else {//some browsers behave differently - cs.length is always 0, so we must do a for...in loop.
for (i in cs) {
if (i.indexOf("Transform") === -1 || _transformProp === i) {//Some webkit browsers duplicate transform values, one non-prefixed and one prefixed ("transform" and "WebkitTransform"), so we must weed out the extra one here.
s[i] = cs[i];
}
}
}
} else if (cs = t.currentStyle || t.style) {
for (i in cs) {
if (typeof i === "string" && s[i] === undefined) {
s[i.replace(_camelExp, _camelFunc)] = cs[i];
}
}
}
if (!_supportsOpacity) {
s.opacity = _getIEOpacity(t);
}
tr = _getTransform(t, cs, false);
s.rotation = tr.rotation;
s.skewX = tr.skewX;
s.scaleX = tr.scaleX;
s.scaleY = tr.scaleY;
s.x = tr.x;
s.y = tr.y;
if (_supports3D) {
s.z = tr.z;
s.rotationX = tr.rotationX;
s.rotationY = tr.rotationY;
s.scaleZ = tr.scaleZ;
}
if (s.filters) {
delete s.filters;
}
return s;
},
// @private analyzes two style objects (as returned by _getAllStyles()) and only looks for differences between them that contain tweenable values (like a number or color). It returns an object with a "difs" property which refers to an object containing only those isolated properties and values for tweening, and a "firstMPT" property which refers to the first MiniPropTween instance in a linked list that recorded all the starting values of the different properties so that we can revert to them at the end or beginning of the tween - we don't want the cascading to get messed up. The forceLookup parameter is an optional generic object with properties that should be forced into the results - this is necessary for className tweens that are overwriting others because imagine a scenario where a rollover/rollout adds/removes a class and the user swipes the mouse over the target SUPER fast, thus nothing actually changed yet and the subsequent comparison of the properties would indicate they match (especially when px rounding is taken into consideration), thus no tweening is necessary even though it SHOULD tween and remove those properties after the tween (otherwise the inline styles will contaminate things). See the className SpecialProp code for details.
_cssDif = function _cssDif(t, s1, s2, vars, forceLookup) {
var difs = {},
style = t.style,
val,p,mpt;
for (p in s2) {
if (p !== "cssText") if (p !== "length") if (isNaN(p)) if (s1[p] !== (val = s2[p]) || forceLookup && forceLookup[p]) if (p.indexOf("Origin") === -1) if (typeof val === "number" || typeof val === "string") {
difs[p] = val === "auto" && (p === "left" || p === "top") ? _calculateOffset(t, p) : (val === "" || val === "auto" || val === "none") && typeof s1[p] === "string" && s1[p].replace(_NaNExp, "") !== "" ? 0 : val; //if the ending value is defaulting ("" or "auto"), we check the starting value and if it can be parsed into a number (a string which could have a suffix too, like 700px), then we swap in 0 for "" or "auto" so that things actually tween.
if (style[p] !== undefined) {//for className tweens, we must remember which properties already existed inline - the ones that didn't should be removed when the tween isn't in progress because they were only introduced to facilitate the transition between classes.
mpt = new MiniPropTween(style, p, style[p], mpt);
}
}
}
if (vars) {
for (p in vars) {//copy properties (except className)
if (p !== "className") {
difs[p] = vars[p];
}
}
}
return { difs: difs, firstMPT: mpt };
},
_dimensions = { width: ["Left", "Right"], height: ["Top", "Bottom"] },
_margins = ["marginLeft", "marginRight", "marginTop", "marginBottom"],
/**
* @private Gets the width or height of an element
* @param {!Object} t Target element
* @param {!string} p Property name ("width" or "height")
* @param {Object=} cs Computed style object (if one exists). Just a speed optimization.
* @return {number} Dimension (in pixels)
*/
_getDimension = function _getDimension(t, p, cs) {
if ((t.nodeName + "").toLowerCase() === "svg") {//Chrome no longer supports offsetWidth/offsetHeight on SVG elements.
return (cs || _getComputedStyle(t))[p] || 0;
} else if (t.getCTM && _isSVG(t)) {
return t.getBBox()[p] || 0;
}
var v = parseFloat(p === "width" ? t.offsetWidth : t.offsetHeight),
a = _dimensions[p],
i = a.length;
cs = cs || _getComputedStyle(t, null);
while (--i > -1) {
v -= parseFloat(_getStyle(t, "padding" + a[i], cs, true)) || 0;
v -= parseFloat(_getStyle(t, "border" + a[i] + "Width", cs, true)) || 0;
}
return v;
},
// @private Parses position-related complex strings like "top left" or "50px 10px" or "70% 20%", etc. which are used for things like transformOrigin or backgroundPosition. Optionally decorates a supplied object (recObj) with the following properties: "ox" (offsetX), "oy" (offsetY), "oxp" (if true, "ox" is a percentage not a pixel value), and "oxy" (if true, "oy" is a percentage not a pixel value)
_parsePosition = function _parsePosition(v, recObj) {
if (v === "contain" || v === "auto" || v === "auto auto") {//note: Firefox uses "auto auto" as default whereas Chrome uses "auto".
return v + " ";
}
if (v == null || v === "") {
v = "0 0";
}
var a = v.split(" "),
x = v.indexOf("left") !== -1 ? "0%" : v.indexOf("right") !== -1 ? "100%" : a[0],
y = v.indexOf("top") !== -1 ? "0%" : v.indexOf("bottom") !== -1 ? "100%" : a[1],
i;
if (a.length > 3 && !recObj) {//multiple positions
a = v.split(", ").join(",").split(",");
v = [];
for (i = 0; i < a.length; i++) {
v.push(_parsePosition(a[i]));
}
return v.join(",");
}
if (y == null) {
y = x === "center" ? "50%" : "0";
} else if (y === "center") {
y = "50%";
}
if (x === "center" || isNaN(parseFloat(x)) && (x + "").indexOf("=") === -1) {//remember, the user could flip-flop the values and say "bottom center" or "center bottom", etc. "center" is ambiguous because it could be used to describe horizontal or vertical, hence the isNaN(). If there's an "=" sign in the value, it's relative.
x = "50%";
}
v = x + " " + y + (a.length > 2 ? " " + a[2] : "");
if (recObj) {
recObj.oxp = x.indexOf("%") !== -1;
recObj.oyp = y.indexOf("%") !== -1;
recObj.oxr = x.charAt(1) === "=";
recObj.oyr = y.charAt(1) === "=";
recObj.ox = parseFloat(x.replace(_NaNExp, ""));
recObj.oy = parseFloat(y.replace(_NaNExp, ""));
recObj.v = v;
}
return recObj || v;
},
/**
* @private Takes an ending value (typically a string, but can be a number) and a starting value and returns the change between the two, looking for relative value indicators like += and -= and it also ignores suffixes (but make sure the ending value starts with a number or +=/-= and that the starting value is a NUMBER!)
* @param {(number|string)} e End value which is typically a string, but could be a number
* @param {(number|string)} b Beginning value which is typically a string but could be a number
* @return {number} Amount of change between the beginning and ending values (relative values that have a "+=" or "-=" are recognized)
*/
_parseChange = function _parseChange(e, b) {
if (typeof e === "function") {
e = e(_index, _target);
}
return typeof e === "string" && e.charAt(1) === "=" ? parseInt(e.charAt(0) + "1", 10) * parseFloat(e.substr(2)) : parseFloat(e) - parseFloat(b) || 0;
},
/**
* @private Takes a value and a default number, checks if the value is relative, null, or numeric and spits back a normalized number accordingly. Primarily used in the _parseTransform() function.
* @param {Object} v Value to be parsed
* @param {!number} d Default value (which is also used for relative calculations if "+=" or "-=" is found in the first parameter)
* @return {number} Parsed value
*/
_parseVal = function _parseVal(v, d) {
if (typeof v === "function") {
v = v(_index, _target);
}
return v == null ? d : typeof v === "string" && v.charAt(1) === "=" ? parseInt(v.charAt(0) + "1", 10) * parseFloat(v.substr(2)) + d : parseFloat(v) || 0;
},
/**
* @private Translates strings like "40deg" or "40" or 40rad" or "+=40deg" or "270_short" or "-90_cw" or "+=45_ccw" to a numeric radian angle. Of course a starting/default value must be fed in too so that relative values can be calculated properly.
* @param {Object} v Value to be parsed
* @param {!number} d Default value (which is also used for relative calculations if "+=" or "-=" is found in the first parameter)
* @param {string=} p property name for directionalEnd (optional - only used when the parsed value is directional ("_short", "_cw", or "_ccw" suffix). We need a way to store the uncompensated value so that at the end of the tween, we set it to exactly what was requested with no directional compensation). Property name would be "rotation", "rotationX", or "rotationY"
* @param {Object=} directionalEnd An object that will store the raw end values for directional angles ("_short", "_cw", or "_ccw" suffix). We need a way to store the uncompensated value so that at the end of the tween, we set it to exactly what was requested with no directional compensation.
* @return {number} parsed angle in radians
*/
_parseAngle = function _parseAngle(v, d, p, directionalEnd) {
var min = 0.000001,
cap,split,dif,result,isRelative;
if (typeof v === "function") {
v = v(_index, _target);
}
if (v == null) {
result = d;
} else if (typeof v === "number") {
result = v;
} else {
cap = 360;
split = v.split("_");
isRelative = v.charAt(1) === "=";
dif = (isRelative ? parseInt(v.charAt(0) + "1", 10) * parseFloat(split[0].substr(2)) : parseFloat(split[0])) * (v.indexOf("rad") === -1 ? 1 : _RAD2DEG) - (isRelative ? 0 : d);
if (split.length) {
if (directionalEnd) {
directionalEnd[p] = d + dif;
}
if (v.indexOf("short") !== -1) {
dif = dif % cap;
if (dif !== dif % (cap / 2)) {
dif = dif < 0 ? dif + cap : dif - cap;
}
}
if (v.indexOf("_cw") !== -1 && dif < 0) {
dif = (dif + cap * 9999999999) % cap - (dif / cap | 0) * cap;
} else if (v.indexOf("ccw") !== -1 && dif > 0) {
dif = (dif - cap * 9999999999) % cap - (dif / cap | 0) * cap;
}
}
result = d + dif;
}
if (result < min && result > -min) {
result = 0;
}
return result;
},
_colorLookup = { aqua: [0, 255, 255],
lime: [0, 255, 0],
silver: [192, 192, 192],
black: [0, 0, 0],
maroon: [128, 0, 0],
teal: [0, 128, 128],
blue: [0, 0, 255],
navy: [0, 0, 128],
white: [255, 255, 255],
fuchsia: [255, 0, 255],
olive: [128, 128, 0],
yellow: [255, 255, 0],
orange: [255, 165, 0],
gray: [128, 128, 128],
purple: [128, 0, 128],
green: [0, 128, 0],
red: [255, 0, 0],
pink: [255, 192, 203],
cyan: [0, 255, 255],
transparent: [255, 255, 255, 0] },
_hue = function _hue(h, m1, m2) {
h = h < 0 ? h + 1 : h > 1 ? h - 1 : h;
return (h * 6 < 1 ? m1 + (m2 - m1) * h * 6 : h < 0.5 ? m2 : h * 3 < 2 ? m1 + (m2 - m1) * (2 / 3 - h) * 6 : m1) * 255 + 0.5 | 0;
},
/**
* @private Parses a color (like #9F0, #FF9900, rgb(255,51,153) or hsl(108, 50%, 10%)) into an array with 3 elements for red, green, and blue or if toHSL parameter is true, it will populate the array with hue, saturation, and lightness values. If a relative value is found in an hsl() or hsla() string, it will preserve those relative prefixes and all the values in the array will be strings instead of numbers (in all other cases it will be populated with numbers).
* @param {(string|number)} v The value the should be parsed which could be a string like #9F0 or rgb(255,102,51) or rgba(255,0,0,0.5) or it could be a number like 0xFF00CC or even a named color like red, blue, purple, etc.
* @param {(boolean)} toHSL If true, an hsl() or hsla() value will be returned instead of rgb() or rgba()
* @return {Array.<number>} An array containing red, green, and blue (and optionally alpha) in that order, or if the toHSL parameter was true, the array will contain hue, saturation and lightness (and optionally alpha) in that order. Always numbers unless there's a relative prefix found in an hsl() or hsla() string and toHSL is true.
*/
_parseColor = CSSPlugin.parseColor = function (v, toHSL) {
var a, r, g, b, h, s, l, max, min, d, wasHSL;
if (!v) {
a = _colorLookup.black;
} else if (typeof v === "number") {
a = [v >> 16, v >> 8 & 255, v & 255];
} else {
if (v.charAt(v.length - 1) === ",") {//sometimes a trailing comma is included and we should chop it off (typically from a comma-delimited list of values like a textShadow:"2px 2px 2px blue, 5px 5px 5px rgb(255,0,0)" - in this example "blue," has a trailing comma. We could strip it out inside parseComplex() but we'd need to do it to the beginning and ending values plus it wouldn't provide protection from other potential scenarios like if the user passes in a similar value.
v = v.substr(0, v.length - 1);
}
if (_colorLookup[v]) {
a = _colorLookup[v];
} else if (v.charAt(0) === "#") {
if (v.length === 4) {//for shorthand like #9F0
r = v.charAt(1);
g = v.charAt(2);
b = v.charAt(3);
v = "#" + r + r + g + g + b + b;
}
v = parseInt(v.substr(1), 16);
a = [v >> 16, v >> 8 & 255, v & 255];
} else if (v.substr(0, 3) === "hsl") {
a = wasHSL = v.match(_numExp);
if (!toHSL) {
h = Number(a[0]) % 360 / 360;
s = Number(a[1]) / 100;
l = Number(a[2]) / 100;
g = l <= 0.5 ? l * (s + 1) : l + s - l * s;
r = l * 2 - g;
if (a.length > 3) {
a[3] = Number(a[3]);
}
a[0] = _hue(h + 1 / 3, r, g);
a[1] = _hue(h, r, g);
a[2] = _hue(h - 1 / 3, r, g);
} else if (v.indexOf("=") !== -1) {//if relative values are found, just return the raw strings with the relative prefixes in place.
return v.match(_relNumExp);
}
} else {
a = v.match(_numExp) || _colorLookup.transparent;
}
a[0] = Number(a[0]);
a[1] = Number(a[1]);
a[2] = Number(a[2]);
if (a.length > 3) {
a[3] = Number(a[3]);
}
}
if (toHSL && !wasHSL) {
r = a[0] / 255;
g = a[1] / 255;
b = a[2] / 255;
max = Math.max(r, g, b);
min = Math.min(r, g, b);
l = (max + min) / 2;
if (max === min) {
h = s = 0;
} else {
d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
h = max === r ? (g - b) / d + (g < b ? 6 : 0) : max === g ? (b - r) / d + 2 : (r - g) / d + 4;
h *= 60;
}
a[0] = h + 0.5 | 0;
a[1] = s * 100 + 0.5 | 0;
a[2] = l * 100 + 0.5 | 0;
}
return a;
},
_formatColors = function _formatColors(s, toHSL) {
var colors = s.match(_colorExp) || [],
charIndex = 0,
parsed = "",
i,color,temp;
if (!colors.length) {
return s;
}
for (i = 0; i < colors.length; i++) {
color = colors[i];
temp = s.substr(charIndex, s.indexOf(color, charIndex) - charIndex);
charIndex += temp.length + color.length;
color = _parseColor(color, toHSL);
if (color.length === 3) {
color.push(1);
}
parsed += temp + (toHSL ? "hsla(" + color[0] + "," + color[1] + "%," + color[2] + "%," + color[3] : "rgba(" + color.join(",")) + ")";
}
return parsed + s.substr(charIndex);
},
_colorExp = "(?:\\b(?:(?:rgb|rgba|hsl|hsla)\\(.+?\\))|\\B#(?:[0-9a-f]{3}){1,2}\\b"; //we'll dynamically build this Regular Expression to conserve file size. After building it, it will be able to find rgb(), rgba(), # (hexadecimal), and named color values like red, blue, purple, etc.
for (p in _colorLookup) {
_colorExp += "|" + p + "\\b";
}
_colorExp = new RegExp(_colorExp + ")", "gi");
CSSPlugin.colorStringFilter = function (a) {
var combined = a[0] + " " + a[1],
toHSL;
if (_colorExp.test(combined)) {
toHSL = combined.indexOf("hsl(") !== -1 || combined.indexOf("hsla(") !== -1;
a[0] = _formatColors(a[0], toHSL);
a[1] = _formatColors(a[1], toHSL);
}
_colorExp.lastIndex = 0;
};
if (!TweenLite.defaultStringFilter) {
TweenLite.defaultStringFilter = CSSPlugin.colorStringFilter;
}
/**
* @private Returns a formatter function that handles taking a string (or number in some cases) and returning a consistently formatted one in terms of delimiters, quantity of values, etc. For example, we may get boxShadow values defined as "0px red" or "0px 0px 10px rgb(255,0,0)" or "0px 0px 20px 20px #F00" and we need to ensure that what we get back is described with 4 numbers and a color. This allows us to feed it into the _parseComplex() method and split the values up appropriately. The neat thing about this _getFormatter() function is that the dflt defines a pattern as well as a default, so for example, _getFormatter("0px 0px 0px 0px #777", true) not only sets the default as 0px for all distances and #777 for the color, but also sets the pattern such that 4 numbers and a color will always get returned.
* @param {!string} dflt The default value and pattern to follow. So "0px 0px 0px 0px #777" will ensure that 4 numbers and a color will always get returned.
* @param {boolean=} clr If true, the values should be searched for color-related data. For example, boxShadow values typically contain a color whereas borderRadius don't.
* @param {boolean=} collapsible If true, the value is a top/left/right/bottom style one that acts like margin or padding, where if only one value is received, it's used for all 4; if 2 are received, the first is duplicated for 3rd (bottom) and the 2nd is duplicated for the 4th spot (left), etc.
* @return {Function} formatter function
*/
var _getFormatter = function _getFormatter(dflt, clr, collapsible, multi) {
if (dflt == null) {
return function (v) {return v;};
}
var dColor = clr ? (dflt.match(_colorExp) || [""])[0] : "",
dVals = dflt.split(dColor).join("").match(_valuesExp) || [],
pfx = dflt.substr(0, dflt.indexOf(dVals[0])),
sfx = dflt.charAt(dflt.length - 1) === ")" ? ")" : "",
delim = dflt.indexOf(" ") !== -1 ? " " : ",",
numVals = dVals.length,
dSfx = numVals > 0 ? dVals[0].replace(_numExp, "") : "",
_formatter2;
if (!numVals) {
return function (v) {return v;};
}
if (clr) {
_formatter2 = function formatter(v) {
var color, vals, i, a;
if (typeof v === "number") {
v += dSfx;
} else if (multi && _commasOutsideParenExp.test(v)) {
a = v.replace(_commasOutsideParenExp, "|").split("|");
for (i = 0; i < a.length; i++) {
a[i] = _formatter2(a[i]);
}
return a.join(",");
}
color = (v.match(_colorExp) || [dColor])[0];
vals = v.split(color).join("").match(_valuesExp) || [];
i = vals.length;
if (numVals > i--) {
while (++i < numVals) {
vals[i] = collapsible ? vals[(i - 1) / 2 | 0] : dVals[i];
}
}
return pfx + vals.join(delim) + delim + color + sfx + (v.indexOf("inset") !== -1 ? " inset" : "");
};
return _formatter2;
}
_formatter2 = function _formatter(v) {
var vals, a, i;
if (typeof v === "number") {
v += dSfx;
} else if (multi && _commasOutsideParenExp.test(v)) {
a = v.replace(_commasOutsideParenExp, "|").split("|");
for (i = 0; i < a.length; i++) {
a[i] = _formatter2(a[i]);
}
return a.join(",");
}
vals = v.match(_valuesExp) || [];
i = vals.length;
if (numVals > i--) {
while (++i < numVals) {
vals[i] = collapsible ? vals[(i - 1) / 2 | 0] : dVals[i];
}
}
return pfx + vals.join(delim) + sfx;
};
return _formatter2;
},
/**
* @private returns a formatter function that's used for edge-related values like marginTop, marginLeft, paddingBottom, paddingRight, etc. Just pass a comma-delimited list of property names related to the edges.
* @param {!string} props a comma-delimited list of property names in order from top to left, like "marginTop,marginRight,marginBottom,marginLeft"
* @return {Function} a formatter function
*/
_getEdgeParser = function _getEdgeParser(props) {
props = props.split(",");
return function (t, e, p, cssp, pt, plugin, vars) {
var a = (e + "").split(" "),
i;
vars = {};
for (i = 0; i < 4; i++) {
vars[props[i]] = a[i] = a[i] || a[(i - 1) / 2 >> 0];
}
return cssp.parse(t, vars, pt, plugin);
};
},
// @private used when other plugins must tween values first, like BezierPlugin or ThrowPropsPlugin, etc. That plugin's setRatio() gets called first so that the values are updated, and then we loop through the MiniPropTweens which handle copying the values into their appropriate slots so that they can then be applied correctly in the main CSSPlugin setRatio() method. Remember, we typically create a proxy object that has a bunch of uniquely-named properties that we feed to the sub-plugin and it does its magic normally, and then we must interpret those values and apply them to the css because often numbers must get combined/concatenated, suffixes added, etc. to work with css, like boxShadow could have 4 values plus a color.
_setPluginRatio = _internals._setPluginRatio = function (v) {
this.plugin.setRatio(v);
var d = this.data,
proxy = d.proxy,
mpt = d.firstMPT,
min = 0.000001,
val,pt,i,str,p;
while (mpt) {
val = proxy[mpt.v];
if (mpt.r) {
val = Math.round(val);
} else if (val < min && val > -min) {
val = 0;
}
mpt.t[mpt.p] = val;
mpt = mpt._next;
}
if (d.autoRotate) {
d.autoRotate.rotation = d.mod ? d.mod(proxy.rotation, this.t) : proxy.rotation; //special case for ModifyPlugin to hook into an auto-rotating bezier
}
//at the end, we must set the CSSPropTween's "e" (end) value dynamically here because that's what is used in the final setRatio() method. Same for "b" at the beginning.
if (v === 1 || v === 0) {
mpt = d.firstMPT;
p = v === 1 ? "e" : "b";
while (mpt) {
pt = mpt.t;
if (!pt.type) {
pt[p] = pt.s + pt.xs0;
} else if (pt.type === 1) {
str = pt.xs0 + pt.s + pt.xs1;
for (i = 1; i < pt.l; i++) {
str += pt["xn" + i] + pt["xs" + (i + 1)];
}
pt[p] = str;
}
mpt = mpt._next;
}
}
},
/**
* @private @constructor Used by a few SpecialProps to hold important values for proxies. For example, _parseToProxy() creates a MiniPropTween instance for each property that must get tweened on the proxy, and we record the original property name as well as the unique one we create for the proxy, plus whether or not the value needs to be rounded plus the original value.
* @param {!Object} t target object whose property we're tweening (often a CSSPropTween)
* @param {!string} p property name
* @param {(number|string|object)} v value
* @param {MiniPropTween=} next next MiniPropTween in the linked list
* @param {boolean=} r if true, the tweened value should be rounded to the nearest integer
*/
MiniPropTween = function MiniPropTween(t, p, v, next, r) {
this.t = t;
this.p = p;
this.v = v;
this.r = r;
if (next) {
next._prev = this;
this._next = next;
}
},
/**
* @private Most other plugins (like BezierPlugin and ThrowPropsPlugin and others) can only tween numeric values, but CSSPlugin must accommodate special values that have a bunch of extra data (like a suffix or strings between numeric values, etc.). For example, boxShadow has values like "10px 10px 20px 30px rgb(255,0,0)" which would utterly confuse other plugins. This method allows us to split that data apart and grab only the numeric data and attach it to uniquely-named properties of a generic proxy object ({}) so that we can feed that to virtually any plugin to have the numbers tweened. However, we must also keep track of which properties from the proxy go with which CSSPropTween values and instances. So we create a linked list of MiniPropTweens. Each one records a target (the original CSSPropTween), property (like "s" or "xn1" or "xn2") that we're tweening and the unique property name that was used for the proxy (like "boxShadow_xn1" and "boxShadow_xn2") and whether or not they need to be rounded. That way, in the _setPluginRatio() method we can simply copy the values over from the proxy to the CSSPropTween instance(s). Then, when the main CSSPlugin setRatio() method runs and applies the CSSPropTween values accordingly, they're updated nicely. So the external plugin tweens the numbers, _setPluginRatio() copies them over, and setRatio() acts normally, applying css-specific values to the element.
* This method returns an object that has the following properties:
* - proxy: a generic object containing the starting values for all the properties that will be tweened by the external plugin. This is what we feed to the external _onInitTween() as the target
* - end: a generic object containing the ending values for all the properties that will be tweened by the external plugin. This is what we feed to the external plugin's _onInitTween() as the destination values
* - firstMPT: the first MiniPropTween in the linked list
* - pt: the first CSSPropTween in the linked list that was created when parsing. If shallow is true, this linked list will NOT attach to the one passed into the _parseToProxy() as the "pt" (4th) parameter.
* @param {!Object} t target object to be tweened
* @param {!(Object|string)} vars the object containing the information about the tweening values (typically the end/destination values) that should be parsed
* @param {!CSSPlugin} cssp The CSSPlugin instance
* @param {CSSPropTween=} pt the next CSSPropTween in the linked list
* @param {TweenPlugin=} plugin the external TweenPlugin instance that will be handling tweening the numeric values
* @param {boolean=} shallow if true, the resulting linked list from the parse will NOT be attached to the CSSPropTween that was passed in as the "pt" (4th) parameter.
* @return An object containing the following properties: proxy, end, firstMPT, and pt (see above for descriptions)
*/
_parseToProxy = _internals._parseToProxy = function (t, vars, cssp, pt, plugin, shallow) {
var bpt = pt,
start = {},
end = {},
transform = cssp._transform,
oldForce = _forcePT,
i,p,xp,mpt,firstPT;
cssp._transform = null;
_forcePT = vars;
pt = firstPT = cssp.parse(t, vars, pt, plugin);
_forcePT = oldForce;
//break off from the linked list so the new ones are isolated.
if (shallow) {
cssp._transform = transform;
if (bpt) {
bpt._prev = null;
if (bpt._prev) {
bpt._prev._next = null;
}
}
}
while (pt && pt !== bpt) {
if (pt.type <= 1) {
p = pt.p;
end[p] = pt.s + pt.c;
start[p] = pt.s;
if (!shallow) {
mpt = new MiniPropTween(pt, "s", p, mpt, pt.r);
pt.c = 0;
}
if (pt.type === 1) {
i = pt.l;
while (--i > 0) {
xp = "xn" + i;
p = pt.p + "_" + xp;
end[p] = pt.data[xp];
start[p] = pt[xp];
if (!shallow) {
mpt = new MiniPropTween(pt, xp, p, mpt, pt.rxp[xp]);
}
}
}
}
pt = pt._next;
}
return { proxy: start, end: end, firstMPT: mpt, pt: firstPT };
},
/**
* @constructor Each property that is tweened has at least one CSSPropTween associated with it. These instances store important information like the target, property, starting value, amount of change, etc. They can also optionally have a number of "extra" strings and numeric values named xs1, xn1, xs2, xn2, xs3, xn3, etc. where "s" indicates string and "n" indicates number. These can be pieced together in a complex-value tween (type:1) that has alternating types of data like a string, number, string, number, etc. For example, boxShadow could be "5px 5px 8px rgb(102, 102, 51)". In that value, there are 6 numbers that may need to tween and then pieced back together into a string again with spaces, suffixes, etc. xs0 is special in that it stores the suffix for standard (type:0) tweens, -OR- the first string (prefix) in a complex-value (type:1) CSSPropTween -OR- it can be the non-tweening value in a type:-1 CSSPropTween. We do this to conserve memory.
* CSSPropTweens have the following optional properties as well (not defined through the constructor):
* - l: Length in terms of the number of extra properties that the CSSPropTween has (default: 0). For example, for a boxShadow we may need to tween 5 numbers in which case l would be 5; Keep in mind that the start/end values for the first number that's tweened are always stored in the s and c properties to conserve memory. All additional values thereafter are stored in xn1, xn2, etc.
* - xfirst: The first instance of any sub-CSSPropTweens that are tweening properties of this instance. For example, we may split up a boxShadow tween so that there's a main CSSPropTween of type:1 that has various xs* and xn* values associated with the h-shadow, v-shadow, blur, color, etc. Then we spawn a CSSPropTween for each of those that has a higher priority and runs BEFORE the main CSSPropTween so that the values are all set by the time it needs to re-assemble them. The xfirst gives us an easy way to identify the first one in that chain which typically ends at the main one (because they're all prepende to the linked list)
* - plugin: The TweenPlugin instance that will handle the tweening of any complex values. For example, sometimes we don't want to use normal subtweens (like xfirst refers to) to tween the values - we might want ThrowPropsPlugin or BezierPlugin some other plugin to do the actual tweening, so we create a plugin instance and store a reference here. We need this reference so that if we get a request to round values or disable a tween, we can pass along that request.
* - data: Arbitrary data that needs to be stored with the CSSPropTween. Typically if we're going to have a plugin handle the tweening of a complex-value tween, we create a generic object that stores the END values that we're tweening to and the CSSPropTween's xs1, xs2, etc. have the starting values. We store that object as data. That way, we can simply pass that object to the plugin and use the CSSPropTween as the target.
* - setRatio: Only used for type:2 tweens that require custom functionality. In this case, we call the CSSPropTween's setRatio() method and pass the ratio each time the tween updates. This isn't quite as efficient as doing things directly in the CSSPlugin's setRatio() method, but it's very convenient and flexible.
* @param {!Object} t Target object whose property will be tweened. Often a DOM element, but not always. It could be anything.
* @param {string} p Property to tween (name). For example, to tween element.width, p would be "width".
* @param {number} s Starting numeric value
* @param {number} c Change in numeric value over the course of the entire tween. For example, if element.width starts at 5 and should end at 100, c would be 95.
* @param {CSSPropTween=} next The next CSSPropTween in the linked list. If one is defined, we will define its _prev as the new instance, and the new instance's _next will be pointed at it.
* @param {number=} type The type of CSSPropTween where -1 = a non-tweening value, 0 = a standard simple tween, 1 = a complex value (like one that has multiple numbers in a comma- or space-delimited string like border:"1px solid red"), and 2 = one that uses a custom setRatio function that does all of the work of applying the values on each update.
* @param {string=} n Name of the property that should be used for overwriting purposes which is typically the same as p but not always. For example, we may need to create a subtween for the 2nd part of a "clip:rect(...)" tween in which case "p" might be xs1 but "n" is still "clip"
* @param {boolean=} r If true, the value(s) should be rounded
* @param {number=} pr Priority in the linked list order. Higher priority CSSPropTweens will be updated before lower priority ones. The default priority is 0.
* @param {string=} b Beginning value. We store this to ensure that it is EXACTLY what it was when the tween began without any risk of interpretation issues.
* @param {string=} e Ending value. We store this to ensure that it is EXACTLY what the user defined at the end of the tween without any risk of interpretation issues.
*/
CSSPropTween = _internals.CSSPropTween = function (t, p, s, c, next, type, n, r, pr, b, e) {
this.t = t; //target
this.p = p; //property
this.s = s; //starting value
this.c = c; //change value
this.n = n || p; //name that this CSSPropTween should be associated to (usually the same as p, but not always - n is what overwriting looks at)
if (!(t instanceof CSSPropTween)) {
_overwriteProps.push(this.n);
}
this.r = r; //round (boolean)
this.type = type || 0; //0 = normal tween, -1 = non-tweening (in which case xs0 will be applied to the target's property, like tp.t[tp.p] = tp.xs0), 1 = complex-value SpecialProp, 2 = custom setRatio() that does all the work
if (pr) {
this.pr = pr;
_hasPriority = true;
}
this.b = b === undefined ? s : b;
this.e = e === undefined ? s + c : e;
if (next) {
this._next = next;
next._prev = this;
}
},
_addNonTweeningNumericPT = function _addNonTweeningNumericPT(target, prop, start, end, next, overwriteProp) {//cleans up some code redundancies and helps minification. Just a fast way to add a NUMERIC non-tweening CSSPropTween
var pt = new CSSPropTween(target, prop, start, end - start, next, -1, overwriteProp);
pt.b = start;
pt.e = pt.xs0 = end;
return pt;
},
/**
* Takes a target, the beginning value and ending value (as strings) and parses them into a CSSPropTween (possibly with child CSSPropTweens) that accommodates multiple numbers, colors, comma-delimited values, etc. For example:
* sp.parseComplex(element, "boxShadow", "5px 10px 20px rgb(255,102,51)", "0px 0px 0px red", true, "0px 0px 0px rgb(0,0,0,0)", pt);
* It will walk through the beginning and ending values (which should be in the same format with the same number and type of values) and figure out which parts are numbers, what strings separate the numeric/tweenable values, and then create the CSSPropTweens accordingly. If a plugin is defined, no child CSSPropTweens will be created. Instead, the ending values will be stored in the "data" property of the returned CSSPropTween like: {s:-5, xn1:-10, xn2:-20, xn3:255, xn4:0, xn5:0} so that it can be fed to any other plugin and it'll be plain numeric tweens but the recomposition of the complex value will be handled inside CSSPlugin's setRatio().
* If a setRatio is defined, the type of the CSSPropTween will be set to 2 and recomposition of the values will be the responsibility of that method.
*
* @param {!Object} t Target whose property will be tweened
* @param {!string} p Property that will be tweened (its name, like "left" or "backgroundColor" or "boxShadow")
* @param {string} b Beginning value
* @param {string} e Ending value
* @param {boolean} clrs If true, the value could contain a color value like "rgb(255,0,0)" or "#F00" or "red". The default is false, so no colors will be recognized (a performance optimization)
* @param {(string|number|Object)} dflt The default beginning value that should be used if no valid beginning value is defined or if the number of values inside the complex beginning and ending values don't match
* @param {?CSSPropTween} pt CSSPropTween instance that is the current head of the linked list (we'll prepend to this).
* @param {number=} pr Priority in the linked list order. Higher priority properties will be updated before lower priority ones. The default priority is 0.
* @param {TweenPlugin=} plugin If a plugin should handle the tweening of extra properties, pass the plugin instance here. If one is defined, then NO subtweens will be created for any extra properties (the properties will be created - just not additional CSSPropTween instances to tween them) because the plugin is expected to do so. However, the end values WILL be populated in the "data" property, like {s:100, xn1:50, xn2:300}
* @param {function(number)=} setRatio If values should be set in a custom function instead of being pieced together in a type:1 (complex-value) CSSPropTween, define that custom function here.
* @return {CSSPropTween} The first CSSPropTween in the linked list which includes the new one(s) added by the parseComplex() call.
*/
_parseComplex = CSSPlugin.parseComplex = function (t, p, b, e, clrs, dflt, pt, pr, plugin, setRatio) {
//DEBUG: _log("parseComplex: "+p+", b: "+b+", e: "+e);
b = b || dflt || "";
if (typeof e === "function") {
e = e(_index, _target);
}
pt = new CSSPropTween(t, p, 0, 0, pt, setRatio ? 2 : 1, null, false, pr, b, e);
e += ""; //ensures it's a string
if (clrs && _colorExp.test(e + b)) {//if colors are found, normalize the formatting to rgba() or hsla().
e = [b, e];
CSSPlugin.colorStringFilter(e);
b = e[0];
e = e[1];
}
var ba = b.split(", ").join(",").split(" "), //beginning array
ea = e.split(", ").join(",").split(" "), //ending array
l = ba.length,
autoRound = _autoRound !== false,
i,xi,ni,bv,ev,bnums,enums,bn,hasAlpha,temp,cv,str,useHSL;
if (e.indexOf(",") !== -1 || b.indexOf(",") !== -1) {
if ((e + b).indexOf("rgb") !== -1 || (e + b).indexOf("hsl") !== -1) {//keep rgb(), rgba(), hsl(), and hsla() values together! (remember, we're splitting on spaces)
ba = ba.join(" ").replace(_commasOutsideParenExp, ", ").split(" ");
ea = ea.join(" ").replace(_commasOutsideParenExp, ", ").split(" ");
} else {
ba = ba.join(" ").split(",").join(", ").split(" ");
ea = ea.join(" ").split(",").join(", ").split(" ");
}
l = ba.length;
}
if (l !== ea.length) {
//DEBUG: _log("mismatched formatting detected on " + p + " (" + b + " vs " + e + ")");
ba = (dflt || "").split(" ");
l = ba.length;
}
pt.plugin = plugin;
pt.setRatio = setRatio;
_colorExp.lastIndex = 0;
for (i = 0; i < l; i++) {
bv = ba[i];
ev = ea[i];
bn = parseFloat(bv);
//if the value begins with a number (most common). It's fine if it has a suffix like px
if (bn || bn === 0) {
pt.appendXtra("", bn, _parseChange(ev, bn), ev.replace(_relNumExp, ""), autoRound && ev.indexOf("px") !== -1, true);
//if the value is a color
} else if (clrs && _colorExp.test(bv)) {
str = ev.indexOf(")") + 1;
str = ")" + (str ? ev.substr(str) : ""); //if there's a comma or ) at the end, retain it.
useHSL = ev.indexOf("hsl") !== -1 && _supportsOpacity;
temp = ev; //original string value so we can look for any prefix later.
bv = _parseColor(bv, useHSL);
ev = _parseColor(ev, useHSL);
hasAlpha = bv.length + ev.length > 6;
if (hasAlpha && !_supportsOpacity && ev[3] === 0) {//older versions of IE don't support rgba(), so if the destination alpha is 0, just use "transparent" for the end color
pt["xs" + pt.l] += pt.l ? " transparent" : "transparent";
pt.e = pt.e.split(ea[i]).join("transparent");
} else {
if (!_supportsOpacity) {//old versions of IE don't support rgba().
hasAlpha = false;
}
if (useHSL) {
pt.appendXtra(temp.substr(0, temp.indexOf("hsl")) + (hasAlpha ? "hsla(" : "hsl("), bv[0], _parseChange(ev[0], bv[0]), ",", false, true).
appendXtra("", bv[1], _parseChange(ev[1], bv[1]), "%,", false).
appendXtra("", bv[2], _parseChange(ev[2], bv[2]), hasAlpha ? "%," : "%" + str, false);
} else {
pt.appendXtra(temp.substr(0, temp.indexOf("rgb")) + (hasAlpha ? "rgba(" : "rgb("), bv[0], ev[0] - bv[0], ",", true, true).
appendXtra("", bv[1], ev[1] - bv[1], ",", true).
appendXtra("", bv[2], ev[2] - bv[2], hasAlpha ? "," : str, true);
}
if (hasAlpha) {
bv = bv.length < 4 ? 1 : bv[3];
pt.appendXtra("", bv, (ev.length < 4 ? 1 : ev[3]) - bv, str, false);
}
}
_colorExp.lastIndex = 0; //otherwise the test() on the RegExp could move the lastIndex and taint future results.
} else {
bnums = bv.match(_numExp); //gets each group of numbers in the beginning value string and drops them into an array
//if no number is found, treat it as a non-tweening value and just append the string to the current xs.
if (!bnums) {
pt["xs" + pt.l] += pt.l || pt["xs" + pt.l] ? " " + ev : ev;
//loop through all the numbers that are found and construct the extra values on the pt.
} else {
enums = ev.match(_relNumExp); //get each group of numbers in the end value string and drop them into an array. We allow relative values too, like +=50 or -=.5
if (!enums || enums.length !== bnums.length) {
//DEBUG: _log("mismatched formatting detected on " + p + " (" + b + " vs " + e + ")");
return pt;
}
ni = 0;
for (xi = 0; xi < bnums.length; xi++) {
cv = bnums[xi];
temp = bv.indexOf(cv, ni);
pt.appendXtra(bv.substr(ni, temp - ni), Number(cv), _parseChange(enums[xi], cv), "", autoRound && bv.substr(temp + cv.length, 2) === "px", xi === 0);
ni = temp + cv.length;
}
pt["xs" + pt.l] += bv.substr(ni);
}
}
}
//if there are relative values ("+=" or "-=" prefix), we need to adjust the ending value to eliminate the prefixes and combine the values properly.
if (e.indexOf("=") !== -1) if (pt.data) {
str = pt.xs0 + pt.data.s;
for (i = 1; i < pt.l; i++) {
str += pt["xs" + i] + pt.data["xn" + i];
}
pt.e = str + pt["xs" + i];
}
if (!pt.l) {
pt.type = -1;
pt.xs0 = pt.e;
}
return pt.xfirst || pt;
},
i = 9;
p = CSSPropTween.prototype;
p.l = p.pr = 0; //length (number of extra properties like xn1, xn2, xn3, etc.
while (--i > 0) {
p["xn" + i] = 0;
p["xs" + i] = "";
}
p.xs0 = "";
p._next = p._prev = p.xfirst = p.data = p.plugin = p.setRatio = p.rxp = null;
/**
* Appends and extra tweening value to a CSSPropTween and automatically manages any prefix and suffix strings. The first extra value is stored in the s and c of the main CSSPropTween instance, but thereafter any extras are stored in the xn1, xn2, xn3, etc. The prefixes and suffixes are stored in the xs0, xs1, xs2, etc. properties. For example, if I walk through a clip value like "rect(10px, 5px, 0px, 20px)", the values would be stored like this:
* xs0:"rect(", s:10, xs1:"px, ", xn1:5, xs2:"px, ", xn2:0, xs3:"px, ", xn3:20, xn4:"px)"
* And they'd all get joined together when the CSSPlugin renders (in the setRatio() method).
* @param {string=} pfx Prefix (if any)
* @param {!number} s Starting value
* @param {!number} c Change in numeric value over the course of the entire tween. For example, if the start is 5 and the end is 100, the change would be 95.
* @param {string=} sfx Suffix (if any)
* @param {boolean=} r Round (if true).
* @param {boolean=} pad If true, this extra value should be separated by the previous one by a space. If there is no previous extra and pad is true, it will automatically drop the space.
* @return {CSSPropTween} returns itself so that multiple methods can be chained together.
*/
p.appendXtra = function (pfx, s, c, sfx, r, pad) {
var pt = this,
l = pt.l;
pt["xs" + l] += pad && (l || pt["xs" + l]) ? " " + pfx : pfx || "";
if (!c) if (l !== 0 && !pt.plugin) {//typically we'll combine non-changing values right into the xs to optimize performance, but we don't combine them when there's a plugin that will be tweening the values because it may depend on the values being split apart, like for a bezier, if a value doesn't change between the first and second iteration but then it does on the 3rd, we'll run into trouble because there's no xn slot for that value!
pt["xs" + l] += s + (sfx || "");
return pt;
}
pt.l++;
pt.type = pt.setRatio ? 2 : 1;
pt["xs" + pt.l] = sfx || "";
if (l > 0) {
pt.data["xn" + l] = s + c;
pt.rxp["xn" + l] = r; //round extra property (we need to tap into this in the _parseToProxy() method)
pt["xn" + l] = s;
if (!pt.plugin) {
pt.xfirst = new CSSPropTween(pt, "xn" + l, s, c, pt.xfirst || pt, 0, pt.n, r, pt.pr);
pt.xfirst.xs0 = 0; //just to ensure that the property stays numeric which helps modern browsers speed up processing. Remember, in the setRatio() method, we do pt.t[pt.p] = val + pt.xs0 so if pt.xs0 is "" (the default), it'll cast the end value as a string. When a property is a number sometimes and a string sometimes, it prevents the compiler from locking in the data type, slowing things down slightly.
}
return pt;
}
pt.data = { s: s + c };
pt.rxp = {};
pt.s = s;
pt.c = c;
pt.r = r;
return pt;
};
/**
* @constructor A SpecialProp is basically a css property that needs to be treated in a non-standard way, like if it may contain a complex value like boxShadow:"5px 10px 15px rgb(255, 102, 51)" or if it is associated with another plugin like ThrowPropsPlugin or BezierPlugin. Every SpecialProp is associated with a particular property name like "boxShadow" or "throwProps" or "bezier" and it will intercept those values in the vars object that's passed to the CSSPlugin and handle them accordingly.
* @param {!string} p Property name (like "boxShadow" or "throwProps")
* @param {Object=} options An object containing any of the following configuration options:
* - defaultValue: the default value
* - parser: A function that should be called when the associated property name is found in the vars. This function should return a CSSPropTween instance and it should ensure that it is properly inserted into the linked list. It will receive 4 paramters: 1) The target, 2) The value defined in the vars, 3) The CSSPlugin instance (whose _firstPT should be used for the linked list), and 4) A computed style object if one was calculated (this is a speed optimization that allows retrieval of starting values quicker)
* - formatter: a function that formats any value received for this special property (for example, boxShadow could take "5px 5px red" and format it to "5px 5px 0px 0px red" so that both the beginning and ending values have a common order and quantity of values.)
* - prefix: if true, we'll determine whether or not this property requires a vendor prefix (like Webkit or Moz or ms or O)
* - color: set this to true if the value for this SpecialProp may contain color-related values like rgb(), rgba(), etc.
* - priority: priority in the linked list order. Higher priority SpecialProps will be updated before lower priority ones. The default priority is 0.
* - multi: if true, the formatter should accommodate a comma-delimited list of values, like boxShadow could have multiple boxShadows listed out.
* - collapsible: if true, the formatter should treat the value like it's a top/right/bottom/left value that could be collapsed, like "5px" would apply to all, "5px, 10px" would use 5px for top/bottom and 10px for right/left, etc.
* - keyword: a special keyword that can [optionally] be found inside the value (like "inset" for boxShadow). This allows us to validate beginning/ending values to make sure they match (if the keyword is found in one, it'll be added to the other for consistency by default).
*/
var SpecialProp = function SpecialProp(p, options) {
options = options || {};
this.p = options.prefix ? _checkPropPrefix(p) || p : p;
_specialProps[p] = _specialProps[this.p] = this;
this.format = options.formatter || _getFormatter(options.defaultValue, options.color, options.collapsible, options.multi);
if (options.parser) {
this.parse = options.parser;
}
this.clrs = options.color;
this.multi = options.multi;
this.keyword = options.keyword;
this.dflt = options.defaultValue;
this.pr = options.priority || 0;
},
//shortcut for creating a new SpecialProp that can accept multiple properties as a comma-delimited list (helps minification). dflt can be an array for multiple values (we don't do a comma-delimited list because the default value may contain commas, like rect(0px,0px,0px,0px)). We attach this method to the SpecialProp class/object instead of using a private _createSpecialProp() method so that we can tap into it externally if necessary, like from another plugin.
_registerComplexSpecialProp = _internals._registerComplexSpecialProp = function (p, options, defaults) {
if ((typeof options === "undefined" ? "undefined" : _typeof(options)) !== "object") {
options = { parser: defaults }; //to make backwards compatible with older versions of BezierPlugin and ThrowPropsPlugin
}
var a = p.split(","),
d = options.defaultValue,
i,temp;
defaults = defaults || [d];
for (i = 0; i < a.length; i++) {
options.prefix = i === 0 && options.prefix;
options.defaultValue = defaults[i] || d;
temp = new SpecialProp(a[i], options);
}
},
//creates a placeholder special prop for a plugin so that the property gets caught the first time a tween of it is attempted, and at that time it makes the plugin register itself, thus taking over for all future tweens of that property. This allows us to not mandate that things load in a particular order and it also allows us to log() an error that informs the user when they attempt to tween an external plugin-related property without loading its .js file.
_registerPluginProp = _internals._registerPluginProp = function (p) {
if (!_specialProps[p]) {
var pluginName = p.charAt(0).toUpperCase() + p.substr(1) + "Plugin";
_registerComplexSpecialProp(p, { parser: function parser(t, e, p, cssp, pt, plugin, vars) {
var pluginClass = _globals.com.greensock.plugins[pluginName];
if (!pluginClass) {
_log("Error: " + pluginName + " js file not loaded.");
return pt;
}
pluginClass._cssRegister();
return _specialProps[p].parse(t, e, p, cssp, pt, plugin, vars);
} });
}
};
p = SpecialProp.prototype;
/**
* Alias for _parseComplex() that automatically plugs in certain values for this SpecialProp, like its property name, whether or not colors should be sensed, the default value, and priority. It also looks for any keyword that the SpecialProp defines (like "inset" for boxShadow) and ensures that the beginning and ending values have the same number of values for SpecialProps where multi is true (like boxShadow and textShadow can have a comma-delimited list)
* @param {!Object} t target element
* @param {(string|number|object)} b beginning value
* @param {(string|number|object)} e ending (destination) value
* @param {CSSPropTween=} pt next CSSPropTween in the linked list
* @param {TweenPlugin=} plugin If another plugin will be tweening the complex value, that TweenPlugin instance goes here.
* @param {function=} setRatio If a custom setRatio() method should be used to handle this complex value, that goes here.
* @return {CSSPropTween=} First CSSPropTween in the linked list
*/
p.parseComplex = function (t, b, e, pt, plugin, setRatio) {
var kwd = this.keyword,
i,ba,ea,l,bi,ei;
//if this SpecialProp's value can contain a comma-delimited list of values (like boxShadow or textShadow), we must parse them in a special way, and look for a keyword (like "inset" for boxShadow) and ensure that the beginning and ending BOTH have it if the end defines it as such. We also must ensure that there are an equal number of values specified (we can't tween 1 boxShadow to 3 for example)
if (this.multi) if (_commasOutsideParenExp.test(e) || _commasOutsideParenExp.test(b)) {
ba = b.replace(_commasOutsideParenExp, "|").split("|");
ea = e.replace(_commasOutsideParenExp, "|").split("|");
} else if (kwd) {
ba = [b];
ea = [e];
}
if (ea) {
l = ea.length > ba.length ? ea.length : ba.length;
for (i = 0; i < l; i++) {
b = ba[i] = ba[i] || this.dflt;
e = ea[i] = ea[i] || this.dflt;
if (kwd) {
bi = b.indexOf(kwd);
ei = e.indexOf(kwd);
if (bi !== ei) {
if (ei === -1) {//if the keyword isn't in the end value, remove it from the beginning one.
ba[i] = ba[i].split(kwd).join("");
} else if (bi === -1) {//if the keyword isn't in the beginning, add it.
ba[i] += " " + kwd;
}
}
}
}
b = ba.join(", ");
e = ea.join(", ");
}
return _parseComplex(t, this.p, b, e, this.clrs, this.dflt, pt, this.pr, plugin, setRatio);
};
/**
* Accepts a target and end value and spits back a CSSPropTween that has been inserted into the CSSPlugin's linked list and conforms with all the conventions we use internally, like type:-1, 0, 1, or 2, setting up any extra property tweens, priority, etc. For example, if we have a boxShadow SpecialProp and call:
* this._firstPT = sp.parse(element, "5px 10px 20px rgb(2550,102,51)", "boxShadow", this);
* It should figure out the starting value of the element's boxShadow, compare it to the provided end value and create all the necessary CSSPropTweens of the appropriate types to tween the boxShadow. The CSSPropTween that gets spit back should already be inserted into the linked list (the 4th parameter is the current head, so prepend to that).
* @param {!Object} t Target object whose property is being tweened
* @param {Object} e End value as provided in the vars object (typically a string, but not always - like a throwProps would be an object).
* @param {!string} p Property name
* @param {!CSSPlugin} cssp The CSSPlugin instance that should be associated with this tween.
* @param {?CSSPropTween} pt The CSSPropTween that is the current head of the linked list (we'll prepend to it)
* @param {TweenPlugin=} plugin If a plugin will be used to tween the parsed value, this is the plugin instance.
* @param {Object=} vars Original vars object that contains the data for parsing.
* @return {CSSPropTween} The first CSSPropTween in the linked list which includes the new one(s) added by the parse() call.
*/
p.parse = function (t, e, p, cssp, pt, plugin, vars) {
return this.parseComplex(t.style, this.format(_getStyle(t, this.p, _cs, false, this.dflt)), this.format(e), pt, plugin);
};
/**
* Registers a special property that should be intercepted from any "css" objects defined in tweens. This allows you to handle them however you want without CSSPlugin doing it for you. The 2nd parameter should be a function that accepts 3 parameters:
* 1) Target object whose property should be tweened (typically a DOM element)
* 2) The end/destination value (could be a string, number, object, or whatever you want)
* 3) The tween instance (you probably don't need to worry about this, but it can be useful for looking up information like the duration)
*
* Then, your function should return a function which will be called each time the tween gets rendered, passing a numeric "ratio" parameter to your function that indicates the change factor (usually between 0 and 1). For example:
*
* CSSPlugin.registerSpecialProp("myCustomProp", function(target, value, tween) {
* var start = target.style.width;
* return function(ratio) {
* target.style.width = (start + value * ratio) + "px";
* console.log("set width to " + target.style.width);
* }
* }, 0);
*
* Then, when I do this tween, it will trigger my special property:
*
* TweenLite.to(element, 1, {css:{myCustomProp:100}});
*
* In the example, of course, we're just changing the width, but you can do anything you want.
*
* @param {!string} name Property name (or comma-delimited list of property names) that should be intercepted and handled by your function. For example, if I define "myCustomProp", then it would handle that portion of the following tween: TweenLite.to(element, 1, {css:{myCustomProp:100}})
* @param {!function(Object, Object, Object, string):function(number)} onInitTween The function that will be called when a tween of this special property is performed. The function will receive 4 parameters: 1) Target object that should be tweened, 2) Value that was passed to the tween, 3) The tween instance itself (rarely used), and 4) The property name that's being tweened. Your function should return a function that should be called on every update of the tween. That function will receive a single parameter that is a "change factor" value (typically between 0 and 1) indicating the amount of change as a ratio. You can use this to determine how to set the values appropriately in your function.
* @param {number=} priority Priority that helps the engine determine the order in which to set the properties (default: 0). Higher priority properties will be updated before lower priority ones.
*/
CSSPlugin.registerSpecialProp = function (name, onInitTween, priority) {
_registerComplexSpecialProp(name, { parser: function parser(t, e, p, cssp, pt, plugin, vars) {
var rv = new CSSPropTween(t, p, 0, 0, pt, 2, p, false, priority);
rv.plugin = plugin;
rv.setRatio = onInitTween(t, e, cssp._tween, p);
return rv;
}, priority: priority });
};
//transform-related methods and properties
CSSPlugin.useSVGTransformAttr = true; //Safari and Firefox both have some rendering bugs when applying CSS transforms to SVG elements, so default to using the "transform" attribute instead (users can override this).
var _transformProps = "scaleX,scaleY,scaleZ,x,y,z,skewX,skewY,rotation,rotationX,rotationY,perspective,xPercent,yPercent".split(","),
_transformProp = _checkPropPrefix("transform"), //the Javascript (camelCase) transform property, like msTransform, WebkitTransform, MozTransform, or OTransform.
_transformPropCSS = _prefixCSS + "transform",
_transformOriginProp = _checkPropPrefix("transformOrigin"),
_supports3D = _checkPropPrefix("perspective") !== null,
Transform = _internals.Transform = function () {
this.perspective = parseFloat(CSSPlugin.defaultTransformPerspective) || 0;
this.force3D = CSSPlugin.defaultForce3D === false || !_supports3D ? false : CSSPlugin.defaultForce3D || "auto";
},
_SVGElement = _gsScope.SVGElement,
_useSVGTransformAttr,
//Some browsers (like Firefox and IE) don't honor transform-origin properly in SVG elements, so we need to manually adjust the matrix accordingly. We feature detect here rather than always doing the conversion for certain browsers because they may fix the problem at some point in the future.
_createSVG = function _createSVG(type, container, attributes) {
var element = _doc.createElementNS("http://www.w3.org/2000/svg", type),
reg = /([a-z])([A-Z])/g,
p;
for (p in attributes) {
element.setAttributeNS(null, p.replace(reg, "$1-$2").toLowerCase(), attributes[p]);
}
container.appendChild(element);
return element;
},
_docElement = _doc.documentElement || {},
_forceSVGTransformAttr = function () {
//IE and Android stock don't support CSS transforms on SVG elements, so we must write them to the "transform" attribute. We populate this variable in the _parseTransform() method, and only if/when we come across an SVG element
var force = _ieVers || /Android/i.test(_agent) && !_gsScope.chrome,
svg,rect,width;
if (_doc.createElementNS && !force) {//IE8 and earlier doesn't support SVG anyway
svg = _createSVG("svg", _docElement);
rect = _createSVG("rect", svg, { width: 100, height: 50, x: 100 });
width = rect.getBoundingClientRect().width;
rect.style[_transformOriginProp] = "50% 50%";
rect.style[_transformProp] = "scaleX(0.5)";
force = width === rect.getBoundingClientRect().width && !(_isFirefox && _supports3D); //note: Firefox fails the test even though it does support CSS transforms in 3D. Since we can't push 3D stuff into the transform attribute, we force Firefox to pass the test here (as long as it does truly support 3D).
_docElement.removeChild(svg);
}
return force;
}(),
_parseSVGOrigin = function _parseSVGOrigin(e, local, decoratee, absolute, smoothOrigin, skipRecord) {
var tm = e._gsTransform,
m = _getMatrix(e, true),
v,x,y,xOrigin,yOrigin,a,b,c,d,tx,ty,determinant,xOriginOld,yOriginOld;
if (tm) {
xOriginOld = tm.xOrigin; //record the original values before we alter them.
yOriginOld = tm.yOrigin;
}
if (!absolute || (v = absolute.split(" ")).length < 2) {
b = e.getBBox();
if (b.x === 0 && b.y === 0 && b.width + b.height === 0) {//some browsers (like Firefox) misreport the bounds if the element has zero width and height (it just assumes it's at x:0, y:0), thus we need to manually grab the position in that case.
b = { x: parseFloat(e.hasAttribute("x") ? e.getAttribute("x") : e.hasAttribute("cx") ? e.getAttribute("cx") : 0) || 0, y: parseFloat(e.hasAttribute("y") ? e.getAttribute("y") : e.hasAttribute("cy") ? e.getAttribute("cy") : 0) || 0, width: 0, height: 0 };
}
local = _parsePosition(local).split(" ");
v = [(local[0].indexOf("%") !== -1 ? parseFloat(local[0]) / 100 * b.width : parseFloat(local[0])) + b.x,
(local[1].indexOf("%") !== -1 ? parseFloat(local[1]) / 100 * b.height : parseFloat(local[1])) + b.y];
}
decoratee.xOrigin = xOrigin = parseFloat(v[0]);
decoratee.yOrigin = yOrigin = parseFloat(v[1]);
if (absolute && m !== _identity2DMatrix) {//if svgOrigin is being set, we must invert the matrix and determine where the absolute point is, factoring in the current transforms. Otherwise, the svgOrigin would be based on the element's non-transformed position on the canvas.
a = m[0];
b = m[1];
c = m[2];
d = m[3];
tx = m[4];
ty = m[5];
determinant = a * d - b * c;
if (determinant) {//if it's zero (like if scaleX and scaleY are zero), skip it to avoid errors with dividing by zero.
x = xOrigin * (d / determinant) + yOrigin * (-c / determinant) + (c * ty - d * tx) / determinant;
y = xOrigin * (-b / determinant) + yOrigin * (a / determinant) - (a * ty - b * tx) / determinant;
xOrigin = decoratee.xOrigin = v[0] = x;
yOrigin = decoratee.yOrigin = v[1] = y;
}
}
if (tm) {//avoid jump when transformOrigin is changed - adjust the x/y values accordingly
if (skipRecord) {
decoratee.xOffset = tm.xOffset;
decoratee.yOffset = tm.yOffset;
tm = decoratee;
}
if (smoothOrigin || smoothOrigin !== false && CSSPlugin.defaultSmoothOrigin !== false) {
x = xOrigin - xOriginOld;
y = yOrigin - yOriginOld;
//originally, we simply adjusted the x and y values, but that would cause problems if, for example, you created a rotational tween part-way through an x/y tween. Managing the offset in a separate variable gives us ultimate flexibility.
//tm.x -= x - (x * m[0] + y * m[2]);
//tm.y -= y - (x * m[1] + y * m[3]);
tm.xOffset += x * m[0] + y * m[2] - x;
tm.yOffset += x * m[1] + y * m[3] - y;
} else {
tm.xOffset = tm.yOffset = 0;
}
}
if (!skipRecord) {
e.setAttribute("data-svg-origin", v.join(" "));
}
},
_getBBoxHack = function _getBBoxHack(swapIfPossible) {//works around issues in some browsers (like Firefox) that don't correctly report getBBox() on SVG elements inside a <defs> element and/or <mask>. We try creating an SVG, adding it to the documentElement and toss the element in there so that it's definitely part of the rendering tree, then grab the bbox and if it works, we actually swap out the original getBBox() method for our own that does these extra steps whenever getBBox is needed. This helps ensure that performance is optimal (only do all these extra steps when absolutely necessary...most elements don't need it).
var svg = _createElement("svg", this.ownerSVGElement && this.ownerSVGElement.getAttribute("xmlns") || "http://www.w3.org/2000/svg"),
oldParent = this.parentNode,
oldSibling = this.nextSibling,
oldCSS = this.style.cssText,
bbox;
_docElement.appendChild(svg);
svg.appendChild(this);
this.style.display = "block";
if (swapIfPossible) {
try {
bbox = this.getBBox();
this._originalGetBBox = this.getBBox;
this.getBBox = _getBBoxHack;
} catch (e) {}
} else if (this._originalGetBBox) {
bbox = this._originalGetBBox();
}
if (oldSibling) {
oldParent.insertBefore(this, oldSibling);
} else {
oldParent.appendChild(this);
}
_docElement.removeChild(svg);
this.style.cssText = oldCSS;
return bbox;
},
_getBBox = function _getBBox(e) {
try {
return e.getBBox(); //Firefox throws errors if you try calling getBBox() on an SVG element that's not rendered (like in a <symbol> or <defs>). https://bugzilla.mozilla.org/show_bug.cgi?id=612118
} catch (error) {
return _getBBoxHack.call(e, true);
}
},
_isSVG = function _isSVG(e) {//reports if the element is an SVG on which getBBox() actually works
return !!(_SVGElement && e.getCTM && (!e.parentNode || e.ownerSVGElement) && _getBBox(e));
},
_identity2DMatrix = [1, 0, 0, 1, 0, 0],
_getMatrix = function _getMatrix(e, force2D) {
var tm = e._gsTransform || new Transform(),
rnd = 100000,
style = e.style,
isDefault,s,m,n,dec,none;
if (_transformProp) {
s = _getStyle(e, _transformPropCSS, null, true);
} else if (e.currentStyle) {
//for older versions of IE, we need to interpret the filter portion that is in the format: progid:DXImageTransform.Microsoft.Matrix(M11=6.123233995736766e-17, M12=-1, M21=1, M22=6.123233995736766e-17, sizingMethod='auto expand') Notice that we need to swap b and c compared to a normal matrix.
s = e.currentStyle.filter.match(_ieGetMatrixExp);
s = s && s.length === 4 ? [s[0].substr(4), Number(s[2].substr(4)), Number(s[1].substr(4)), s[3].substr(4), tm.x || 0, tm.y || 0].join(",") : "";
}
isDefault = !s || s === "none" || s === "matrix(1, 0, 0, 1, 0, 0)";
if (_transformProp && ((none = !_getComputedStyle(e) || _getComputedStyle(e).display === "none") || !e.parentNode)) {//note: Firefox returns null for getComputedStyle() if the element is in an iframe that has display:none. https://bugzilla.mozilla.org/show_bug.cgi?id=548397
if (none) {//browsers don't report transforms accurately unless the element is in the DOM and has a display value that's not "none". Firefox and Microsoft browsers have a partial bug where they'll report transforms even if display:none BUT not any percentage-based values like translate(-50%, 8px) will be reported as if it's translate(0, 8px).
n = style.display;
style.display = "block";
}
if (!e.parentNode) {
dec = 1; //flag
_docElement.appendChild(e);
}
s = _getStyle(e, _transformPropCSS, null, true);
isDefault = !s || s === "none" || s === "matrix(1, 0, 0, 1, 0, 0)";
if (n) {
style.display = n;
} else if (none) {
_removeProp(style, "display");
}
if (dec) {
_docElement.removeChild(e);
}
}
if (tm.svg || e.getCTM && _isSVG(e)) {
if (isDefault && (style[_transformProp] + "").indexOf("matrix") !== -1) {//some browsers (like Chrome 40) don't correctly report transforms that are applied inline on an SVG element (they don't get included in the computed style), so we double-check here and accept matrix values
s = style[_transformProp];
isDefault = 0;
}
m = e.getAttribute("transform");
if (isDefault && m) {
m = e.transform.baseVal.consolidate().matrix; //ensures that even complex values like "translate(50,60) rotate(135,0,0)" are parsed because it mashes it into a matrix.
s = "matrix(" + m.a + "," + m.b + "," + m.c + "," + m.d + "," + m.e + "," + m.f + ")";
isDefault = 0;
}
}
if (isDefault) {
return _identity2DMatrix;
}
//split the matrix values out into an array (m for matrix)
m = (s || "").match(_numExp) || [];
i = m.length;
while (--i > -1) {
n = Number(m[i]);
m[i] = (dec = n - (n |= 0)) ? (dec * rnd + (dec < 0 ? -0.5 : 0.5) | 0) / rnd + n : n; //convert strings to Numbers and round to 5 decimal places to avoid issues with tiny numbers. Roughly 20x faster than Number.toFixed(). We also must make sure to round before dividing so that values like 0.9999999999 become 1 to avoid glitches in browser rendering and interpretation of flipped/rotated 3D matrices. And don't just multiply the number by rnd, floor it, and then divide by rnd because the bitwise operations max out at a 32-bit signed integer, thus it could get clipped at a relatively low value (like 22,000.00000 for example).
}
return force2D && m.length > 6 ? [m[0], m[1], m[4], m[5], m[12], m[13]] : m;
},
/**
* Parses the transform values for an element, returning an object with x, y, z, scaleX, scaleY, scaleZ, rotation, rotationX, rotationY, skewX, and skewY properties. Note: by default (for performance reasons), all skewing is combined into skewX and rotation but skewY still has a place in the transform object so that we can record how much of the skew is attributed to skewX vs skewY. Remember, a skewY of 10 looks the same as a rotation of 10 and skewX of -10.
* @param {!Object} t target element
* @param {Object=} cs computed style object (optional)
* @param {boolean=} rec if true, the transform values will be recorded to the target element's _gsTransform object, like target._gsTransform = {x:0, y:0, z:0, scaleX:1...}
* @param {boolean=} parse if true, we'll ignore any _gsTransform values that already exist on the element, and force a reparsing of the css (calculated style)
* @return {object} object containing all of the transform properties/values like {x:0, y:0, z:0, scaleX:1...}
*/
_getTransform = _internals.getTransform = function (t, cs, rec, parse) {
if (t._gsTransform && rec && !parse) {
return t._gsTransform; //if the element already has a _gsTransform, use that. Note: some browsers don't accurately return the calculated style for the transform (particularly for SVG), so it's almost always safest to just use the values we've already applied rather than re-parsing things.
}
var tm = rec ? t._gsTransform || new Transform() : new Transform(),
invX = tm.scaleX < 0, //in order to interpret things properly, we need to know if the user applied a negative scaleX previously so that we can adjust the rotation and skewX accordingly. Otherwise, if we always interpret a flipped matrix as affecting scaleY and the user only wants to tween the scaleX on multiple sequential tweens, it would keep the negative scaleY without that being the user's intent.
min = 0.00002,
rnd = 100000,
zOrigin = _supports3D ? parseFloat(_getStyle(t, _transformOriginProp, cs, false, "0 0 0").split(" ")[2]) || tm.zOrigin || 0 : 0,
defaultTransformPerspective = parseFloat(CSSPlugin.defaultTransformPerspective) || 0,
m,i,scaleX,scaleY,rotation,skewX;
tm.svg = !!(t.getCTM && _isSVG(t));
if (tm.svg) {
_parseSVGOrigin(t, _getStyle(t, _transformOriginProp, cs, false, "50% 50%") + "", tm, t.getAttribute("data-svg-origin"));
_useSVGTransformAttr = CSSPlugin.useSVGTransformAttr || _forceSVGTransformAttr;
}
m = _getMatrix(t);
if (m !== _identity2DMatrix) {
if (m.length === 16) {
//we'll only look at these position-related 6 variables first because if x/y/z all match, it's relatively safe to assume we don't need to re-parse everything which risks losing important rotational information (like rotationX:180 plus rotationY:180 would look the same as rotation:180 - there's no way to know for sure which direction was taken based solely on the matrix3d() values)
var a11 = m[0],a21 = m[1],a31 = m[2],a41 = m[3],
a12 = m[4],a22 = m[5],a32 = m[6],a42 = m[7],
a13 = m[8],a23 = m[9],a33 = m[10],
a14 = m[12],a24 = m[13],a34 = m[14],
a43 = m[11],
angle = Math.atan2(a32, a33),
t1,t2,t3,t4,cos,sin;
//we manually compensate for non-zero z component of transformOrigin to work around bugs in Safari
if (tm.zOrigin) {
a34 = -tm.zOrigin;
a14 = a13 * a34 - m[12];
a24 = a23 * a34 - m[13];
a34 = a33 * a34 + tm.zOrigin - m[14];
}
//note for possible future consolidation: rotationX: Math.atan2(a32, a33), rotationY: Math.atan2(-a31, Math.sqrt(a33 * a33 + a32 * a32)), rotation: Math.atan2(a21, a11), skew: Math.atan2(a12, a22). However, it doesn't seem to be quite as reliable as the full-on backwards rotation procedure.
tm.rotationX = angle * _RAD2DEG;
//rotationX
if (angle) {
cos = Math.cos(-angle);
sin = Math.sin(-angle);
t1 = a12 * cos + a13 * sin;
t2 = a22 * cos + a23 * sin;
t3 = a32 * cos + a33 * sin;
a13 = a12 * -sin + a13 * cos;
a23 = a22 * -sin + a23 * cos;
a33 = a32 * -sin + a33 * cos;
a43 = a42 * -sin + a43 * cos;
a12 = t1;
a22 = t2;
a32 = t3;
}
//rotationY
angle = Math.atan2(-a31, a33);
tm.rotationY = angle * _RAD2DEG;
if (angle) {
cos = Math.cos(-angle);
sin = Math.sin(-angle);
t1 = a11 * cos - a13 * sin;
t2 = a21 * cos - a23 * sin;
t3 = a31 * cos - a33 * sin;
a23 = a21 * sin + a23 * cos;
a33 = a31 * sin + a33 * cos;
a43 = a41 * sin + a43 * cos;
a11 = t1;
a21 = t2;
a31 = t3;
}
//rotationZ
angle = Math.atan2(a21, a11);
tm.rotation = angle * _RAD2DEG;
if (angle) {
cos = Math.cos(angle);
sin = Math.sin(angle);
t1 = a11 * cos + a21 * sin;
t2 = a12 * cos + a22 * sin;
t3 = a13 * cos + a23 * sin;
a21 = a21 * cos - a11 * sin;
a22 = a22 * cos - a12 * sin;
a23 = a23 * cos - a13 * sin;
a11 = t1;
a12 = t2;
a13 = t3;
}
if (tm.rotationX && Math.abs(tm.rotationX) + Math.abs(tm.rotation) > 359.9) {//when rotationY is set, it will often be parsed as 180 degrees different than it should be, and rotationX and rotation both being 180 (it looks the same), so we adjust for that here.
tm.rotationX = tm.rotation = 0;
tm.rotationY = 180 - tm.rotationY;
}
//skewX
angle = Math.atan2(a12, a22);
//scales
tm.scaleX = (Math.sqrt(a11 * a11 + a21 * a21 + a31 * a31) * rnd + 0.5 | 0) / rnd;
tm.scaleY = (Math.sqrt(a22 * a22 + a32 * a32) * rnd + 0.5 | 0) / rnd;
tm.scaleZ = (Math.sqrt(a13 * a13 + a23 * a23 + a33 * a33) * rnd + 0.5 | 0) / rnd;
a11 /= tm.scaleX;
a12 /= tm.scaleY;
a21 /= tm.scaleX;
a22 /= tm.scaleY;
if (Math.abs(angle) > min) {
tm.skewX = angle * _RAD2DEG;
a12 = 0; //unskews
if (tm.skewType !== "simple") {
tm.scaleY *= 1 / Math.cos(angle); //by default, we compensate the scale based on the skew so that the element maintains a similar proportion when skewed, so we have to alter the scaleY here accordingly to match the default (non-adjusted) skewing that CSS does (stretching more and more as it skews).
}
} else {
tm.skewX = 0;
}
/* //for testing purposes
var transform = "matrix3d(",
comma = ",",
zero = "0";
a13 /= tm.scaleZ;
a23 /= tm.scaleZ;
a31 /= tm.scaleX;
a32 /= tm.scaleY;
a33 /= tm.scaleZ;
transform += ((a11 < min && a11 > -min) ? zero : a11) + comma + ((a21 < min && a21 > -min) ? zero : a21) + comma + ((a31 < min && a31 > -min) ? zero : a31);
transform += comma + ((a41 < min && a41 > -min) ? zero : a41) + comma + ((a12 < min && a12 > -min) ? zero : a12) + comma + ((a22 < min && a22 > -min) ? zero : a22);
transform += comma + ((a32 < min && a32 > -min) ? zero : a32) + comma + ((a42 < min && a42 > -min) ? zero : a42) + comma + ((a13 < min && a13 > -min) ? zero : a13);
transform += comma + ((a23 < min && a23 > -min) ? zero : a23) + comma + ((a33 < min && a33 > -min) ? zero : a33) + comma + ((a43 < min && a43 > -min) ? zero : a43) + comma;
transform += a14 + comma + a24 + comma + a34 + comma + (tm.perspective ? (1 + (-a34 / tm.perspective)) : 1) + ")";
console.log(transform);
document.querySelector(".test").style[_transformProp] = transform;
*/
tm.perspective = a43 ? 1 / (a43 < 0 ? -a43 : a43) : 0;
tm.x = a14;
tm.y = a24;
tm.z = a34;
if (tm.svg) {
tm.x -= tm.xOrigin - (tm.xOrigin * a11 - tm.yOrigin * a12);
tm.y -= tm.yOrigin - (tm.yOrigin * a21 - tm.xOrigin * a22);
}
} else if (!_supports3D || parse || !m.length || tm.x !== m[4] || tm.y !== m[5] || !tm.rotationX && !tm.rotationY) {//sometimes a 6-element matrix is returned even when we performed 3D transforms, like if rotationX and rotationY are 180. In cases like this, we still need to honor the 3D transforms. If we just rely on the 2D info, it could affect how the data is interpreted, like scaleY might get set to -1 or rotation could get offset by 180 degrees. For example, do a TweenLite.to(element, 1, {css:{rotationX:180, rotationY:180}}) and then later, TweenLite.to(element, 1, {css:{rotationX:0}}) and without this conditional logic in place, it'd jump to a state of being unrotated when the 2nd tween starts. Then again, we need to honor the fact that the user COULD alter the transforms outside of CSSPlugin, like by manually applying new css, so we try to sense that by looking at x and y because if those changed, we know the changes were made outside CSSPlugin and we force a reinterpretation of the matrix values. Also, in Webkit browsers, if the element's "display" is "none", its calculated style value will always return empty, so if we've already recorded the values in the _gsTransform object, we'll just rely on those.
var k = m.length >= 6,
a = k ? m[0] : 1,
b = m[1] || 0,
c = m[2] || 0,
d = k ? m[3] : 1;
tm.x = m[4] || 0;
tm.y = m[5] || 0;
scaleX = Math.sqrt(a * a + b * b);
scaleY = Math.sqrt(d * d + c * c);
rotation = a || b ? Math.atan2(b, a) * _RAD2DEG : tm.rotation || 0; //note: if scaleX is 0, we cannot accurately measure rotation. Same for skewX with a scaleY of 0. Therefore, we default to the previously recorded value (or zero if that doesn't exist).
skewX = c || d ? Math.atan2(c, d) * _RAD2DEG + rotation : tm.skewX || 0;
tm.scaleX = scaleX;
tm.scaleY = scaleY;
tm.rotation = rotation;
tm.skewX = skewX;
if (_supports3D) {
tm.rotationX = tm.rotationY = tm.z = 0;
tm.perspective = defaultTransformPerspective;
tm.scaleZ = 1;
}
if (tm.svg) {
tm.x -= tm.xOrigin - (tm.xOrigin * a + tm.yOrigin * c);
tm.y -= tm.yOrigin - (tm.xOrigin * b + tm.yOrigin * d);
}
}
if (Math.abs(tm.skewX) > 90 && Math.abs(tm.skewX) < 270) {
if (invX) {
tm.scaleX *= -1;
tm.skewX += tm.rotation <= 0 ? 180 : -180;
tm.rotation += tm.rotation <= 0 ? 180 : -180;
} else {
tm.scaleY *= -1;
tm.skewX += tm.skewX <= 0 ? 180 : -180;
}
}
tm.zOrigin = zOrigin;
//some browsers have a hard time with very small values like 2.4492935982947064e-16 (notice the "e-" towards the end) and would render the object slightly off. So we round to 0 in these cases. The conditional logic here is faster than calling Math.abs(). Also, browsers tend to render a SLIGHTLY rotated object in a fuzzy way, so we need to snap to exactly 0 when appropriate.
for (i in tm) {
if (tm[i] < min) if (tm[i] > -min) {
tm[i] = 0;
}
}
}
//DEBUG: _log("parsed rotation of " + t.getAttribute("id")+": "+(tm.rotationX)+", "+(tm.rotationY)+", "+(tm.rotation)+", scale: "+tm.scaleX+", "+tm.scaleY+", "+tm.scaleZ+", position: "+tm.x+", "+tm.y+", "+tm.z+", perspective: "+tm.perspective+ ", origin: "+ tm.xOrigin+ ","+ tm.yOrigin);
if (rec) {
t._gsTransform = tm; //record to the object's _gsTransform which we use so that tweens can control individual properties independently (we need all the properties to accurately recompose the matrix in the setRatio() method)
if (tm.svg) {//if we're supposed to apply transforms to the SVG element's "transform" attribute, make sure there aren't any CSS transforms applied or they'll override the attribute ones. Also clear the transform attribute if we're using CSS, just to be clean.
if (_useSVGTransformAttr && t.style[_transformProp]) {
TweenLite.delayedCall(0.001, function () {//if we apply this right away (before anything has rendered), we risk there being no transforms for a brief moment and it also interferes with adjusting the transformOrigin in a tween with immediateRender:true (it'd try reading the matrix and it wouldn't have the appropriate data in place because we just removed it).
_removeProp(t.style, _transformProp);
});
} else if (!_useSVGTransformAttr && t.getAttribute("transform")) {
TweenLite.delayedCall(0.001, function () {
t.removeAttribute("transform");
});
}
}
}
return tm;
},
//for setting 2D transforms in IE6, IE7, and IE8 (must use a "filter" to emulate the behavior of modern day browser transforms)
_setIETransformRatio = function _setIETransformRatio(v) {
var t = this.data, //refers to the element's _gsTransform object
ang = -t.rotation * _DEG2RAD,
skew = ang + t.skewX * _DEG2RAD,
rnd = 100000,
a = (Math.cos(ang) * t.scaleX * rnd | 0) / rnd,
b = (Math.sin(ang) * t.scaleX * rnd | 0) / rnd,
c = (Math.sin(skew) * -t.scaleY * rnd | 0) / rnd,
d = (Math.cos(skew) * t.scaleY * rnd | 0) / rnd,
style = this.t.style,
cs = this.t.currentStyle,
filters,val;
if (!cs) {
return;
}
val = b; //just for swapping the variables an inverting them (reused "val" to avoid creating another variable in memory). IE's filter matrix uses a non-standard matrix configuration (angle goes the opposite way, and b and c are reversed and inverted)
b = -c;
c = -val;
filters = cs.filter;
style.filter = ""; //remove filters so that we can accurately measure offsetWidth/offsetHeight
var w = this.t.offsetWidth,
h = this.t.offsetHeight,
clip = cs.position !== "absolute",
m = "progid:DXImageTransform.Microsoft.Matrix(M11=" + a + ", M12=" + b + ", M21=" + c + ", M22=" + d,
ox = t.x + w * t.xPercent / 100,
oy = t.y + h * t.yPercent / 100,
dx,dy;
//if transformOrigin is being used, adjust the offset x and y
if (t.ox != null) {
dx = (t.oxp ? w * t.ox * 0.01 : t.ox) - w / 2;
dy = (t.oyp ? h * t.oy * 0.01 : t.oy) - h / 2;
ox += dx - (dx * a + dy * b);
oy += dy - (dx * c + dy * d);
}
if (!clip) {
m += ", sizingMethod='auto expand')";
} else {
dx = w / 2;
dy = h / 2;
//translate to ensure that transformations occur around the correct origin (default is center).
m += ", Dx=" + (dx - (dx * a + dy * b) + ox) + ", Dy=" + (dy - (dx * c + dy * d) + oy) + ")";
}
if (filters.indexOf("DXImageTransform.Microsoft.Matrix(") !== -1) {
style.filter = filters.replace(_ieSetMatrixExp, m);
} else {
style.filter = m + " " + filters; //we must always put the transform/matrix FIRST (before alpha(opacity=xx)) to avoid an IE bug that slices part of the object when rotation is applied with alpha.
}
//at the end or beginning of the tween, if the matrix is normal (1, 0, 0, 1) and opacity is 100 (or doesn't exist), remove the filter to improve browser performance.
if (v === 0 || v === 1) if (a === 1) if (b === 0) if (c === 0) if (d === 1) if (!clip || m.indexOf("Dx=0, Dy=0") !== -1) if (!_opacityExp.test(filters) || parseFloat(RegExp.$1) === 100) if (filters.indexOf("gradient(" && filters.indexOf("Alpha")) === -1) {
style.removeAttribute("filter");
}
//we must set the margins AFTER applying the filter in order to avoid some bugs in IE8 that could (in rare scenarios) cause them to be ignored intermittently (vibration).
if (!clip) {
var mult = _ieVers < 8 ? 1 : -1, //in Internet Explorer 7 and before, the box model is broken, causing the browser to treat the width/height of the actual rotated filtered image as the width/height of the box itself, but Microsoft corrected that in IE8. We must use a negative offset in IE8 on the right/bottom
marg,prop,dif;
dx = t.ieOffsetX || 0;
dy = t.ieOffsetY || 0;
t.ieOffsetX = Math.round((w - ((a < 0 ? -a : a) * w + (b < 0 ? -b : b) * h)) / 2 + ox);
t.ieOffsetY = Math.round((h - ((d < 0 ? -d : d) * h + (c < 0 ? -c : c) * w)) / 2 + oy);
for (i = 0; i < 4; i++) {
prop = _margins[i];
marg = cs[prop];
//we need to get the current margin in case it is being tweened separately (we want to respect that tween's changes)
val = marg.indexOf("px") !== -1 ? parseFloat(marg) : _convertToPixels(this.t, prop, parseFloat(marg), marg.replace(_suffixExp, "")) || 0;
if (val !== t[prop]) {
dif = i < 2 ? -t.ieOffsetX : -t.ieOffsetY; //if another tween is controlling a margin, we cannot only apply the difference in the ieOffsets, so we essentially zero-out the dx and dy here in that case. We record the margin(s) later so that we can keep comparing them, making this code very flexible.
} else {
dif = i < 2 ? dx - t.ieOffsetX : dy - t.ieOffsetY;
}
style[prop] = (t[prop] = Math.round(val - dif * (i === 0 || i === 2 ? 1 : mult))) + "px";
}
}
},
/* translates a super small decimal to a string WITHOUT scientific notation
_safeDecimal = function(n) {
var s = (n < 0 ? -n : n) + "",
a = s.split("e-");
return (n < 0 ? "-0." : "0.") + new Array(parseInt(a[1], 10) || 0).join("0") + a[0].split(".").join("");
},
*/
_setTransformRatio = _internals.set3DTransformRatio = _internals.setTransformRatio = function (v) {
var t = this.data, //refers to the element's _gsTransform object
style = this.t.style,
angle = t.rotation,
rotationX = t.rotationX,
rotationY = t.rotationY,
sx = t.scaleX,
sy = t.scaleY,
sz = t.scaleZ,
x = t.x,
y = t.y,
z = t.z,
isSVG = t.svg,
perspective = t.perspective,
force3D = t.force3D,
skewY = t.skewY,
skewX = t.skewX,
t1,a11,a12,a13,a21,a22,a23,a31,a32,a33,a41,a42,a43,
zOrigin,min,cos,sin,t2,transform,comma,zero,skew,rnd;
if (skewY) {//for performance reasons, we combine all skewing into the skewX and rotation values. Remember, a skewY of 10 degrees looks the same as a rotation of 10 degrees plus a skewX of 10 degrees.
skewX += skewY;
angle += skewY;
}
//check to see if we should render as 2D (and SVGs must use 2D when _useSVGTransformAttr is true)
if (((v === 1 || v === 0) && force3D === "auto" && (this.tween._totalTime === this.tween._totalDuration || !this.tween._totalTime) || !force3D) && !z && !perspective && !rotationY && !rotationX && sz === 1 || _useSVGTransformAttr && isSVG || !_supports3D) {//on the final render (which could be 0 for a from tween), if there are no 3D aspects, render in 2D to free up memory and improve performance especially on mobile devices. Check the tween's totalTime/totalDuration too in order to make sure it doesn't happen between repeats if it's a repeating tween.
//2D
if (angle || skewX || isSVG) {
angle *= _DEG2RAD;
skew = skewX * _DEG2RAD;
rnd = 100000;
a11 = Math.cos(angle) * sx;
a21 = Math.sin(angle) * sx;
a12 = Math.sin(angle - skew) * -sy;
a22 = Math.cos(angle - skew) * sy;
if (skew && t.skewType === "simple") {//by default, we compensate skewing on the other axis to make it look more natural, but you can set the skewType to "simple" to use the uncompensated skewing that CSS does
t1 = Math.tan(skew - skewY * _DEG2RAD);
t1 = Math.sqrt(1 + t1 * t1);
a12 *= t1;
a22 *= t1;
if (skewY) {
t1 = Math.tan(skewY * _DEG2RAD);
t1 = Math.sqrt(1 + t1 * t1);
a11 *= t1;
a21 *= t1;
}
}
if (isSVG) {
x += t.xOrigin - (t.xOrigin * a11 + t.yOrigin * a12) + t.xOffset;
y += t.yOrigin - (t.xOrigin * a21 + t.yOrigin * a22) + t.yOffset;
if (_useSVGTransformAttr && (t.xPercent || t.yPercent)) {//The SVG spec doesn't support percentage-based translation in the "transform" attribute, so we merge it into the matrix to simulate it.
min = this.t.getBBox();
x += t.xPercent * 0.01 * min.width;
y += t.yPercent * 0.01 * min.height;
}
min = 0.000001;
if (x < min) if (x > -min) {
x = 0;
}
if (y < min) if (y > -min) {
y = 0;
}
}
transform = (a11 * rnd | 0) / rnd + "," + (a21 * rnd | 0) / rnd + "," + (a12 * rnd | 0) / rnd + "," + (a22 * rnd | 0) / rnd + "," + x + "," + y + ")";
if (isSVG && _useSVGTransformAttr) {
this.t.setAttribute("transform", "matrix(" + transform);
} else {
//some browsers have a hard time with very small values like 2.4492935982947064e-16 (notice the "e-" towards the end) and would render the object slightly off. So we round to 5 decimal places.
style[_transformProp] = (t.xPercent || t.yPercent ? "translate(" + t.xPercent + "%," + t.yPercent + "%) matrix(" : "matrix(") + transform;
}
} else {
style[_transformProp] = (t.xPercent || t.yPercent ? "translate(" + t.xPercent + "%," + t.yPercent + "%) matrix(" : "matrix(") + sx + ",0,0," + sy + "," + x + "," + y + ")";
}
return;
}
if (_isFirefox) {//Firefox has a bug (at least in v25) that causes it to render the transparent part of 32-bit PNG images as black when displayed inside an iframe and the 3D scale is very small and doesn't change sufficiently enough between renders (like if you use a Power4.easeInOut to scale from 0 to 1 where the beginning values only change a tiny amount to begin the tween before accelerating). In this case, we force the scale to be 0.00002 instead which is visually the same but works around the Firefox issue.
min = 0.0001;
if (sx < min && sx > -min) {
sx = sz = 0.00002;
}
if (sy < min && sy > -min) {
sy = sz = 0.00002;
}
if (perspective && !t.z && !t.rotationX && !t.rotationY) {//Firefox has a bug that causes elements to have an odd super-thin, broken/dotted black border on elements that have a perspective set but aren't utilizing 3D space (no rotationX, rotationY, or z).
perspective = 0;
}
}
if (angle || skewX) {
angle *= _DEG2RAD;
cos = a11 = Math.cos(angle);
sin = a21 = Math.sin(angle);
if (skewX) {
angle -= skewX * _DEG2RAD;
cos = Math.cos(angle);
sin = Math.sin(angle);
if (t.skewType === "simple") {//by default, we compensate skewing on the other axis to make it look more natural, but you can set the skewType to "simple" to use the uncompensated skewing that CSS does
t1 = Math.tan((skewX - skewY) * _DEG2RAD);
t1 = Math.sqrt(1 + t1 * t1);
cos *= t1;
sin *= t1;
if (t.skewY) {
t1 = Math.tan(skewY * _DEG2RAD);
t1 = Math.sqrt(1 + t1 * t1);
a11 *= t1;
a21 *= t1;
}
}
}
a12 = -sin;
a22 = cos;
} else if (!rotationY && !rotationX && sz === 1 && !perspective && !isSVG) {//if we're only translating and/or 2D scaling, this is faster...
style[_transformProp] = (t.xPercent || t.yPercent ? "translate(" + t.xPercent + "%," + t.yPercent + "%) translate3d(" : "translate3d(") + x + "px," + y + "px," + z + "px)" + (sx !== 1 || sy !== 1 ? " scale(" + sx + "," + sy + ")" : "");
return;
} else {
a11 = a22 = 1;
a12 = a21 = 0;
}
// KEY INDEX AFFECTS a[row][column]
// a11 0 rotation, rotationY, scaleX
// a21 1 rotation, rotationY, scaleX
// a31 2 rotationY, scaleX
// a41 3 rotationY, scaleX
// a12 4 rotation, skewX, rotationX, scaleY
// a22 5 rotation, skewX, rotationX, scaleY
// a32 6 rotationX, scaleY
// a42 7 rotationX, scaleY
// a13 8 rotationY, rotationX, scaleZ
// a23 9 rotationY, rotationX, scaleZ
// a33 10 rotationY, rotationX, scaleZ
// a43 11 rotationY, rotationX, perspective, scaleZ
// a14 12 x, zOrigin, svgOrigin
// a24 13 y, zOrigin, svgOrigin
// a34 14 z, zOrigin
// a44 15
// rotation: Math.atan2(a21, a11)
// rotationY: Math.atan2(a13, a33) (or Math.atan2(a13, a11))
// rotationX: Math.atan2(a32, a33)
a33 = 1;
a13 = a23 = a31 = a32 = a41 = a42 = 0;
a43 = perspective ? -1 / perspective : 0;
zOrigin = t.zOrigin;
min = 0.000001; //threshold below which browsers use scientific notation which won't work.
comma = ",";
zero = "0";
angle = rotationY * _DEG2RAD;
if (angle) {
cos = Math.cos(angle);
sin = Math.sin(angle);
a31 = -sin;
a41 = a43 * -sin;
a13 = a11 * sin;
a23 = a21 * sin;
a33 = cos;
a43 *= cos;
a11 *= cos;
a21 *= cos;
}
angle = rotationX * _DEG2RAD;
if (angle) {
cos = Math.cos(angle);
sin = Math.sin(angle);
t1 = a12 * cos + a13 * sin;
t2 = a22 * cos + a23 * sin;
a32 = a33 * sin;
a42 = a43 * sin;
a13 = a12 * -sin + a13 * cos;
a23 = a22 * -sin + a23 * cos;
a33 = a33 * cos;
a43 = a43 * cos;
a12 = t1;
a22 = t2;
}
if (sz !== 1) {
a13 *= sz;
a23 *= sz;
a33 *= sz;
a43 *= sz;
}
if (sy !== 1) {
a12 *= sy;
a22 *= sy;
a32 *= sy;
a42 *= sy;
}
if (sx !== 1) {
a11 *= sx;
a21 *= sx;
a31 *= sx;
a41 *= sx;
}
if (zOrigin || isSVG) {
if (zOrigin) {
x += a13 * -zOrigin;
y += a23 * -zOrigin;
z += a33 * -zOrigin + zOrigin;
}
if (isSVG) {//due to bugs in some browsers, we need to manage the transform-origin of SVG manually
x += t.xOrigin - (t.xOrigin * a11 + t.yOrigin * a12) + t.xOffset;
y += t.yOrigin - (t.xOrigin * a21 + t.yOrigin * a22) + t.yOffset;
}
if (x < min && x > -min) {
x = zero;
}
if (y < min && y > -min) {
y = zero;
}
if (z < min && z > -min) {
z = 0; //don't use string because we calculate perspective later and need the number.
}
}
//optimized way of concatenating all the values into a string. If we do it all in one shot, it's slower because of the way browsers have to create temp strings and the way it affects memory. If we do it piece-by-piece with +=, it's a bit slower too. We found that doing it in these sized chunks works best overall:
transform = t.xPercent || t.yPercent ? "translate(" + t.xPercent + "%," + t.yPercent + "%) matrix3d(" : "matrix3d(";
transform += (a11 < min && a11 > -min ? zero : a11) + comma + (a21 < min && a21 > -min ? zero : a21) + comma + (a31 < min && a31 > -min ? zero : a31);
transform += comma + (a41 < min && a41 > -min ? zero : a41) + comma + (a12 < min && a12 > -min ? zero : a12) + comma + (a22 < min && a22 > -min ? zero : a22);
if (rotationX || rotationY || sz !== 1) {//performance optimization (often there's no rotationX or rotationY, so we can skip these calculations)
transform += comma + (a32 < min && a32 > -min ? zero : a32) + comma + (a42 < min && a42 > -min ? zero : a42) + comma + (a13 < min && a13 > -min ? zero : a13);
transform += comma + (a23 < min && a23 > -min ? zero : a23) + comma + (a33 < min && a33 > -min ? zero : a33) + comma + (a43 < min && a43 > -min ? zero : a43) + comma;
} else {
transform += ",0,0,0,0,1,0,";
}
transform += x + comma + y + comma + z + comma + (perspective ? 1 + -z / perspective : 1) + ")";
style[_transformProp] = transform;
};
p = Transform.prototype;
p.x = p.y = p.z = p.skewX = p.skewY = p.rotation = p.rotationX = p.rotationY = p.zOrigin = p.xPercent = p.yPercent = p.xOffset = p.yOffset = 0;
p.scaleX = p.scaleY = p.scaleZ = 1;
_registerComplexSpecialProp("transform,scale,scaleX,scaleY,scaleZ,x,y,z,rotation,rotationX,rotationY,rotationZ,skewX,skewY,shortRotation,shortRotationX,shortRotationY,shortRotationZ,transformOrigin,svgOrigin,transformPerspective,directionalRotation,parseTransform,force3D,skewType,xPercent,yPercent,smoothOrigin", { parser: function parser(t, e, parsingProp, cssp, pt, plugin, vars) {
if (cssp._lastParsedTransform === vars) {return pt;} //only need to parse the transform once, and only if the browser supports it.
cssp._lastParsedTransform = vars;
var scaleFunc = vars.scale && typeof vars.scale === "function" ? vars.scale : 0, //if there's a function-based "scale" value, swap in the resulting numeric value temporarily. Otherwise, if it's called for both scaleX and scaleY independently, they may not match (like if the function uses Math.random()).
swapFunc;
if (typeof vars[parsingProp] === "function") {//whatever property triggers the initial parsing might be a function-based value in which case it already got called in parse(), thus we don't want to call it again in here. The most efficient way to avoid this is to temporarily swap the value directly into the vars object, and then after we do all our parsing in this function, we'll swap it back again.
swapFunc = vars[parsingProp];
vars[parsingProp] = e;
}
if (scaleFunc) {
vars.scale = scaleFunc(_index, t);
}
var originalGSTransform = t._gsTransform,
style = t.style,
min = 0.000001,
i = _transformProps.length,
v = vars,
endRotations = {},
transformOriginString = "transformOrigin",
m1 = _getTransform(t, _cs, true, v.parseTransform),
orig = v.transform && (typeof v.transform === "function" ? v.transform(_index, _target) : v.transform),
m2,copy,has3D,hasChange,dr,x,y,matrix,p;
m1.skewType = v.skewType || m1.skewType || CSSPlugin.defaultSkewType;
cssp._transform = m1;
if (orig && typeof orig === "string" && _transformProp) {//for values like transform:"rotate(60deg) scale(0.5, 0.8)"
copy = _tempDiv.style; //don't use the original target because it might be SVG in which case some browsers don't report computed style correctly.
copy[_transformProp] = orig;
copy.display = "block"; //if display is "none", the browser often refuses to report the transform properties correctly.
copy.position = "absolute";
_doc.body.appendChild(_tempDiv);
m2 = _getTransform(_tempDiv, null, false);
if (m1.skewType === "simple") {//the default _getTransform() reports the skewX/scaleY as if skewType is "compensated", thus we need to adjust that here if skewType is "simple".
m2.scaleY *= Math.cos(m2.skewX * _DEG2RAD);
}
if (m1.svg) {//if it's an SVG element, x/y part of the matrix will be affected by whatever we use as the origin and the offsets, so compensate here...
x = m1.xOrigin;
y = m1.yOrigin;
m2.x -= m1.xOffset;
m2.y -= m1.yOffset;
if (v.transformOrigin || v.svgOrigin) {//if this tween is altering the origin, we must factor that in here. The actual work of recording the transformOrigin values and setting up the PropTween is done later (still inside this function) so we cannot leave the changes intact here - we only want to update the x/y accordingly.
orig = {};
_parseSVGOrigin(t, _parsePosition(v.transformOrigin), orig, v.svgOrigin, v.smoothOrigin, true);
x = orig.xOrigin;
y = orig.yOrigin;
m2.x -= orig.xOffset - m1.xOffset;
m2.y -= orig.yOffset - m1.yOffset;
}
if (x || y) {
matrix = _getMatrix(_tempDiv, true);
m2.x -= x - (x * matrix[0] + y * matrix[2]);
m2.y -= y - (x * matrix[1] + y * matrix[3]);
}
}
_doc.body.removeChild(_tempDiv);
if (!m2.perspective) {
m2.perspective = m1.perspective; //tweening to no perspective gives very unintuitive results - just keep the same perspective in that case.
}
if (v.xPercent != null) {
m2.xPercent = _parseVal(v.xPercent, m1.xPercent);
}
if (v.yPercent != null) {
m2.yPercent = _parseVal(v.yPercent, m1.yPercent);
}
} else if ((typeof v === "undefined" ? "undefined" : _typeof(v)) === "object") {//for values like scaleX, scaleY, rotation, x, y, skewX, and skewY or transform:{...} (object)
m2 = { scaleX: _parseVal(v.scaleX != null ? v.scaleX : v.scale, m1.scaleX),
scaleY: _parseVal(v.scaleY != null ? v.scaleY : v.scale, m1.scaleY),
scaleZ: _parseVal(v.scaleZ, m1.scaleZ),
x: _parseVal(v.x, m1.x),
y: _parseVal(v.y, m1.y),
z: _parseVal(v.z, m1.z),
xPercent: _parseVal(v.xPercent, m1.xPercent),
yPercent: _parseVal(v.yPercent, m1.yPercent),
perspective: _parseVal(v.transformPerspective, m1.perspective) };
dr = v.directionalRotation;
if (dr != null) {
if ((typeof dr === "undefined" ? "undefined" : _typeof(dr)) === "object") {
for (copy in dr) {
v[copy] = dr[copy];
}
} else {
v.rotation = dr;
}
}
if (typeof v.x === "string" && v.x.indexOf("%") !== -1) {
m2.x = 0;
m2.xPercent = _parseVal(v.x, m1.xPercent);
}
if (typeof v.y === "string" && v.y.indexOf("%") !== -1) {
m2.y = 0;
m2.yPercent = _parseVal(v.y, m1.yPercent);
}
m2.rotation = _parseAngle("rotation" in v ? v.rotation : "shortRotation" in v ? v.shortRotation + "_short" : "rotationZ" in v ? v.rotationZ : m1.rotation, m1.rotation, "rotation", endRotations);
if (_supports3D) {
m2.rotationX = _parseAngle("rotationX" in v ? v.rotationX : "shortRotationX" in v ? v.shortRotationX + "_short" : m1.rotationX || 0, m1.rotationX, "rotationX", endRotations);
m2.rotationY = _parseAngle("rotationY" in v ? v.rotationY : "shortRotationY" in v ? v.shortRotationY + "_short" : m1.rotationY || 0, m1.rotationY, "rotationY", endRotations);
}
m2.skewX = _parseAngle(v.skewX, m1.skewX);
m2.skewY = _parseAngle(v.skewY, m1.skewY);
}
if (_supports3D && v.force3D != null) {
m1.force3D = v.force3D;
hasChange = true;
}
has3D = m1.force3D || m1.z || m1.rotationX || m1.rotationY || m2.z || m2.rotationX || m2.rotationY || m2.perspective;
if (!has3D && v.scale != null) {
m2.scaleZ = 1; //no need to tween scaleZ.
}
while (--i > -1) {
p = _transformProps[i];
orig = m2[p] - m1[p];
if (orig > min || orig < -min || v[p] != null || _forcePT[p] != null) {
hasChange = true;
pt = new CSSPropTween(m1, p, m1[p], orig, pt);
if (p in endRotations) {
pt.e = endRotations[p]; //directional rotations typically have compensated values during the tween, but we need to make sure they end at exactly what the user requested
}
pt.xs0 = 0; //ensures the value stays numeric in setRatio()
pt.plugin = plugin;
cssp._overwriteProps.push(pt.n);
}
}
orig = v.transformOrigin;
if (m1.svg && (orig || v.svgOrigin)) {
x = m1.xOffset; //when we change the origin, in order to prevent things from jumping we adjust the x/y so we must record those here so that we can create PropTweens for them and flip them at the same time as the origin
y = m1.yOffset;
_parseSVGOrigin(t, _parsePosition(orig), m2, v.svgOrigin, v.smoothOrigin);
pt = _addNonTweeningNumericPT(m1, "xOrigin", (originalGSTransform ? m1 : m2).xOrigin, m2.xOrigin, pt, transformOriginString); //note: if there wasn't a transformOrigin defined yet, just start with the destination one; it's wasteful otherwise, and it causes problems with fromTo() tweens. For example, TweenLite.to("#wheel", 3, {rotation:180, transformOrigin:"50% 50%", delay:1}); TweenLite.fromTo("#wheel", 3, {scale:0.5, transformOrigin:"50% 50%"}, {scale:1, delay:2}); would cause a jump when the from values revert at the beginning of the 2nd tween.
pt = _addNonTweeningNumericPT(m1, "yOrigin", (originalGSTransform ? m1 : m2).yOrigin, m2.yOrigin, pt, transformOriginString);
if (x !== m1.xOffset || y !== m1.yOffset) {
pt = _addNonTweeningNumericPT(m1, "xOffset", originalGSTransform ? x : m1.xOffset, m1.xOffset, pt, transformOriginString);
pt = _addNonTweeningNumericPT(m1, "yOffset", originalGSTransform ? y : m1.yOffset, m1.yOffset, pt, transformOriginString);
}
orig = "0px 0px"; //certain browsers (like firefox) completely botch transform-origin, so we must remove it to prevent it from contaminating transforms. We manage it ourselves with xOrigin and yOrigin
}
if (orig || _supports3D && has3D && m1.zOrigin) {//if anything 3D is happening and there's a transformOrigin with a z component that's non-zero, we must ensure that the transformOrigin's z-component is set to 0 so that we can manually do those calculations to get around Safari bugs. Even if the user didn't specifically define a "transformOrigin" in this particular tween (maybe they did it via css directly).
if (_transformProp) {
hasChange = true;
p = _transformOriginProp;
orig = (orig || _getStyle(t, p, _cs, false, "50% 50%")) + ""; //cast as string to avoid errors
pt = new CSSPropTween(style, p, 0, 0, pt, -1, transformOriginString);
pt.b = style[p];
pt.plugin = plugin;
if (_supports3D) {
copy = m1.zOrigin;
orig = orig.split(" ");
m1.zOrigin = (orig.length > 2 && !(copy !== 0 && orig[2] === "0px") ? parseFloat(orig[2]) : copy) || 0; //Safari doesn't handle the z part of transformOrigin correctly, so we'll manually handle it in the _set3DTransformRatio() method.
pt.xs0 = pt.e = orig[0] + " " + (orig[1] || "50%") + " 0px"; //we must define a z value of 0px specifically otherwise iOS 5 Safari will stick with the old one (if one was defined)!
pt = new CSSPropTween(m1, "zOrigin", 0, 0, pt, -1, pt.n); //we must create a CSSPropTween for the _gsTransform.zOrigin so that it gets reset properly at the beginning if the tween runs backward (as opposed to just setting m1.zOrigin here)
pt.b = copy;
pt.xs0 = pt.e = m1.zOrigin;
} else {
pt.xs0 = pt.e = orig;
}
//for older versions of IE (6-8), we need to manually calculate things inside the setRatio() function. We record origin x and y (ox and oy) and whether or not the values are percentages (oxp and oyp).
} else {
_parsePosition(orig + "", m1);
}
}
if (hasChange) {
cssp._transformType = !(m1.svg && _useSVGTransformAttr) && (has3D || this._transformType === 3) ? 3 : 2; //quicker than calling cssp._enableTransforms();
}
if (swapFunc) {
vars[parsingProp] = swapFunc;
}
if (scaleFunc) {
vars.scale = scaleFunc;
}
return pt;
}, prefix: true });
_registerComplexSpecialProp("boxShadow", { defaultValue: "0px 0px 0px 0px #999", prefix: true, color: true, multi: true, keyword: "inset" });
_registerComplexSpecialProp("borderRadius", { defaultValue: "0px", parser: function parser(t, e, p, cssp, pt, plugin) {
e = this.format(e);
var props = ["borderTopLeftRadius", "borderTopRightRadius", "borderBottomRightRadius", "borderBottomLeftRadius"],
style = t.style,
ea1,i,es2,bs2,bs,es,bn,en,w,h,esfx,bsfx,rel,hn,vn,em;
w = parseFloat(t.offsetWidth);
h = parseFloat(t.offsetHeight);
ea1 = e.split(" ");
for (i = 0; i < props.length; i++) {//if we're dealing with percentages, we must convert things separately for the horizontal and vertical axis!
if (this.p.indexOf("border")) {//older browsers used a prefix
props[i] = _checkPropPrefix(props[i]);
}
bs = bs2 = _getStyle(t, props[i], _cs, false, "0px");
if (bs.indexOf(" ") !== -1) {
bs2 = bs.split(" ");
bs = bs2[0];
bs2 = bs2[1];
}
es = es2 = ea1[i];
bn = parseFloat(bs);
bsfx = bs.substr((bn + "").length);
rel = es.charAt(1) === "=";
if (rel) {
en = parseInt(es.charAt(0) + "1", 10);
es = es.substr(2);
en *= parseFloat(es);
esfx = es.substr((en + "").length - (en < 0 ? 1 : 0)) || "";
} else {
en = parseFloat(es);
esfx = es.substr((en + "").length);
}
if (esfx === "") {
esfx = _suffixMap[p] || bsfx;
}
if (esfx !== bsfx) {
hn = _convertToPixels(t, "borderLeft", bn, bsfx); //horizontal number (we use a bogus "borderLeft" property just because the _convertToPixels() method searches for the keywords "Left", "Right", "Top", and "Bottom" to determine of it's a horizontal or vertical property, and we need "border" in the name so that it knows it should measure relative to the element itself, not its parent.
vn = _convertToPixels(t, "borderTop", bn, bsfx); //vertical number
if (esfx === "%") {
bs = hn / w * 100 + "%";
bs2 = vn / h * 100 + "%";
} else if (esfx === "em") {
em = _convertToPixels(t, "borderLeft", 1, "em");
bs = hn / em + "em";
bs2 = vn / em + "em";
} else {
bs = hn + "px";
bs2 = vn + "px";
}
if (rel) {
es = parseFloat(bs) + en + esfx;
es2 = parseFloat(bs2) + en + esfx;
}
}
pt = _parseComplex(style, props[i], bs + " " + bs2, es + " " + es2, false, "0px", pt);
}
return pt;
}, prefix: true, formatter: _getFormatter("0px 0px 0px 0px", false, true) });
_registerComplexSpecialProp("borderBottomLeftRadius,borderBottomRightRadius,borderTopLeftRadius,borderTopRightRadius", { defaultValue: "0px", parser: function parser(t, e, p, cssp, pt, plugin) {
return _parseComplex(t.style, p, this.format(_getStyle(t, p, _cs, false, "0px 0px")), this.format(e), false, "0px", pt);
}, prefix: true, formatter: _getFormatter("0px 0px", false, true) });
_registerComplexSpecialProp("backgroundPosition", { defaultValue: "0 0", parser: function parser(t, e, p, cssp, pt, plugin) {
var bp = "background-position",
cs = _cs || _getComputedStyle(t, null),
bs = this.format((cs ? _ieVers ? cs.getPropertyValue(bp + "-x") + " " + cs.getPropertyValue(bp + "-y") : cs.getPropertyValue(bp) : t.currentStyle.backgroundPositionX + " " + t.currentStyle.backgroundPositionY) || "0 0"), //Internet Explorer doesn't report background-position correctly - we must query background-position-x and background-position-y and combine them (even in IE10). Before IE9, we must do the same with the currentStyle object and use camelCase
es = this.format(e),
ba,ea,i,pct,overlap,src;
if (bs.indexOf("%") !== -1 !== (es.indexOf("%") !== -1) && es.split(",").length < 2) {
src = _getStyle(t, "backgroundImage").replace(_urlExp, "");
if (src && src !== "none") {
ba = bs.split(" ");
ea = es.split(" ");
_tempImg.setAttribute("src", src); //set the temp IMG's src to the background-image so that we can measure its width/height
i = 2;
while (--i > -1) {
bs = ba[i];
pct = bs.indexOf("%") !== -1;
if (pct !== (ea[i].indexOf("%") !== -1)) {
overlap = i === 0 ? t.offsetWidth - _tempImg.width : t.offsetHeight - _tempImg.height;
ba[i] = pct ? parseFloat(bs) / 100 * overlap + "px" : parseFloat(bs) / overlap * 100 + "%";
}
}
bs = ba.join(" ");
}
}
return this.parseComplex(t.style, bs, es, pt, plugin);
}, formatter: _parsePosition });
_registerComplexSpecialProp("backgroundSize", { defaultValue: "0 0", formatter: function formatter(v) {
v += ""; //ensure it's a string
return _parsePosition(v.indexOf(" ") === -1 ? v + " " + v : v); //if set to something like "100% 100%", Safari typically reports the computed style as just "100%" (no 2nd value), but we should ensure that there are two values, so copy the first one. Otherwise, it'd be interpreted as "100% 0" (wrong).
} });
_registerComplexSpecialProp("perspective", { defaultValue: "0px", prefix: true });
_registerComplexSpecialProp("perspectiveOrigin", { defaultValue: "50% 50%", prefix: true });
_registerComplexSpecialProp("transformStyle", { prefix: true });
_registerComplexSpecialProp("backfaceVisibility", { prefix: true });
_registerComplexSpecialProp("userSelect", { prefix: true });
_registerComplexSpecialProp("margin", { parser: _getEdgeParser("marginTop,marginRight,marginBottom,marginLeft") });
_registerComplexSpecialProp("padding", { parser: _getEdgeParser("paddingTop,paddingRight,paddingBottom,paddingLeft") });
_registerComplexSpecialProp("clip", { defaultValue: "rect(0px,0px,0px,0px)", parser: function parser(t, e, p, cssp, pt, plugin) {
var b, cs, delim;
if (_ieVers < 9) {//IE8 and earlier don't report a "clip" value in the currentStyle - instead, the values are split apart into clipTop, clipRight, clipBottom, and clipLeft. Also, in IE7 and earlier, the values inside rect() are space-delimited, not comma-delimited.
cs = t.currentStyle;
delim = _ieVers < 8 ? " " : ",";
b = "rect(" + cs.clipTop + delim + cs.clipRight + delim + cs.clipBottom + delim + cs.clipLeft + ")";
e = this.format(e).split(",").join(delim);
} else {
b = this.format(_getStyle(t, this.p, _cs, false, this.dflt));
e = this.format(e);
}
return this.parseComplex(t.style, b, e, pt, plugin);
} });
_registerComplexSpecialProp("textShadow", { defaultValue: "0px 0px 0px #999", color: true, multi: true });
_registerComplexSpecialProp("autoRound,strictUnits", { parser: function parser(t, e, p, cssp, pt) {return pt;} }); //just so that we can ignore these properties (not tween them)
_registerComplexSpecialProp("border", { defaultValue: "0px solid #000", parser: function parser(t, e, p, cssp, pt, plugin) {
var bw = _getStyle(t, "borderTopWidth", _cs, false, "0px"),
end = this.format(e).split(" "),
esfx = end[0].replace(_suffixExp, "");
if (esfx !== "px") {//if we're animating to a non-px value, we need to convert the beginning width to that unit.
bw = parseFloat(bw) / _convertToPixels(t, "borderTopWidth", 1, esfx) + esfx;
}
return this.parseComplex(t.style, this.format(bw + " " + _getStyle(t, "borderTopStyle", _cs, false, "solid") + " " + _getStyle(t, "borderTopColor", _cs, false, "#000")), end.join(" "), pt, plugin);
}, color: true, formatter: function formatter(v) {
var a = v.split(" ");
return a[0] + " " + (a[1] || "solid") + " " + (v.match(_colorExp) || ["#000"])[0];
} });
_registerComplexSpecialProp("borderWidth", { parser: _getEdgeParser("borderTopWidth,borderRightWidth,borderBottomWidth,borderLeftWidth") }); //Firefox doesn't pick up on borderWidth set in style sheets (only inline).
_registerComplexSpecialProp("float,cssFloat,styleFloat", { parser: function parser(t, e, p, cssp, pt, plugin) {
var s = t.style,
prop = "cssFloat" in s ? "cssFloat" : "styleFloat";
return new CSSPropTween(s, prop, 0, 0, pt, -1, p, false, 0, s[prop], e);
} });
//opacity-related
var _setIEOpacityRatio = function _setIEOpacityRatio(v) {
var t = this.t, //refers to the element's style property
filters = t.filter || _getStyle(this.data, "filter") || "",
val = this.s + this.c * v | 0,
skip;
if (val === 100) {//for older versions of IE that need to use a filter to apply opacity, we should remove the filter if opacity hits 1 in order to improve performance, but make sure there isn't a transform (matrix) or gradient in the filters.
if (filters.indexOf("atrix(") === -1 && filters.indexOf("radient(") === -1 && filters.indexOf("oader(") === -1) {
t.removeAttribute("filter");
skip = !_getStyle(this.data, "filter"); //if a class is applied that has an alpha filter, it will take effect (we don't want that), so re-apply our alpha filter in that case. We must first remove it and then check.
} else {
t.filter = filters.replace(_alphaFilterExp, "");
skip = true;
}
}
if (!skip) {
if (this.xn1) {
t.filter = filters = filters || "alpha(opacity=" + val + ")"; //works around bug in IE7/8 that prevents changes to "visibility" from being applied properly if the filter is changed to a different alpha on the same frame.
}
if (filters.indexOf("pacity") === -1) {//only used if browser doesn't support the standard opacity style property (IE 7 and 8). We omit the "O" to avoid case-sensitivity issues
if (val !== 0 || !this.xn1) {//bugs in IE7/8 won't render the filter properly if opacity is ADDED on the same frame/render as "visibility" changes (this.xn1 is 1 if this tween is an "autoAlpha" tween)
t.filter = filters + " alpha(opacity=" + val + ")"; //we round the value because otherwise, bugs in IE7/8 can prevent "visibility" changes from being applied properly.
}
} else {
t.filter = filters.replace(_opacityExp, "opacity=" + val);
}
}
};
_registerComplexSpecialProp("opacity,alpha,autoAlpha", { defaultValue: "1", parser: function parser(t, e, p, cssp, pt, plugin) {
var b = parseFloat(_getStyle(t, "opacity", _cs, false, "1")),
style = t.style,
isAutoAlpha = p === "autoAlpha";
if (typeof e === "string" && e.charAt(1) === "=") {
e = (e.charAt(0) === "-" ? -1 : 1) * parseFloat(e.substr(2)) + b;
}
if (isAutoAlpha && b === 1 && _getStyle(t, "visibility", _cs) === "hidden" && e !== 0) {//if visibility is initially set to "hidden", we should interpret that as intent to make opacity 0 (a convenience)
b = 0;
}
if (_supportsOpacity) {
pt = new CSSPropTween(style, "opacity", b, e - b, pt);
} else {
pt = new CSSPropTween(style, "opacity", b * 100, (e - b) * 100, pt);
pt.xn1 = isAutoAlpha ? 1 : 0; //we need to record whether or not this is an autoAlpha so that in the setRatio(), we know to duplicate the setting of the alpha in order to work around a bug in IE7 and IE8 that prevents changes to "visibility" from taking effect if the filter is changed to a different alpha(opacity) at the same time. Setting it to the SAME value first, then the new value works around the IE7/8 bug.
style.zoom = 1; //helps correct an IE issue.
pt.type = 2;
pt.b = "alpha(opacity=" + pt.s + ")";
pt.e = "alpha(opacity=" + (pt.s + pt.c) + ")";
pt.data = t;
pt.plugin = plugin;
pt.setRatio = _setIEOpacityRatio;
}
if (isAutoAlpha) {//we have to create the "visibility" PropTween after the opacity one in the linked list so that they run in the order that works properly in IE8 and earlier
pt = new CSSPropTween(style, "visibility", 0, 0, pt, -1, null, false, 0, b !== 0 ? "inherit" : "hidden", e === 0 ? "hidden" : "inherit");
pt.xs0 = "inherit";
cssp._overwriteProps.push(pt.n);
cssp._overwriteProps.push(p);
}
return pt;
} });
var _removeProp = function _removeProp(s, p) {
if (p) {
if (s.removeProperty) {
if (p.substr(0, 2) === "ms" || p.substr(0, 6) === "webkit") {//Microsoft and some Webkit browsers don't conform to the standard of capitalizing the first prefix character, so we adjust so that when we prefix the caps with a dash, it's correct (otherwise it'd be "ms-transform" instead of "-ms-transform" for IE9, for example)
p = "-" + p;
}
s.removeProperty(p.replace(_capsExp, "-$1").toLowerCase());
} else {//note: old versions of IE use "removeAttribute()" instead of "removeProperty()"
s.removeAttribute(p);
}
}
},
_setClassNameRatio = function _setClassNameRatio(v) {
this.t._gsClassPT = this;
if (v === 1 || v === 0) {
this.t.setAttribute("class", v === 0 ? this.b : this.e);
var mpt = this.data, //first MiniPropTween
s = this.t.style;
while (mpt) {
if (!mpt.v) {
_removeProp(s, mpt.p);
} else {
s[mpt.p] = mpt.v;
}
mpt = mpt._next;
}
if (v === 1 && this.t._gsClassPT === this) {
this.t._gsClassPT = null;
}
} else if (this.t.getAttribute("class") !== this.e) {
this.t.setAttribute("class", this.e);
}
};
_registerComplexSpecialProp("className", { parser: function parser(t, e, p, cssp, pt, plugin, vars) {
var b = t.getAttribute("class") || "", //don't use t.className because it doesn't work consistently on SVG elements; getAttribute("class") and setAttribute("class", value") is more reliable.
cssText = t.style.cssText,
difData,bs,cnpt,cnptLookup,mpt;
pt = cssp._classNamePT = new CSSPropTween(t, p, 0, 0, pt, 2);
pt.setRatio = _setClassNameRatio;
pt.pr = -11;
_hasPriority = true;
pt.b = b;
bs = _getAllStyles(t, _cs);
//if there's a className tween already operating on the target, force it to its end so that the necessary inline styles are removed and the class name is applied before we determine the end state (we don't want inline styles interfering that were there just for class-specific values)
cnpt = t._gsClassPT;
if (cnpt) {
cnptLookup = {};
mpt = cnpt.data; //first MiniPropTween which stores the inline styles - we need to force these so that the inline styles don't contaminate things. Otherwise, there's a small chance that a tween could start and the inline values match the destination values and they never get cleaned.
while (mpt) {
cnptLookup[mpt.p] = 1;
mpt = mpt._next;
}
cnpt.setRatio(1);
}
t._gsClassPT = pt;
pt.e = e.charAt(1) !== "=" ? e : b.replace(new RegExp("(?:\\s|^)" + e.substr(2) + "(?![\\w-])"), "") + (e.charAt(0) === "+" ? " " + e.substr(2) : "");
t.setAttribute("class", pt.e);
difData = _cssDif(t, bs, _getAllStyles(t), vars, cnptLookup);
t.setAttribute("class", b);
pt.data = difData.firstMPT;
t.style.cssText = cssText; //we recorded cssText before we swapped classes and ran _getAllStyles() because in cases when a className tween is overwritten, we remove all the related tweening properties from that class change (otherwise class-specific stuff can't override properties we've directly set on the target's style object due to specificity).
pt = pt.xfirst = cssp.parse(t, difData.difs, pt, plugin); //we record the CSSPropTween as the xfirst so that we can handle overwriting propertly (if "className" gets overwritten, we must kill all the properties associated with the className part of the tween, so we can loop through from xfirst to the pt itself)
return pt;
} });
var _setClearPropsRatio = function _setClearPropsRatio(v) {
if (v === 1 || v === 0) if (this.data._totalTime === this.data._totalDuration && this.data.data !== "isFromStart") {//this.data refers to the tween. Only clear at the END of the tween (remember, from() tweens make the ratio go from 1 to 0, so we can't just check that and if the tween is the zero-duration one that's created internally to render the starting values in a from() tween, ignore that because otherwise, for example, from(...{height:100, clearProps:"height", delay:1}) would wipe the height at the beginning of the tween and after 1 second, it'd kick back in).
var s = this.t.style,
transformParse = _specialProps.transform.parse,
a,p,i,clearTransform,transform;
if (this.e === "all") {
s.cssText = "";
clearTransform = true;
} else {
a = this.e.split(" ").join("").split(",");
i = a.length;
while (--i > -1) {
p = a[i];
if (_specialProps[p]) {
if (_specialProps[p].parse === transformParse) {
clearTransform = true;
} else {
p = p === "transformOrigin" ? _transformOriginProp : _specialProps[p].p; //ensures that special properties use the proper browser-specific property name, like "scaleX" might be "-webkit-transform" or "boxShadow" might be "-moz-box-shadow"
}
}
_removeProp(s, p);
}
}
if (clearTransform) {
_removeProp(s, _transformProp);
transform = this.t._gsTransform;
if (transform) {
if (transform.svg) {
this.t.removeAttribute("data-svg-origin");
this.t.removeAttribute("transform");
}
delete this.t._gsTransform;
}
}
}
};
_registerComplexSpecialProp("clearProps", { parser: function parser(t, e, p, cssp, pt) {
pt = new CSSPropTween(t, p, 0, 0, pt, 2);
pt.setRatio = _setClearPropsRatio;
pt.e = e;
pt.pr = -10;
pt.data = cssp._tween;
_hasPriority = true;
return pt;
} });
p = "bezier,throwProps,physicsProps,physics2D".split(",");
i = p.length;
while (i--) {
_registerPluginProp(p[i]);
}
p = CSSPlugin.prototype;
p._firstPT = p._lastParsedTransform = p._transform = null;
//gets called when the tween renders for the first time. This kicks everything off, recording start/end values, etc.
p._onInitTween = function (target, vars, tween, index) {
if (!target.nodeType) {//css is only for dom elements
return false;
}
this._target = _target = target;
this._tween = tween;
this._vars = vars;
_index = index;
_autoRound = vars.autoRound;
_hasPriority = false;
_suffixMap = vars.suffixMap || CSSPlugin.suffixMap;
_cs = _getComputedStyle(target, "");
_overwriteProps = this._overwriteProps;
var style = target.style,
v,pt,pt2,first,last,next,zIndex,tpt,threeD;
if (_reqSafariFix) if (style.zIndex === "") {
v = _getStyle(target, "zIndex", _cs);
if (v === "auto" || v === "") {
//corrects a bug in [non-Android] Safari that prevents it from repainting elements in their new positions if they don't have a zIndex set. We also can't just apply this inside _parseTransform() because anything that's moved in any way (like using "left" or "top" instead of transforms like "x" and "y") can be affected, so it is best to ensure that anything that's tweening has a z-index. Setting "WebkitPerspective" to a non-zero value worked too except that on iOS Safari things would flicker randomly. Plus zIndex is less memory-intensive.
this._addLazySet(style, "zIndex", 0);
}
}
if (typeof vars === "string") {
first = style.cssText;
v = _getAllStyles(target, _cs);
style.cssText = first + ";" + vars;
v = _cssDif(target, v, _getAllStyles(target)).difs;
if (!_supportsOpacity && _opacityValExp.test(vars)) {
v.opacity = parseFloat(RegExp.$1);
}
vars = v;
style.cssText = first;
}
if (vars.className) {//className tweens will combine any differences they find in the css with the vars that are passed in, so {className:"myClass", scale:0.5, left:20} would work.
this._firstPT = pt = _specialProps.className.parse(target, vars.className, "className", this, null, null, vars);
} else {
this._firstPT = pt = this.parse(target, vars, null);
}
if (this._transformType) {
threeD = this._transformType === 3;
if (!_transformProp) {
style.zoom = 1; //helps correct an IE issue.
} else if (_isSafari) {
_reqSafariFix = true;
//if zIndex isn't set, iOS Safari doesn't repaint things correctly sometimes (seemingly at random).
if (style.zIndex === "") {
zIndex = _getStyle(target, "zIndex", _cs);
if (zIndex === "auto" || zIndex === "") {
this._addLazySet(style, "zIndex", 0);
}
}
//Setting WebkitBackfaceVisibility corrects 3 bugs:
// 1) [non-Android] Safari skips rendering changes to "top" and "left" that are made on the same frame/render as a transform update.
// 2) iOS Safari sometimes neglects to repaint elements in their new positions. Setting "WebkitPerspective" to a non-zero value worked too except that on iOS Safari things would flicker randomly.
// 3) Safari sometimes displayed odd artifacts when tweening the transform (or WebkitTransform) property, like ghosts of the edges of the element remained. Definitely a browser bug.
//Note: we allow the user to override the auto-setting by defining WebkitBackfaceVisibility in the vars of the tween.
if (_isSafariLT6) {
this._addLazySet(style, "WebkitBackfaceVisibility", this._vars.WebkitBackfaceVisibility || (threeD ? "visible" : "hidden"));
}
}
pt2 = pt;
while (pt2 && pt2._next) {
pt2 = pt2._next;
}
tpt = new CSSPropTween(target, "transform", 0, 0, null, 2);
this._linkCSSP(tpt, null, pt2);
tpt.setRatio = _transformProp ? _setTransformRatio : _setIETransformRatio;
tpt.data = this._transform || _getTransform(target, _cs, true);
tpt.tween = tween;
tpt.pr = -1; //ensures that the transforms get applied after the components are updated.
_overwriteProps.pop(); //we don't want to force the overwrite of all "transform" tweens of the target - we only care about individual transform properties like scaleX, rotation, etc. The CSSPropTween constructor automatically adds the property to _overwriteProps which is why we need to pop() here.
}
if (_hasPriority) {
//reorders the linked list in order of pr (priority)
while (pt) {
next = pt._next;
pt2 = first;
while (pt2 && pt2.pr > pt.pr) {
pt2 = pt2._next;
}
if (pt._prev = pt2 ? pt2._prev : last) {
pt._prev._next = pt;
} else {
first = pt;
}
if (pt._next = pt2) {
pt2._prev = pt;
} else {
last = pt;
}
pt = next;
}
this._firstPT = first;
}
return true;
};
p.parse = function (target, vars, pt, plugin) {
var style = target.style,
p,sp,bn,en,bs,es,bsfx,esfx,isStr,rel;
for (p in vars) {
es = vars[p]; //ending value string
if (typeof es === "function") {
es = es(_index, _target);
}
sp = _specialProps[p]; //SpecialProp lookup.
if (sp) {
pt = sp.parse(target, es, p, this, pt, plugin, vars);
} else if (p.substr(0, 2) === "--") {//for tweening CSS variables (which always start with "--"). To maximize performance and simplicity, we bypass CSSPlugin altogether and just add a normal property tween to the tween instance itself.
this._tween._propLookup[p] = this._addTween.call(this._tween, target.style, "setProperty", _getComputedStyle(target).getPropertyValue(p) + "", es + "", p, false, p);
continue;
} else {
bs = _getStyle(target, p, _cs) + "";
isStr = typeof es === "string";
if (p === "color" || p === "fill" || p === "stroke" || p.indexOf("Color") !== -1 || isStr && _rgbhslExp.test(es)) {//Opera uses background: to define color sometimes in addition to backgroundColor:
if (!isStr) {
es = _parseColor(es);
es = (es.length > 3 ? "rgba(" : "rgb(") + es.join(",") + ")";
}
pt = _parseComplex(style, p, bs, es, true, "transparent", pt, 0, plugin);
} else if (isStr && _complexExp.test(es)) {
pt = _parseComplex(style, p, bs, es, true, null, pt, 0, plugin);
} else {
bn = parseFloat(bs);
bsfx = bn || bn === 0 ? bs.substr((bn + "").length) : ""; //remember, bs could be non-numeric like "normal" for fontWeight, so we should default to a blank suffix in that case.
if (bs === "" || bs === "auto") {
if (p === "width" || p === "height") {
bn = _getDimension(target, p, _cs);
bsfx = "px";
} else if (p === "left" || p === "top") {
bn = _calculateOffset(target, p, _cs);
bsfx = "px";
} else {
bn = p !== "opacity" ? 0 : 1;
bsfx = "";
}
}
rel = isStr && es.charAt(1) === "=";
if (rel) {
en = parseInt(es.charAt(0) + "1", 10);
es = es.substr(2);
en *= parseFloat(es);
esfx = es.replace(_suffixExp, "");
} else {
en = parseFloat(es);
esfx = isStr ? es.replace(_suffixExp, "") : "";
}
if (esfx === "") {
esfx = p in _suffixMap ? _suffixMap[p] : bsfx; //populate the end suffix, prioritizing the map, then if none is found, use the beginning suffix.
}
es = en || en === 0 ? (rel ? en + bn : en) + esfx : vars[p]; //ensures that any += or -= prefixes are taken care of. Record the end value before normalizing the suffix because we always want to end the tween on exactly what they intended even if it doesn't match the beginning value's suffix.
//if the beginning/ending suffixes don't match, normalize them...
if (bsfx !== esfx) if (esfx !== "" || p === "lineHeight") if (en || en === 0) if (bn) {//note: if the beginning value (bn) is 0, we don't need to convert units!
bn = _convertToPixels(target, p, bn, bsfx);
if (esfx === "%") {
bn /= _convertToPixels(target, p, 100, "%") / 100;
if (vars.strictUnits !== true) {//some browsers report only "px" values instead of allowing "%" with getComputedStyle(), so we assume that if we're tweening to a %, we should start there too unless strictUnits:true is defined. This approach is particularly useful for responsive designs that use from() tweens.
bs = bn + "%";
}
} else if (esfx === "em" || esfx === "rem" || esfx === "vw" || esfx === "vh") {
bn /= _convertToPixels(target, p, 1, esfx);
//otherwise convert to pixels.
} else if (esfx !== "px") {
en = _convertToPixels(target, p, en, esfx);
esfx = "px"; //we don't use bsfx after this, so we don't need to set it to px too.
}
if (rel) if (en || en === 0) {
es = en + bn + esfx; //the changes we made affect relative calculations, so adjust the end value here.
}
}
if (rel) {
en += bn;
}
if ((bn || bn === 0) && (en || en === 0)) {//faster than isNaN(). Also, previously we required en !== bn but that doesn't really gain much performance and it prevents _parseToProxy() from working properly if beginning and ending values match but need to get tweened by an external plugin anyway. For example, a bezier tween where the target starts at left:0 and has these points: [{left:50},{left:0}] wouldn't work properly because when parsing the last point, it'd match the first (current) one and a non-tweening CSSPropTween would be recorded when we actually need a normal tween (type:0) so that things get updated during the tween properly.
pt = new CSSPropTween(style, p, bn, en - bn, pt, 0, p, _autoRound !== false && (esfx === "px" || p === "zIndex"), 0, bs, es);
pt.xs0 = esfx;
//DEBUG: _log("tween "+p+" from "+pt.b+" ("+bn+esfx+") to "+pt.e+" with suffix: "+pt.xs0);
} else if (style[p] === undefined || !es && (es + "" === "NaN" || es == null)) {
_log("invalid " + p + " tween value: " + vars[p]);
} else {
pt = new CSSPropTween(style, p, en || bn || 0, 0, pt, -1, p, false, 0, bs, es);
pt.xs0 = es === "none" && (p === "display" || p.indexOf("Style") !== -1) ? bs : es; //intermediate value should typically be set immediately (end value) except for "display" or things like borderTopStyle, borderBottomStyle, etc. which should use the beginning value during the tween.
//DEBUG: _log("non-tweening value "+p+": "+pt.xs0);
}
}
}
if (plugin) if (pt && !pt.plugin) {
pt.plugin = plugin;
}
}
return pt;
};
//gets called every time the tween updates, passing the new ratio (typically a value between 0 and 1, but not always (for example, if an Elastic.easeOut is used, the value can jump above 1 mid-tween). It will always start and 0 and end at 1.
p.setRatio = function (v) {
var pt = this._firstPT,
min = 0.000001,
val,str,i;
//at the end of the tween, we set the values to exactly what we received in order to make sure non-tweening values (like "position" or "float" or whatever) are set and so that if the beginning/ending suffixes (units) didn't match and we normalized to px, the value that the user passed in is used here. We check to see if the tween is at its beginning in case it's a from() tween in which case the ratio will actually go from 1 to 0 over the course of the tween (backwards).
if (v === 1 && (this._tween._time === this._tween._duration || this._tween._time === 0)) {
while (pt) {
if (pt.type !== 2) {
if (pt.r && pt.type !== -1) {
val = Math.round(pt.s + pt.c);
if (!pt.type) {
pt.t[pt.p] = val + pt.xs0;
} else if (pt.type === 1) {//complex value (one that typically has multiple numbers inside a string, like "rect(5px,10px,20px,25px)"
i = pt.l;
str = pt.xs0 + val + pt.xs1;
for (i = 1; i < pt.l; i++) {
str += pt["xn" + i] + pt["xs" + (i + 1)];
}
pt.t[pt.p] = str;
}
} else {
pt.t[pt.p] = pt.e;
}
} else {
pt.setRatio(v);
}
pt = pt._next;
}
} else if (v || !(this._tween._time === this._tween._duration || this._tween._time === 0) || this._tween._rawPrevTime === -0.000001) {
while (pt) {
val = pt.c * v + pt.s;
if (pt.r) {
val = Math.round(val);
} else if (val < min) if (val > -min) {
val = 0;
}
if (!pt.type) {
pt.t[pt.p] = val + pt.xs0;
} else if (pt.type === 1) {//complex value (one that typically has multiple numbers inside a string, like "rect(5px,10px,20px,25px)"
i = pt.l;
if (i === 2) {
pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2;
} else if (i === 3) {
pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2 + pt.xn2 + pt.xs3;
} else if (i === 4) {
pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2 + pt.xn2 + pt.xs3 + pt.xn3 + pt.xs4;
} else if (i === 5) {
pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2 + pt.xn2 + pt.xs3 + pt.xn3 + pt.xs4 + pt.xn4 + pt.xs5;
} else {
str = pt.xs0 + val + pt.xs1;
for (i = 1; i < pt.l; i++) {
str += pt["xn" + i] + pt["xs" + (i + 1)];
}
pt.t[pt.p] = str;
}
} else if (pt.type === -1) {//non-tweening value
pt.t[pt.p] = pt.xs0;
} else if (pt.setRatio) {//custom setRatio() for things like SpecialProps, external plugins, etc.
pt.setRatio(v);
}
pt = pt._next;
}
//if the tween is reversed all the way back to the beginning, we need to restore the original values which may have different units (like % instead of px or em or whatever).
} else {
while (pt) {
if (pt.type !== 2) {
pt.t[pt.p] = pt.b;
} else {
pt.setRatio(v);
}
pt = pt._next;
}
}
};
/**
* @private
* Forces rendering of the target's transforms (rotation, scale, etc.) whenever the CSSPlugin's setRatio() is called.
* Basically, this tells the CSSPlugin to create a CSSPropTween (type 2) after instantiation that runs last in the linked
* list and calls the appropriate (3D or 2D) rendering function. We separate this into its own method so that we can call
* it from other plugins like BezierPlugin if, for example, it needs to apply an autoRotation and this CSSPlugin
* doesn't have any transform-related properties of its own. You can call this method as many times as you
* want and it won't create duplicate CSSPropTweens.
*
* @param {boolean} threeD if true, it should apply 3D tweens (otherwise, just 2D ones are fine and typically faster)
*/
p._enableTransforms = function (threeD) {
this._transform = this._transform || _getTransform(this._target, _cs, true); //ensures that the element has a _gsTransform property with the appropriate values.
this._transformType = !(this._transform.svg && _useSVGTransformAttr) && (threeD || this._transformType === 3) ? 3 : 2;
};
var lazySet = function lazySet(v) {
this.t[this.p] = this.e;
this.data._linkCSSP(this, this._next, null, true); //we purposefully keep this._next even though it'd make sense to null it, but this is a performance optimization, as this happens during the while (pt) {} loop in setRatio() at the bottom of which it sets pt = pt._next, so if we null it, the linked list will be broken in that loop.
};
/** @private Gives us a way to set a value on the first render (and only the first render). **/
p._addLazySet = function (t, p, v) {
var pt = this._firstPT = new CSSPropTween(t, p, 0, 0, this._firstPT, 2);
pt.e = v;
pt.setRatio = lazySet;
pt.data = this;
};
/** @private **/
p._linkCSSP = function (pt, next, prev, remove) {
if (pt) {
if (next) {
next._prev = pt;
}
if (pt._next) {
pt._next._prev = pt._prev;
}
if (pt._prev) {
pt._prev._next = pt._next;
} else if (this._firstPT === pt) {
this._firstPT = pt._next;
remove = true; //just to prevent resetting this._firstPT 5 lines down in case pt._next is null. (optimized for speed)
}
if (prev) {
prev._next = pt;
} else if (!remove && this._firstPT === null) {
this._firstPT = pt;
}
pt._next = next;
pt._prev = prev;
}
return pt;
};
p._mod = function (lookup) {
var pt = this._firstPT;
while (pt) {
if (typeof lookup[pt.p] === "function" && lookup[pt.p] === Math.round) {//only gets called by RoundPropsPlugin (ModifyPlugin manages all the rendering internally for CSSPlugin properties that need modification). Remember, we handle rounding a bit differently in this plugin for performance reasons, leveraging "r" as an indicator that the value should be rounded internally..
pt.r = 1;
}
pt = pt._next;
}
};
//we need to make sure that if alpha or autoAlpha is killed, opacity is too. And autoAlpha affects the "visibility" property.
p._kill = function (lookup) {
var copy = lookup,
pt,p,xfirst;
if (lookup.autoAlpha || lookup.alpha) {
copy = {};
for (p in lookup) {//copy the lookup so that we're not changing the original which may be passed elsewhere.
copy[p] = lookup[p];
}
copy.opacity = 1;
if (copy.autoAlpha) {
copy.visibility = 1;
}
}
if (lookup.className && (pt = this._classNamePT)) {//for className tweens, we need to kill any associated CSSPropTweens too; a linked list starts at the className's "xfirst".
xfirst = pt.xfirst;
if (xfirst && xfirst._prev) {
this._linkCSSP(xfirst._prev, pt._next, xfirst._prev._prev); //break off the prev
} else if (xfirst === this._firstPT) {
this._firstPT = pt._next;
}
if (pt._next) {
this._linkCSSP(pt._next, pt._next._next, xfirst._prev);
}
this._classNamePT = null;
}
pt = this._firstPT;
while (pt) {
if (pt.plugin && pt.plugin !== p && pt.plugin._kill) {//for plugins that are registered with CSSPlugin, we should notify them of the kill.
pt.plugin._kill(lookup);
p = pt.plugin;
}
pt = pt._next;
}
return TweenPlugin.prototype._kill.call(this, copy);
};
//used by cascadeTo() for gathering all the style properties of each child element into an array for comparison.
var _getChildStyles = function _getChildStyles(e, props, targets) {
var children, i, child, type;
if (e.slice) {
i = e.length;
while (--i > -1) {
_getChildStyles(e[i], props, targets);
}
return;
}
children = e.childNodes;
i = children.length;
while (--i > -1) {
child = children[i];
type = child.type;
if (child.style) {
props.push(_getAllStyles(child));
if (targets) {
targets.push(child);
}
}
if ((type === 1 || type === 9 || type === 11) && child.childNodes.length) {
_getChildStyles(child, props, targets);
}
}
};
/**
* Typically only useful for className tweens that may affect child elements, this method creates a TweenLite
* and then compares the style properties of all the target's child elements at the tween's start and end, and
* if any are different, it also creates tweens for those and returns an array containing ALL of the resulting
* tweens (so that you can easily add() them to a TimelineLite, for example). The reason this functionality is
* wrapped into a separate static method of CSSPlugin instead of being integrated into all regular className tweens
* is because it creates entirely new tweens that may have completely different targets than the original tween,
* so if they were all lumped into the original tween instance, it would be inconsistent with the rest of the API
* and it would create other problems. For example:
* - If I create a tween of elementA, that tween instance may suddenly change its target to include 50 other elements (unintuitive if I specifically defined the target I wanted)
* - We can't just create new independent tweens because otherwise, what happens if the original/parent tween is reversed or pause or dropped into a TimelineLite for tight control? You'd expect that tween's behavior to affect all the others.
* - Analyzing every style property of every child before and after the tween is an expensive operation when there are many children, so this behavior shouldn't be imposed on all className tweens by default, especially since it's probably rare that this extra functionality is needed.
*
* @param {Object} target object to be tweened
* @param {number} Duration in seconds (or frames for frames-based tweens)
* @param {Object} Object containing the end values, like {className:"newClass", ease:Linear.easeNone}
* @return {Array} An array of TweenLite instances
*/
CSSPlugin.cascadeTo = function (target, duration, vars) {
var tween = TweenLite.to(target, duration, vars),
results = [tween],
b = [],
e = [],
targets = [],
_reservedProps = TweenLite._internals.reservedProps,
i,difs,p,from;
target = tween._targets || tween.target;
_getChildStyles(target, b, targets);
tween.render(duration, true, true);
_getChildStyles(target, e);
tween.render(0, true, true);
tween._enabled(true);
i = targets.length;
while (--i > -1) {
difs = _cssDif(targets[i], b[i], e[i]);
if (difs.firstMPT) {
difs = difs.difs;
for (p in vars) {
if (_reservedProps[p]) {
difs[p] = vars[p];
}
}
from = {};
for (p in difs) {
from[p] = b[i][p];
}
results.push(TweenLite.fromTo(targets[i], duration, from, difs));
}
}
return results;
};
TweenPlugin.activate([CSSPlugin]);
return CSSPlugin;
}, true);
/*
* ----------------------------------------------------------------
* RoundPropsPlugin
* ----------------------------------------------------------------
*/
(function () {
var RoundPropsPlugin = _gsScope._gsDefine.plugin({
propName: "roundProps",
version: "1.6.0",
priority: -1,
API: 2,
//called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run.
init: function init(target, value, tween) {
this._tween = tween;
return true;
} }),
_roundLinkedList = function _roundLinkedList(node) {
while (node) {
if (!node.f && !node.blob) {
node.m = Math.round;
}
node = node._next;
}
},
p = RoundPropsPlugin.prototype;
p._onInitAllProps = function () {
var tween = this._tween,
rp = tween.vars.roundProps.join ? tween.vars.roundProps : tween.vars.roundProps.split(","),
i = rp.length,
lookup = {},
rpt = tween._propLookup.roundProps,
prop,pt,next;
while (--i > -1) {
lookup[rp[i]] = Math.round;
}
i = rp.length;
while (--i > -1) {
prop = rp[i];
pt = tween._firstPT;
while (pt) {
next = pt._next; //record here, because it may get removed
if (pt.pg) {
pt.t._mod(lookup);
} else if (pt.n === prop) {
if (pt.f === 2 && pt.t) {//a blob (text containing multiple numeric values)
_roundLinkedList(pt.t._firstPT);
} else {
this._add(pt.t, prop, pt.s, pt.c);
//remove from linked list
if (next) {
next._prev = pt._prev;
}
if (pt._prev) {
pt._prev._next = next;
} else if (tween._firstPT === pt) {
tween._firstPT = next;
}
pt._next = pt._prev = null;
tween._propLookup[prop] = rpt;
}
}
pt = next;
}
}
return false;
};
p._add = function (target, p, s, c) {
this._addTween(target, p, s, s + c, p, Math.round);
this._overwriteProps.push(p);
};
})();
/*
* ----------------------------------------------------------------
* AttrPlugin
* ----------------------------------------------------------------
*/
(function () {
_gsScope._gsDefine.plugin({
propName: "attr",
API: 2,
version: "0.6.1",
//called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run.
init: function init(target, value, tween, index) {
var p, end;
if (typeof target.setAttribute !== "function") {
return false;
}
for (p in value) {
end = value[p];
if (typeof end === "function") {
end = end(index, target);
}
this._addTween(target, "setAttribute", target.getAttribute(p) + "", end + "", p, false, p);
this._overwriteProps.push(p);
}
return true;
} });
})();
/*
* ----------------------------------------------------------------
* DirectionalRotationPlugin
* ----------------------------------------------------------------
*/
_gsScope._gsDefine.plugin({
propName: "directionalRotation",
version: "0.3.1",
API: 2,
//called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run.
init: function init(target, value, tween, index) {
if ((typeof value === "undefined" ? "undefined" : _typeof(value)) !== "object") {
value = { rotation: value };
}
this.finals = {};
var cap = value.useRadians === true ? Math.PI * 2 : 360,
min = 0.000001,
p,v,start,end,dif,split;
for (p in value) {
if (p !== "useRadians") {
end = value[p];
if (typeof end === "function") {
end = end(index, target);
}
split = (end + "").split("_");
v = split[0];
start = parseFloat(typeof target[p] !== "function" ? target[p] : target[p.indexOf("set") || typeof target["get" + p.substr(3)] !== "function" ? p : "get" + p.substr(3)]());
end = this.finals[p] = typeof v === "string" && v.charAt(1) === "=" ? start + parseInt(v.charAt(0) + "1", 10) * Number(v.substr(2)) : Number(v) || 0;
dif = end - start;
if (split.length) {
v = split.join("_");
if (v.indexOf("short") !== -1) {
dif = dif % cap;
if (dif !== dif % (cap / 2)) {
dif = dif < 0 ? dif + cap : dif - cap;
}
}
if (v.indexOf("_cw") !== -1 && dif < 0) {
dif = (dif + cap * 9999999999) % cap - (dif / cap | 0) * cap;
} else if (v.indexOf("ccw") !== -1 && dif > 0) {
dif = (dif - cap * 9999999999) % cap - (dif / cap | 0) * cap;
}
}
if (dif > min || dif < -min) {
this._addTween(target, p, start, start + dif, p);
this._overwriteProps.push(p);
}
}
}
return true;
},
//called each time the values should be updated, and the ratio gets passed as the only parameter (typically it's a value between 0 and 1, but it can exceed those when using an ease like Elastic.easeOut or Back.easeOut, etc.)
set: function set(ratio) {
var pt;
if (ratio !== 1) {
this._super.setRatio.call(this, ratio);
} else {
pt = this._firstPT;
while (pt) {
if (pt.f) {
pt.t[pt.p](this.finals[pt.p]);
} else {
pt.t[pt.p] = this.finals[pt.p];
}
pt = pt._next;
}
}
} }).
_autoCSS = true;
/*
* ----------------------------------------------------------------
* EasePack
* ----------------------------------------------------------------
*/
_gsScope._gsDefine("easing.Back", ["easing.Ease"], function (Ease) {
var w = _gsScope.GreenSockGlobals || _gsScope,
gs = w.com.greensock,
_2PI = Math.PI * 2,
_HALF_PI = Math.PI / 2,
_class = gs._class,
_create = function _create(n, f) {
var C = _class("easing." + n, function () {}, true),
p = C.prototype = new Ease();
p.constructor = C;
p.getRatio = f;
return C;
},
_easeReg = Ease.register || function () {}, //put an empty function in place just as a safety measure in case someone loads an OLD version of TweenLite.js where Ease.register doesn't exist.
_wrap = function _wrap(name, EaseOut, EaseIn, EaseInOut, aliases) {
var C = _class("easing." + name, {
easeOut: new EaseOut(),
easeIn: new EaseIn(),
easeInOut: new EaseInOut() },
true);
_easeReg(C, name);
return C;
},
EasePoint = function EasePoint(time, value, next) {
this.t = time;
this.v = value;
if (next) {
this.next = next;
next.prev = this;
this.c = next.v - value;
this.gap = next.t - time;
}
},
//Back
_createBack = function _createBack(n, f) {
var C = _class("easing." + n, function (overshoot) {
this._p1 = overshoot || overshoot === 0 ? overshoot : 1.70158;
this._p2 = this._p1 * 1.525;
}, true),
p = C.prototype = new Ease();
p.constructor = C;
p.getRatio = f;
p.config = function (overshoot) {
return new C(overshoot);
};
return C;
},
Back = _wrap("Back",
_createBack("BackOut", function (p) {
return (p = p - 1) * p * ((this._p1 + 1) * p + this._p1) + 1;
}),
_createBack("BackIn", function (p) {
return p * p * ((this._p1 + 1) * p - this._p1);
}),
_createBack("BackInOut", function (p) {
return (p *= 2) < 1 ? 0.5 * p * p * ((this._p2 + 1) * p - this._p2) : 0.5 * ((p -= 2) * p * ((this._p2 + 1) * p + this._p2) + 2);
})),
//SlowMo
SlowMo = _class("easing.SlowMo", function (linearRatio, power, yoyoMode) {
power = power || power === 0 ? power : 0.7;
if (linearRatio == null) {
linearRatio = 0.7;
} else if (linearRatio > 1) {
linearRatio = 1;
}
this._p = linearRatio !== 1 ? power : 0;
this._p1 = (1 - linearRatio) / 2;
this._p2 = linearRatio;
this._p3 = this._p1 + this._p2;
this._calcEnd = yoyoMode === true;
}, true),
p = SlowMo.prototype = new Ease(),
SteppedEase,ExpoScaleEase,RoughEase,_createElastic;
p.constructor = SlowMo;
p.getRatio = function (p) {
var r = p + (0.5 - p) * this._p;
if (p < this._p1) {
return this._calcEnd ? 1 - (p = 1 - p / this._p1) * p : r - (p = 1 - p / this._p1) * p * p * p * r;
} else if (p > this._p3) {
return this._calcEnd ? p === 1 ? 0 : 1 - (p = (p - this._p3) / this._p1) * p : r + (p - r) * (p = (p - this._p3) / this._p1) * p * p * p; //added p === 1 ? 0 to avoid floating point rounding errors from affecting the final value, like 1 - 0.7 = 0.30000000000000004 instead of 0.3
}
return this._calcEnd ? 1 : r;
};
SlowMo.ease = new SlowMo(0.7, 0.7);
p.config = SlowMo.config = function (linearRatio, power, yoyoMode) {
return new SlowMo(linearRatio, power, yoyoMode);
};
//SteppedEase
SteppedEase = _class("easing.SteppedEase", function (steps, immediateStart) {
steps = steps || 1;
this._p1 = 1 / steps;
this._p2 = steps + (immediateStart ? 0 : 1);
this._p3 = immediateStart ? 1 : 0;
}, true);
p = SteppedEase.prototype = new Ease();
p.constructor = SteppedEase;
p.getRatio = function (p) {
if (p < 0) {
p = 0;
} else if (p >= 1) {
p = 0.999999999;
}
return ((this._p2 * p | 0) + this._p3) * this._p1;
};
p.config = SteppedEase.config = function (steps, immediateStart) {
return new SteppedEase(steps, immediateStart);
};
//ExpoScaleEase
ExpoScaleEase = _class("easing.ExpoScaleEase", function (start, end, ease) {
this._p1 = Math.log(end / start);
this._p2 = end - start;
this._p3 = start;
this._ease = ease;
}, true);
p = ExpoScaleEase.prototype = new Ease();
p.constructor = ExpoScaleEase;
p.getRatio = function (p) {
if (this._ease) {
p = this._ease.getRatio(p);
}
return (this._p3 * Math.exp(this._p1 * p) - this._p3) / this._p2;
};
p.config = ExpoScaleEase.config = function (start, end, ease) {
return new ExpoScaleEase(start, end, ease);
};
//RoughEase
RoughEase = _class("easing.RoughEase", function (vars) {
vars = vars || {};
var taper = vars.taper || "none",
a = [],
cnt = 0,
points = (vars.points || 20) | 0,
i = points,
randomize = vars.randomize !== false,
clamp = vars.clamp === true,
template = vars.template instanceof Ease ? vars.template : null,
strength = typeof vars.strength === "number" ? vars.strength * 0.4 : 0.4,
x,y,bump,invX,obj,pnt;
while (--i > -1) {
x = randomize ? Math.random() : 1 / points * i;
y = template ? template.getRatio(x) : x;
if (taper === "none") {
bump = strength;
} else if (taper === "out") {
invX = 1 - x;
bump = invX * invX * strength;
} else if (taper === "in") {
bump = x * x * strength;
} else if (x < 0.5) {//"both" (start)
invX = x * 2;
bump = invX * invX * 0.5 * strength;
} else {//"both" (end)
invX = (1 - x) * 2;
bump = invX * invX * 0.5 * strength;
}
if (randomize) {
y += Math.random() * bump - bump * 0.5;
} else if (i % 2) {
y += bump * 0.5;
} else {
y -= bump * 0.5;
}
if (clamp) {
if (y > 1) {
y = 1;
} else if (y < 0) {
y = 0;
}
}
a[cnt++] = { x: x, y: y };
}
a.sort(function (a, b) {
return a.x - b.x;
});
pnt = new EasePoint(1, 1, null);
i = points;
while (--i > -1) {
obj = a[i];
pnt = new EasePoint(obj.x, obj.y, pnt);
}
this._prev = new EasePoint(0, 0, pnt.t !== 0 ? pnt : pnt.next);
}, true);
p = RoughEase.prototype = new Ease();
p.constructor = RoughEase;
p.getRatio = function (p) {
var pnt = this._prev;
if (p > pnt.t) {
while (pnt.next && p >= pnt.t) {
pnt = pnt.next;
}
pnt = pnt.prev;
} else {
while (pnt.prev && p <= pnt.t) {
pnt = pnt.prev;
}
}
this._prev = pnt;
return pnt.v + (p - pnt.t) / pnt.gap * pnt.c;
};
p.config = function (vars) {
return new RoughEase(vars);
};
RoughEase.ease = new RoughEase();
//Bounce
_wrap("Bounce",
_create("BounceOut", function (p) {
if (p < 1 / 2.75) {
return 7.5625 * p * p;
} else if (p < 2 / 2.75) {
return 7.5625 * (p -= 1.5 / 2.75) * p + 0.75;
} else if (p < 2.5 / 2.75) {
return 7.5625 * (p -= 2.25 / 2.75) * p + 0.9375;
}
return 7.5625 * (p -= 2.625 / 2.75) * p + 0.984375;
}),
_create("BounceIn", function (p) {
if ((p = 1 - p) < 1 / 2.75) {
return 1 - 7.5625 * p * p;
} else if (p < 2 / 2.75) {
return 1 - (7.5625 * (p -= 1.5 / 2.75) * p + 0.75);
} else if (p < 2.5 / 2.75) {
return 1 - (7.5625 * (p -= 2.25 / 2.75) * p + 0.9375);
}
return 1 - (7.5625 * (p -= 2.625 / 2.75) * p + 0.984375);
}),
_create("BounceInOut", function (p) {
var invert = p < 0.5;
if (invert) {
p = 1 - p * 2;
} else {
p = p * 2 - 1;
}
if (p < 1 / 2.75) {
p = 7.5625 * p * p;
} else if (p < 2 / 2.75) {
p = 7.5625 * (p -= 1.5 / 2.75) * p + 0.75;
} else if (p < 2.5 / 2.75) {
p = 7.5625 * (p -= 2.25 / 2.75) * p + 0.9375;
} else {
p = 7.5625 * (p -= 2.625 / 2.75) * p + 0.984375;
}
return invert ? (1 - p) * 0.5 : p * 0.5 + 0.5;
}));
//CIRC
_wrap("Circ",
_create("CircOut", function (p) {
return Math.sqrt(1 - (p = p - 1) * p);
}),
_create("CircIn", function (p) {
return -(Math.sqrt(1 - p * p) - 1);
}),
_create("CircInOut", function (p) {
return (p *= 2) < 1 ? -0.5 * (Math.sqrt(1 - p * p) - 1) : 0.5 * (Math.sqrt(1 - (p -= 2) * p) + 1);
}));
//Elastic
_createElastic = function _createElastic(n, f, def) {
var C = _class("easing." + n, function (amplitude, period) {
this._p1 = amplitude >= 1 ? amplitude : 1; //note: if amplitude is < 1, we simply adjust the period for a more natural feel. Otherwise the math doesn't work right and the curve starts at 1.
this._p2 = (period || def) / (amplitude < 1 ? amplitude : 1);
this._p3 = this._p2 / _2PI * (Math.asin(1 / this._p1) || 0);
this._p2 = _2PI / this._p2; //precalculate to optimize
}, true),
p = C.prototype = new Ease();
p.constructor = C;
p.getRatio = f;
p.config = function (amplitude, period) {
return new C(amplitude, period);
};
return C;
};
_wrap("Elastic",
_createElastic("ElasticOut", function (p) {
return this._p1 * Math.pow(2, -10 * p) * Math.sin((p - this._p3) * this._p2) + 1;
}, 0.3),
_createElastic("ElasticIn", function (p) {
return -(this._p1 * Math.pow(2, 10 * (p -= 1)) * Math.sin((p - this._p3) * this._p2));
}, 0.3),
_createElastic("ElasticInOut", function (p) {
return (p *= 2) < 1 ? -0.5 * (this._p1 * Math.pow(2, 10 * (p -= 1)) * Math.sin((p - this._p3) * this._p2)) : this._p1 * Math.pow(2, -10 * (p -= 1)) * Math.sin((p - this._p3) * this._p2) * 0.5 + 1;
}, 0.45));
//Expo
_wrap("Expo",
_create("ExpoOut", function (p) {
return 1 - Math.pow(2, -10 * p);
}),
_create("ExpoIn", function (p) {
return Math.pow(2, 10 * (p - 1)) - 0.001;
}),
_create("ExpoInOut", function (p) {
return (p *= 2) < 1 ? 0.5 * Math.pow(2, 10 * (p - 1)) : 0.5 * (2 - Math.pow(2, -10 * (p - 1)));
}));
//Sine
_wrap("Sine",
_create("SineOut", function (p) {
return Math.sin(p * _HALF_PI);
}),
_create("SineIn", function (p) {
return -Math.cos(p * _HALF_PI) + 1;
}),
_create("SineInOut", function (p) {
return -0.5 * (Math.cos(Math.PI * p) - 1);
}));
_class("easing.EaseLookup", {
find: function find(s) {
return Ease.map[s];
} },
true);
//register the non-standard eases
_easeReg(w.SlowMo, "SlowMo", "ease,");
_easeReg(RoughEase, "RoughEase", "ease,");
_easeReg(SteppedEase, "SteppedEase", "ease,");
return Back;
}, true);
});
if (_gsScope._gsDefine) {_gsScope._gsQueue.pop()();} //necessary in case TweenLite was already loaded separately.
/*
* ----------------------------------------------------------------
* Base classes like TweenLite, SimpleTimeline, Ease, Ticker, etc.
* ----------------------------------------------------------------
*/
(function (window, moduleName) {
"use strict";
var _exports = {},
_doc = window.document,
_globals = window.GreenSockGlobals = window.GreenSockGlobals || window;
if (_globals.TweenLite) {
return; //in case the core set of classes is already loaded, don't instantiate twice.
}
var _namespace = function _namespace(ns) {
var a = ns.split("."),
p = _globals,i;
for (i = 0; i < a.length; i++) {
p[a[i]] = p = p[a[i]] || {};
}
return p;
},
gs = _namespace("com.greensock"),
_tinyNum = 0.0000000001,
_slice = function _slice(a) {//don't use Array.prototype.slice.call(target, 0) because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll()
var b = [],
l = a.length,
i;
for (i = 0; i !== l; b.push(a[i++])) {}
return b;
},
_emptyFunc = function _emptyFunc() {},
_isArray = function () {//works around issues in iframe environments where the Array global isn't shared, thus if the object originates in a different window/iframe, "(obj instanceof Array)" will evaluate false. We added some speed optimizations to avoid Object.prototype.toString.call() unless it's absolutely necessary because it's VERY slow (like 20x slower)
var toString = Object.prototype.toString,
array = toString.call([]);
return function (obj) {
return obj != null && (obj instanceof Array || (typeof obj === "undefined" ? "undefined" : _typeof(obj)) === "object" && !!obj.push && toString.call(obj) === array);
};
}(),
a,i,p,_ticker,_tickerActive,
_defLookup = {},
/**
* @constructor
* Defines a GreenSock class, optionally with an array of dependencies that must be instantiated first and passed into the definition.
* This allows users to load GreenSock JS files in any order even if they have interdependencies (like CSSPlugin extends TweenPlugin which is
* inside TweenLite.js, but if CSSPlugin is loaded first, it should wait to run its code until TweenLite.js loads and instantiates TweenPlugin
* and then pass TweenPlugin to CSSPlugin's definition). This is all done automatically and internally.
*
* Every definition will be added to a "com.greensock" global object (typically window, but if a window.GreenSockGlobals object is found,
* it will go there as of v1.7). For example, TweenLite will be found at window.com.greensock.TweenLite and since it's a global class that should be available anywhere,
* it is ALSO referenced at window.TweenLite. However some classes aren't considered global, like the base com.greensock.core.Animation class, so
* those will only be at the package like window.com.greensock.core.Animation. Again, if you define a GreenSockGlobals object on the window, everything
* gets tucked neatly inside there instead of on the window directly. This allows you to do advanced things like load multiple versions of GreenSock
* files and put them into distinct objects (imagine a banner ad uses a newer version but the main site uses an older one). In that case, you could
* sandbox the banner one like:
*
* <script>
* var gs = window.GreenSockGlobals = {}; //the newer version we're about to load could now be referenced in a "gs" object, like gs.TweenLite.to(...). Use whatever alias you want as long as it's unique, "gs" or "banner" or whatever.
* </script>
* <script src="js/greensock/v1.7/TweenMax.js"></script>
* <script>
* window.GreenSockGlobals = window._gsQueue = window._gsDefine = null; //reset it back to null (along with the special _gsQueue variable) so that the next load of TweenMax affects the window and we can reference things directly like TweenLite.to(...)
* </script>
* <script src="js/greensock/v1.6/TweenMax.js"></script>
* <script>
* gs.TweenLite.to(...); //would use v1.7
* TweenLite.to(...); //would use v1.6
* </script>
*
* @param {!string} ns The namespace of the class definition, leaving off "com.greensock." as that's assumed. For example, "TweenLite" or "plugins.CSSPlugin" or "easing.Back".
* @param {!Array.<string>} dependencies An array of dependencies (described as their namespaces minus "com.greensock." prefix). For example ["TweenLite","plugins.TweenPlugin","core.Animation"]
* @param {!function():Object} func The function that should be called and passed the resolved dependencies which will return the actual class for this definition.
* @param {boolean=} global If true, the class will be added to the global scope (typically window unless you define a window.GreenSockGlobals object)
*/
Definition = function Definition(ns, dependencies, func, global) {
this.sc = _defLookup[ns] ? _defLookup[ns].sc : []; //subclasses
_defLookup[ns] = this;
this.gsClass = null;
this.func = func;
var _classes = [];
this.check = function (init) {
var i = dependencies.length,
missing = i,
cur,a,n,cl;
while (--i > -1) {
if ((cur = _defLookup[dependencies[i]] || new Definition(dependencies[i], [])).gsClass) {
_classes[i] = cur.gsClass;
missing--;
} else if (init) {
cur.sc.push(this);
}
}
if (missing === 0 && func) {
a = ("com.greensock." + ns).split(".");
n = a.pop();
cl = _namespace(a.join("."))[n] = this.gsClass = func.apply(func, _classes);
//exports to multiple environments
if (global) {
_globals[n] = _exports[n] = cl; //provides a way to avoid global namespace pollution. By default, the main classes like TweenLite, Power1, Strong, etc. are added to window unless a GreenSockGlobals is defined. So if you want to have things added to a custom object instead, just do something like window.GreenSockGlobals = {} before loading any GreenSock files. You can even set up an alias like window.GreenSockGlobals = windows.gs = {} so that you can access everything like gs.TweenLite. Also remember that ALL classes are added to the window.com.greensock object (in their respective packages, like com.greensock.easing.Power1, com.greensock.TweenLite, etc.)
if (typeof module !== "undefined" && module.exports) {//node
if (ns === moduleName) {
module.exports = _exports[moduleName] = cl;
for (i in _exports) {
cl[i] = _exports[i];
}
} else if (_exports[moduleName]) {
_exports[moduleName][n] = cl;
}
} else if (true) {//AMD
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {return cl;}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
}
for (i = 0; i < this.sc.length; i++) {
this.sc[i].check();
}
}
};
this.check(true);
},
//used to create Definition instances (which basically registers a class that has dependencies).
_gsDefine = window._gsDefine = function (ns, dependencies, func, global) {
return new Definition(ns, dependencies, func, global);
},
//a quick way to create a class that doesn't have any dependencies. Returns the class, but first registers it in the GreenSock namespace so that other classes can grab it (other classes might be dependent on the class).
_class = gs._class = function (ns, func, global) {
func = func || function () {};
_gsDefine(ns, [], function () {return func;}, global);
return func;
};
_gsDefine.globals = _globals;
/*
* ----------------------------------------------------------------
* Ease
* ----------------------------------------------------------------
*/
var _baseParams = [0, 0, 1, 1],
Ease = _class("easing.Ease", function (func, extraParams, type, power) {
this._func = func;
this._type = type || 0;
this._power = power || 0;
this._params = extraParams ? _baseParams.concat(extraParams) : _baseParams;
}, true),
_easeMap = Ease.map = {},
_easeReg = Ease.register = function (ease, names, types, create) {
var na = names.split(","),
i = na.length,
ta = (types || "easeIn,easeOut,easeInOut").split(","),
e,name,j,type;
while (--i > -1) {
name = na[i];
e = create ? _class("easing." + name, null, true) : gs.easing[name] || {};
j = ta.length;
while (--j > -1) {
type = ta[j];
_easeMap[name + "." + type] = _easeMap[type + name] = e[type] = ease.getRatio ? ease : ease[type] || new ease();
}
}
};
p = Ease.prototype;
p._calcEnd = false;
p.getRatio = function (p) {
if (this._func) {
this._params[0] = p;
return this._func.apply(null, this._params);
}
var t = this._type,
pw = this._power,
r = t === 1 ? 1 - p : t === 2 ? p : p < 0.5 ? p * 2 : (1 - p) * 2;
if (pw === 1) {
r *= r;
} else if (pw === 2) {
r *= r * r;
} else if (pw === 3) {
r *= r * r * r;
} else if (pw === 4) {
r *= r * r * r * r;
}
return t === 1 ? 1 - r : t === 2 ? r : p < 0.5 ? r / 2 : 1 - r / 2;
};
//create all the standard eases like Linear, Quad, Cubic, Quart, Quint, Strong, Power0, Power1, Power2, Power3, and Power4 (each with easeIn, easeOut, and easeInOut)
a = ["Linear", "Quad", "Cubic", "Quart", "Quint,Strong"];
i = a.length;
while (--i > -1) {
p = a[i] + ",Power" + i;
_easeReg(new Ease(null, null, 1, i), p, "easeOut", true);
_easeReg(new Ease(null, null, 2, i), p, "easeIn" + (i === 0 ? ",easeNone" : ""));
_easeReg(new Ease(null, null, 3, i), p, "easeInOut");
}
_easeMap.linear = gs.easing.Linear.easeIn;
_easeMap.swing = gs.easing.Quad.easeInOut; //for jQuery folks
/*
* ----------------------------------------------------------------
* EventDispatcher
* ----------------------------------------------------------------
*/
var EventDispatcher = _class("events.EventDispatcher", function (target) {
this._listeners = {};
this._eventTarget = target || this;
});
p = EventDispatcher.prototype;
p.addEventListener = function (type, callback, scope, useParam, priority) {
priority = priority || 0;
var list = this._listeners[type],
index = 0,
listener,i;
if (this === _ticker && !_tickerActive) {
_ticker.wake();
}
if (list == null) {
this._listeners[type] = list = [];
}
i = list.length;
while (--i > -1) {
listener = list[i];
if (listener.c === callback && listener.s === scope) {
list.splice(i, 1);
} else if (index === 0 && listener.pr < priority) {
index = i + 1;
}
}
list.splice(index, 0, { c: callback, s: scope, up: useParam, pr: priority });
};
p.removeEventListener = function (type, callback) {
var list = this._listeners[type],i;
if (list) {
i = list.length;
while (--i > -1) {
if (list[i].c === callback) {
list.splice(i, 1);
return;
}
}
}
};
p.dispatchEvent = function (type) {
var list = this._listeners[type],
i,t,listener;
if (list) {
i = list.length;
if (i > 1) {
list = list.slice(0); //in case addEventListener() is called from within a listener/callback (otherwise the index could change, resulting in a skip)
}
t = this._eventTarget;
while (--i > -1) {
listener = list[i];
if (listener) {
if (listener.up) {
listener.c.call(listener.s || t, { type: type, target: t });
} else {
listener.c.call(listener.s || t);
}
}
}
}
};
/*
* ----------------------------------------------------------------
* Ticker
* ----------------------------------------------------------------
*/
var _reqAnimFrame = window.requestAnimationFrame,
_cancelAnimFrame = window.cancelAnimationFrame,
_getTime = Date.now || function () {return new Date().getTime();},
_lastUpdate = _getTime();
//now try to determine the requestAnimationFrame and cancelAnimationFrame functions and if none are found, we'll use a setTimeout()/clearTimeout() polyfill.
a = ["ms", "moz", "webkit", "o"];
i = a.length;
while (--i > -1 && !_reqAnimFrame) {
_reqAnimFrame = window[a[i] + "RequestAnimationFrame"];
_cancelAnimFrame = window[a[i] + "CancelAnimationFrame"] || window[a[i] + "CancelRequestAnimationFrame"];
}
_class("Ticker", function (fps, useRAF) {
var _self = this,
_startTime = _getTime(),
_useRAF = useRAF !== false && _reqAnimFrame ? "auto" : false,
_lagThreshold = 500,
_adjustedLag = 33,
_tickWord = "tick", //helps reduce gc burden
_fps,_req,_id,_gap,_nextTime,
_tick = function _tick(manual) {
var elapsed = _getTime() - _lastUpdate,
overlap,dispatch;
if (elapsed > _lagThreshold) {
_startTime += elapsed - _adjustedLag;
}
_lastUpdate += elapsed;
_self.time = (_lastUpdate - _startTime) / 1000;
overlap = _self.time - _nextTime;
if (!_fps || overlap > 0 || manual === true) {
_self.frame++;
_nextTime += overlap + (overlap >= _gap ? 0.004 : _gap - overlap);
dispatch = true;
}
if (manual !== true) {//make sure the request is made before we dispatch the "tick" event so that timing is maintained. Otherwise, if processing the "tick" requires a bunch of time (like 15ms) and we're using a setTimeout() that's based on 16.7ms, it'd technically take 31.7ms between frames otherwise.
_id = _req(_tick);
}
if (dispatch) {
_self.dispatchEvent(_tickWord);
}
};
EventDispatcher.call(_self);
_self.time = _self.frame = 0;
_self.tick = function () {
_tick(true);
};
_self.lagSmoothing = function (threshold, adjustedLag) {
if (!arguments.length) {//if lagSmoothing() is called with no arguments, treat it like a getter that returns a boolean indicating if it's enabled or not. This is purposely undocumented and is for internal use.
return _lagThreshold < 1 / _tinyNum;
}
_lagThreshold = threshold || 1 / _tinyNum; //zero should be interpreted as basically unlimited
_adjustedLag = Math.min(adjustedLag, _lagThreshold, 0);
};
_self.sleep = function () {
if (_id == null) {
return;
}
if (!_useRAF || !_cancelAnimFrame) {
clearTimeout(_id);
} else {
_cancelAnimFrame(_id);
}
_req = _emptyFunc;
_id = null;
if (_self === _ticker) {
_tickerActive = false;
}
};
_self.wake = function (seamless) {
if (_id !== null) {
_self.sleep();
} else if (seamless) {
_startTime += -_lastUpdate + (_lastUpdate = _getTime());
} else if (_self.frame > 10) {//don't trigger lagSmoothing if we're just waking up, and make sure that at least 10 frames have elapsed because of the iOS bug that we work around below with the 1.5-second setTimout().
_lastUpdate = _getTime() - _lagThreshold + 5;
}
_req = _fps === 0 ? _emptyFunc : !_useRAF || !_reqAnimFrame ? function (f) {return setTimeout(f, (_nextTime - _self.time) * 1000 + 1 | 0);} : _reqAnimFrame;
if (_self === _ticker) {
_tickerActive = true;
}
_tick(2);
};
_self.fps = function (value) {
if (!arguments.length) {
return _fps;
}
_fps = value;
_gap = 1 / (_fps || 60);
_nextTime = this.time + _gap;
_self.wake();
};
_self.useRAF = function (value) {
if (!arguments.length) {
return _useRAF;
}
_self.sleep();
_useRAF = value;
_self.fps(_fps);
};
_self.fps(fps);
//a bug in iOS 6 Safari occasionally prevents the requestAnimationFrame from working initially, so we use a 1.5-second timeout that automatically falls back to setTimeout() if it senses this condition.
setTimeout(function () {
if (_useRAF === "auto" && _self.frame < 5 && (_doc || {}).visibilityState !== "hidden") {
_self.useRAF(false);
}
}, 1500);
});
p = gs.Ticker.prototype = new gs.events.EventDispatcher();
p.constructor = gs.Ticker;
/*
* ----------------------------------------------------------------
* Animation
* ----------------------------------------------------------------
*/
var Animation = _class("core.Animation", function (duration, vars) {
this.vars = vars = vars || {};
this._duration = this._totalDuration = duration || 0;
this._delay = Number(vars.delay) || 0;
this._timeScale = 1;
this._active = vars.immediateRender === true;
this.data = vars.data;
this._reversed = vars.reversed === true;
if (!_rootTimeline) {
return;
}
if (!_tickerActive) {//some browsers (like iOS 6 Safari) shut down JavaScript execution when the tab is disabled and they [occasionally] neglect to start up requestAnimationFrame again when returning - this code ensures that the engine starts up again properly.
_ticker.wake();
}
var tl = this.vars.useFrames ? _rootFramesTimeline : _rootTimeline;
tl.add(this, tl._time);
if (this.vars.paused) {
this.paused(true);
}
});
_ticker = Animation.ticker = new gs.Ticker();
p = Animation.prototype;
p._dirty = p._gc = p._initted = p._paused = false;
p._totalTime = p._time = 0;
p._rawPrevTime = -1;
p._next = p._last = p._onUpdate = p._timeline = p.timeline = null;
p._paused = false;
//some browsers (like iOS) occasionally drop the requestAnimationFrame event when the user switches to a different tab and then comes back again, so we use a 2-second setTimeout() to sense if/when that condition occurs and then wake() the ticker.
var _checkTimeout = function _checkTimeout() {
if (_tickerActive && _getTime() - _lastUpdate > 2000 && ((_doc || {}).visibilityState !== "hidden" || !_ticker.lagSmoothing())) {//note: if the tab is hidden, we should still wake if lagSmoothing has been disabled.
_ticker.wake();
}
var t = setTimeout(_checkTimeout, 2000);
if (t.unref) {
// allows a node process to exit even if the timeout’s callback hasn't been invoked. Without it, the node process could hang as this function is called every two seconds.
t.unref();
}
};
_checkTimeout();
p.play = function (from, suppressEvents) {
if (from != null) {
this.seek(from, suppressEvents);
}
return this.reversed(false).paused(false);
};
p.pause = function (atTime, suppressEvents) {
if (atTime != null) {
this.seek(atTime, suppressEvents);
}
return this.paused(true);
};
p.resume = function (from, suppressEvents) {
if (from != null) {
this.seek(from, suppressEvents);
}
return this.paused(false);
};
p.seek = function (time, suppressEvents) {
return this.totalTime(Number(time), suppressEvents !== false);
};
p.restart = function (includeDelay, suppressEvents) {
return this.reversed(false).paused(false).totalTime(includeDelay ? -this._delay : 0, suppressEvents !== false, true);
};
p.reverse = function (from, suppressEvents) {
if (from != null) {
this.seek(from || this.totalDuration(), suppressEvents);
}
return this.reversed(true).paused(false);
};
p.render = function (time, suppressEvents, force) {
//stub - we override this method in subclasses.
};
p.invalidate = function () {
this._time = this._totalTime = 0;
this._initted = this._gc = false;
this._rawPrevTime = -1;
if (this._gc || !this.timeline) {
this._enabled(true);
}
return this;
};
p.isActive = function () {
var tl = this._timeline, //the 2 root timelines won't have a _timeline; they're always active.
startTime = this._startTime,
rawTime;
return !tl || !this._gc && !this._paused && tl.isActive() && (rawTime = tl.rawTime(true)) >= startTime && rawTime < startTime + this.totalDuration() / this._timeScale - 0.0000001;
};
p._enabled = function (enabled, ignoreTimeline) {
if (!_tickerActive) {
_ticker.wake();
}
this._gc = !enabled;
this._active = this.isActive();
if (ignoreTimeline !== true) {
if (enabled && !this.timeline) {
this._timeline.add(this, this._startTime - this._delay);
} else if (!enabled && this.timeline) {
this._timeline._remove(this, true);
}
}
return false;
};
p._kill = function (vars, target) {
return this._enabled(false, false);
};
p.kill = function (vars, target) {
this._kill(vars, target);
return this;
};
p._uncache = function (includeSelf) {
var tween = includeSelf ? this : this.timeline;
while (tween) {
tween._dirty = true;
tween = tween.timeline;
}
return this;
};
p._swapSelfInParams = function (params) {
var i = params.length,
copy = params.concat();
while (--i > -1) {
if (params[i] === "{self}") {
copy[i] = this;
}
}
return copy;
};
p._callback = function (type) {
var v = this.vars,
callback = v[type],
params = v[type + "Params"],
scope = v[type + "Scope"] || v.callbackScope || this,
l = params ? params.length : 0;
switch (l) {//speed optimization; call() is faster than apply() so use it when there are only a few parameters (which is by far most common). Previously we simply did var v = this.vars; v[type].apply(v[type + "Scope"] || v.callbackScope || this, v[type + "Params"] || _blankArray);
case 0:callback.call(scope);break;
case 1:callback.call(scope, params[0]);break;
case 2:callback.call(scope, params[0], params[1]);break;
default:callback.apply(scope, params);}
};
//----Animation getters/setters --------------------------------------------------------
p.eventCallback = function (type, callback, params, scope) {
if ((type || "").substr(0, 2) === "on") {
var v = this.vars;
if (arguments.length === 1) {
return v[type];
}
if (callback == null) {
delete v[type];
} else {
v[type] = callback;
v[type + "Params"] = _isArray(params) && params.join("").indexOf("{self}") !== -1 ? this._swapSelfInParams(params) : params;
v[type + "Scope"] = scope;
}
if (type === "onUpdate") {
this._onUpdate = callback;
}
}
return this;
};
p.delay = function (value) {
if (!arguments.length) {
return this._delay;
}
if (this._timeline.smoothChildTiming) {
this.startTime(this._startTime + value - this._delay);
}
this._delay = value;
return this;
};
p.duration = function (value) {
if (!arguments.length) {
this._dirty = false;
return this._duration;
}
this._duration = this._totalDuration = value;
this._uncache(true); //true in case it's a TweenMax or TimelineMax that has a repeat - we'll need to refresh the totalDuration.
if (this._timeline.smoothChildTiming) if (this._time > 0) if (this._time < this._duration) if (value !== 0) {
this.totalTime(this._totalTime * (value / this._duration), true);
}
return this;
};
p.totalDuration = function (value) {
this._dirty = false;
return !arguments.length ? this._totalDuration : this.duration(value);
};
p.time = function (value, suppressEvents) {
if (!arguments.length) {
return this._time;
}
if (this._dirty) {
this.totalDuration();
}
return this.totalTime(value > this._duration ? this._duration : value, suppressEvents);
};
p.totalTime = function (time, suppressEvents, uncapped) {
if (!_tickerActive) {
_ticker.wake();
}
if (!arguments.length) {
return this._totalTime;
}
if (this._timeline) {
if (time < 0 && !uncapped) {
time += this.totalDuration();
}
if (this._timeline.smoothChildTiming) {
if (this._dirty) {
this.totalDuration();
}
var totalDuration = this._totalDuration,
tl = this._timeline;
if (time > totalDuration && !uncapped) {
time = totalDuration;
}
this._startTime = (this._paused ? this._pauseTime : tl._time) - (!this._reversed ? time : totalDuration - time) / this._timeScale;
if (!tl._dirty) {//for performance improvement. If the parent's cache is already dirty, it already took care of marking the ancestors as dirty too, so skip the function call here.
this._uncache(false);
}
//in case any of the ancestor timelines had completed but should now be enabled, we should reset their totalTime() which will also ensure that they're lined up properly and enabled. Skip for animations that are on the root (wasteful). Example: a TimelineLite.exportRoot() is performed when there's a paused tween on the root, the export will not complete until that tween is unpaused, but imagine a child gets restarted later, after all [unpaused] tweens have completed. The startTime of that child would get pushed out, but one of the ancestors may have completed.
if (tl._timeline) {
while (tl._timeline) {
if (tl._timeline._time !== (tl._startTime + tl._totalTime) / tl._timeScale) {
tl.totalTime(tl._totalTime, true);
}
tl = tl._timeline;
}
}
}
if (this._gc) {
this._enabled(true, false);
}
if (this._totalTime !== time || this._duration === 0) {
if (_lazyTweens.length) {
_lazyRender();
}
this.render(time, suppressEvents, false);
if (_lazyTweens.length) {//in case rendering caused any tweens to lazy-init, we should render them because typically when someone calls seek() or time() or progress(), they expect an immediate render.
_lazyRender();
}
}
}
return this;
};
p.progress = p.totalProgress = function (value, suppressEvents) {
var duration = this.duration();
return !arguments.length ? duration ? this._time / duration : this.ratio : this.totalTime(duration * value, suppressEvents);
};
p.startTime = function (value) {
if (!arguments.length) {
return this._startTime;
}
if (value !== this._startTime) {
this._startTime = value;
if (this.timeline) if (this.timeline._sortChildren) {
this.timeline.add(this, value - this._delay); //ensures that any necessary re-sequencing of Animations in the timeline occurs to make sure the rendering order is correct.
}
}
return this;
};
p.endTime = function (includeRepeats) {
return this._startTime + (includeRepeats != false ? this.totalDuration() : this.duration()) / this._timeScale;
};
p.timeScale = function (value) {
if (!arguments.length) {
return this._timeScale;
}
var pauseTime, t;
value = value || _tinyNum; //can't allow zero because it'll throw the math off
if (this._timeline && this._timeline.smoothChildTiming) {
pauseTime = this._pauseTime;
t = pauseTime || pauseTime === 0 ? pauseTime : this._timeline.totalTime();
this._startTime = t - (t - this._startTime) * this._timeScale / value;
}
this._timeScale = value;
t = this.timeline;
while (t && t.timeline) {//must update the duration/totalDuration of all ancestor timelines immediately in case in the middle of a render loop, one tween alters another tween's timeScale which shoves its startTime before 0, forcing the parent timeline to shift around and shiftChildren() which could affect that next tween's render (startTime). Doesn't matter for the root timeline though.
t._dirty = true;
t.totalDuration();
t = t.timeline;
}
return this;
};
p.reversed = function (value) {
if (!arguments.length) {
return this._reversed;
}
if (value != this._reversed) {
this._reversed = value;
this.totalTime(this._timeline && !this._timeline.smoothChildTiming ? this.totalDuration() - this._totalTime : this._totalTime, true);
}
return this;
};
p.paused = function (value) {
if (!arguments.length) {
return this._paused;
}
var tl = this._timeline,
raw,elapsed;
if (value != this._paused) if (tl) {
if (!_tickerActive && !value) {
_ticker.wake();
}
raw = tl.rawTime();
elapsed = raw - this._pauseTime;
if (!value && tl.smoothChildTiming) {
this._startTime += elapsed;
this._uncache(false);
}
this._pauseTime = value ? raw : null;
this._paused = value;
this._active = this.isActive();
if (!value && elapsed !== 0 && this._initted && this.duration()) {
raw = tl.smoothChildTiming ? this._totalTime : (raw - this._startTime) / this._timeScale;
this.render(raw, raw === this._totalTime, true); //in case the target's properties changed via some other tween or manual update by the user, we should force a render.
}
}
if (this._gc && !value) {
this._enabled(true, false);
}
return this;
};
/*
* ----------------------------------------------------------------
* SimpleTimeline
* ----------------------------------------------------------------
*/
var SimpleTimeline = _class("core.SimpleTimeline", function (vars) {
Animation.call(this, 0, vars);
this.autoRemoveChildren = this.smoothChildTiming = true;
});
p = SimpleTimeline.prototype = new Animation();
p.constructor = SimpleTimeline;
p.kill()._gc = false;
p._first = p._last = p._recent = null;
p._sortChildren = false;
p.add = p.insert = function (child, position, align, stagger) {
var prevTween, st;
child._startTime = Number(position || 0) + child._delay;
if (child._paused) if (this !== child._timeline) {//we only adjust the _pauseTime if it wasn't in this timeline already. Remember, sometimes a tween will be inserted again into the same timeline when its startTime is changed so that the tweens in the TimelineLite/Max are re-ordered properly in the linked list (so everything renders in the proper order).
child._pauseTime = child._startTime + (this.rawTime() - child._startTime) / child._timeScale;
}
if (child.timeline) {
child.timeline._remove(child, true); //removes from existing timeline so that it can be properly added to this one.
}
child.timeline = child._timeline = this;
if (child._gc) {
child._enabled(true, true);
}
prevTween = this._last;
if (this._sortChildren) {
st = child._startTime;
while (prevTween && prevTween._startTime > st) {
prevTween = prevTween._prev;
}
}
if (prevTween) {
child._next = prevTween._next;
prevTween._next = child;
} else {
child._next = this._first;
this._first = child;
}
if (child._next) {
child._next._prev = child;
} else {
this._last = child;
}
child._prev = prevTween;
this._recent = child;
if (this._timeline) {
this._uncache(true);
}
return this;
};
p._remove = function (tween, skipDisable) {
if (tween.timeline === this) {
if (!skipDisable) {
tween._enabled(false, true);
}
if (tween._prev) {
tween._prev._next = tween._next;
} else if (this._first === tween) {
this._first = tween._next;
}
if (tween._next) {
tween._next._prev = tween._prev;
} else if (this._last === tween) {
this._last = tween._prev;
}
tween._next = tween._prev = tween.timeline = null;
if (tween === this._recent) {
this._recent = this._last;
}
if (this._timeline) {
this._uncache(true);
}
}
return this;
};
p.render = function (time, suppressEvents, force) {
var tween = this._first,
next;
this._totalTime = this._time = this._rawPrevTime = time;
while (tween) {
next = tween._next; //record it here because the value could change after rendering...
if (tween._active || time >= tween._startTime && !tween._paused && !tween._gc) {
if (!tween._reversed) {
tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
} else {
tween.render((!tween._dirty ? tween._totalDuration : tween.totalDuration()) - (time - tween._startTime) * tween._timeScale, suppressEvents, force);
}
}
tween = next;
}
};
p.rawTime = function () {
if (!_tickerActive) {
_ticker.wake();
}
return this._totalTime;
};
/*
* ----------------------------------------------------------------
* TweenLite
* ----------------------------------------------------------------
*/
var TweenLite = _class("TweenLite", function (target, duration, vars) {
Animation.call(this, duration, vars);
this.render = TweenLite.prototype.render; //speed optimization (avoid prototype lookup on this "hot" method)
if (target == null) {
throw "Cannot tween a null target.";
}
this.target = target = typeof target !== "string" ? target : TweenLite.selector(target) || target;
var isSelector = target.jquery || target.length && target !== window && target[0] && (target[0] === window || target[0].nodeType && target[0].style && !target.nodeType),
overwrite = this.vars.overwrite,
i,targ,targets;
this._overwrite = overwrite = overwrite == null ? _overwriteLookup[TweenLite.defaultOverwrite] : typeof overwrite === "number" ? overwrite >> 0 : _overwriteLookup[overwrite];
if ((isSelector || target instanceof Array || target.push && _isArray(target)) && typeof target[0] !== "number") {
this._targets = targets = _slice(target); //don't use Array.prototype.slice.call(target, 0) because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll()
this._propLookup = [];
this._siblings = [];
for (i = 0; i < targets.length; i++) {
targ = targets[i];
if (!targ) {
targets.splice(i--, 1);
continue;
} else if (typeof targ === "string") {
targ = targets[i--] = TweenLite.selector(targ); //in case it's an array of strings
if (typeof targ === "string") {
targets.splice(i + 1, 1); //to avoid an endless loop (can't imagine why the selector would return a string, but just in case)
}
continue;
} else if (targ.length && targ !== window && targ[0] && (targ[0] === window || targ[0].nodeType && targ[0].style && !targ.nodeType)) {//in case the user is passing in an array of selector objects (like jQuery objects), we need to check one more level and pull things out if necessary. Also note that <select> elements pass all the criteria regarding length and the first child having style, so we must also check to ensure the target isn't an HTML node itself.
targets.splice(i--, 1);
this._targets = targets = targets.concat(_slice(targ));
continue;
}
this._siblings[i] = _register(targ, this, false);
if (overwrite === 1) if (this._siblings[i].length > 1) {
_applyOverwrite(targ, this, null, 1, this._siblings[i]);
}
}
} else {
this._propLookup = {};
this._siblings = _register(target, this, false);
if (overwrite === 1) if (this._siblings.length > 1) {
_applyOverwrite(target, this, null, 1, this._siblings);
}
}
if (this.vars.immediateRender || duration === 0 && this._delay === 0 && this.vars.immediateRender !== false) {
this._time = -_tinyNum; //forces a render without having to set the render() "force" parameter to true because we want to allow lazying by default (using the "force" parameter always forces an immediate full render)
this.render(Math.min(0, -this._delay)); //in case delay is negative
}
}, true),
_isSelector = function _isSelector(v) {
return v && v.length && v !== window && v[0] && (v[0] === window || v[0].nodeType && v[0].style && !v.nodeType); //we cannot check "nodeType" if the target is window from within an iframe, otherwise it will trigger a security error in some browsers like Firefox.
},
_autoCSS = function _autoCSS(vars, target) {
var css = {},
p;
for (p in vars) {
if (!_reservedProps[p] && (!(p in target) || p === "transform" || p === "x" || p === "y" || p === "width" || p === "height" || p === "className" || p === "border") && (!_plugins[p] || _plugins[p] && _plugins[p]._autoCSS)) {//note: <img> elements contain read-only "x" and "y" properties. We should also prioritize editing css width/height rather than the element's properties.
css[p] = vars[p];
delete vars[p];
}
}
vars.css = css;
};
p = TweenLite.prototype = new Animation();
p.constructor = TweenLite;
p.kill()._gc = false;
//----TweenLite defaults, overwrite management, and root updates ----------------------------------------------------
p.ratio = 0;
p._firstPT = p._targets = p._overwrittenProps = p._startAt = null;
p._notifyPluginsOfEnabled = p._lazy = false;
TweenLite.version = "1.20.4";
TweenLite.defaultEase = p._ease = new Ease(null, null, 1, 1);
TweenLite.defaultOverwrite = "auto";
TweenLite.ticker = _ticker;
TweenLite.autoSleep = 120;
TweenLite.lagSmoothing = function (threshold, adjustedLag) {
_ticker.lagSmoothing(threshold, adjustedLag);
};
TweenLite.selector = window.$ || window.jQuery || function (e) {
var selector = window.$ || window.jQuery;
if (selector) {
TweenLite.selector = selector;
return selector(e);
}
return typeof _doc === "undefined" ? e : _doc.querySelectorAll ? _doc.querySelectorAll(e) : _doc.getElementById(e.charAt(0) === "#" ? e.substr(1) : e);
};
var _lazyTweens = [],
_lazyLookup = {},
_numbersExp = /(?:(-|-=|\+=)?\d*\.?\d*(?:e[\-+]?\d+)?)[0-9]/ig,
_relExp = /[\+-]=-?[\.\d]/,
//_nonNumbersExp = /(?:([\-+](?!(\d|=)))|[^\d\-+=e]|(e(?![\-+][\d])))+/ig,
_setRatio = function _setRatio(v) {
var pt = this._firstPT,
min = 0.000001,
val;
while (pt) {
val = !pt.blob ? pt.c * v + pt.s : v === 1 && this.end != null ? this.end : v ? this.join("") : this.start;
if (pt.m) {
val = pt.m(val, this._target || pt.t);
} else if (val < min) if (val > -min && !pt.blob) {//prevents issues with converting very small numbers to strings in the browser
val = 0;
}
if (!pt.f) {
pt.t[pt.p] = val;
} else if (pt.fp) {
pt.t[pt.p](pt.fp, val);
} else {
pt.t[pt.p](val);
}
pt = pt._next;
}
},
//compares two strings (start/end), finds the numbers that are different and spits back an array representing the whole value but with the changing values isolated as elements. For example, "rgb(0,0,0)" and "rgb(100,50,0)" would become ["rgb(", 0, ",", 50, ",0)"]. Notice it merges the parts that are identical (performance optimization). The array also has a linked list of PropTweens attached starting with _firstPT that contain the tweening data (t, p, s, c, f, etc.). It also stores the starting value as a "start" property so that we can revert to it if/when necessary, like when a tween rewinds fully. If the quantity of numbers differs between the start and end, it will always prioritize the end value(s). The pt parameter is optional - it's for a PropTween that will be appended to the end of the linked list and is typically for actually setting the value after all of the elements have been updated (with array.join("")).
_blobDif = function _blobDif(start, end, filter, pt) {
var a = [],
charIndex = 0,
s = "",
color = 0,
startNums,endNums,num,i,l,nonNumbers,currentNum;
a.start = start;
a.end = end;
start = a[0] = start + ""; //ensure values are strings
end = a[1] = end + "";
if (filter) {
filter(a); //pass an array with the starting and ending values and let the filter do whatever it needs to the values.
start = a[0];
end = a[1];
}
a.length = 0;
startNums = start.match(_numbersExp) || [];
endNums = end.match(_numbersExp) || [];
if (pt) {
pt._next = null;
pt.blob = 1;
a._firstPT = a._applyPT = pt; //apply last in the linked list (which means inserting it first)
}
l = endNums.length;
for (i = 0; i < l; i++) {
currentNum = endNums[i];
nonNumbers = end.substr(charIndex, end.indexOf(currentNum, charIndex) - charIndex);
s += nonNumbers || !i ? nonNumbers : ","; //note: SVG spec allows omission of comma/space when a negative sign is wedged between two numbers, like 2.5-5.3 instead of 2.5,-5.3 but when tweening, the negative value may switch to positive, so we insert the comma just in case.
charIndex += nonNumbers.length;
if (color) {//sense rgba() values and round them.
color = (color + 1) % 5;
} else if (nonNumbers.substr(-5) === "rgba(") {
color = 1;
}
if (currentNum === startNums[i] || startNums.length <= i) {
s += currentNum;
} else {
if (s) {
a.push(s);
s = "";
}
num = parseFloat(startNums[i]);
a.push(num);
a._firstPT = { _next: a._firstPT, t: a, p: a.length - 1, s: num, c: (currentNum.charAt(1) === "=" ? parseInt(currentNum.charAt(0) + "1", 10) * parseFloat(currentNum.substr(2)) : parseFloat(currentNum) - num) || 0, f: 0, m: color && color < 4 ? Math.round : 0 };
//note: we don't set _prev because we'll never need to remove individual PropTweens from this list.
}
charIndex += currentNum.length;
}
s += end.substr(charIndex);
if (s) {
a.push(s);
}
a.setRatio = _setRatio;
if (_relExp.test(end)) {//if the end string contains relative values, delete it so that on the final render (in _setRatio()), we don't actually set it to the string with += or -= characters (forces it to use the calculated value).
a.end = null;
}
return a;
},
//note: "funcParam" is only necessary for function-based getters/setters that require an extra parameter like getAttribute("width") and setAttribute("width", value). In this example, funcParam would be "width". Used by AttrPlugin for example.
_addPropTween = function _addPropTween(target, prop, start, end, overwriteProp, mod, funcParam, stringFilter, index) {
if (typeof end === "function") {
end = end(index || 0, target);
}
var type = _typeof(target[prop]),
getterName = type !== "function" ? "" : prop.indexOf("set") || typeof target["get" + prop.substr(3)] !== "function" ? prop : "get" + prop.substr(3),
s = start !== "get" ? start : !getterName ? target[prop] : funcParam ? target[getterName](funcParam) : target[getterName](),
isRelative = typeof end === "string" && end.charAt(1) === "=",
pt = { t: target, p: prop, s: s, f: type === "function", pg: 0, n: overwriteProp || prop, m: !mod ? 0 : typeof mod === "function" ? mod : Math.round, pr: 0, c: isRelative ? parseInt(end.charAt(0) + "1", 10) * parseFloat(end.substr(2)) : parseFloat(end) - s || 0 },
blob;
if (typeof s !== "number" || typeof end !== "number" && !isRelative) {
if (funcParam || isNaN(s) || !isRelative && isNaN(end) || typeof s === "boolean" || typeof end === "boolean") {
//a blob (string that has multiple numbers in it)
pt.fp = funcParam;
blob = _blobDif(s, isRelative ? parseFloat(pt.s) + pt.c + (pt.s + "").replace(/[0-9\-\.]/g, "") : end, stringFilter || TweenLite.defaultStringFilter, pt);
pt = { t: blob, p: "setRatio", s: 0, c: 1, f: 2, pg: 0, n: overwriteProp || prop, pr: 0, m: 0 }; //"2" indicates it's a Blob property tween. Needed for RoundPropsPlugin for example.
} else {
pt.s = parseFloat(s);
if (!isRelative) {
pt.c = parseFloat(end) - pt.s || 0;
}
}
}
if (pt.c) {//only add it to the linked list if there's a change.
if (pt._next = this._firstPT) {
pt._next._prev = pt;
}
this._firstPT = pt;
return pt;
}
},
_internals = TweenLite._internals = { isArray: _isArray, isSelector: _isSelector, lazyTweens: _lazyTweens, blobDif: _blobDif }, //gives us a way to expose certain private values to other GreenSock classes without contaminating tha main TweenLite object.
_plugins = TweenLite._plugins = {},
_tweenLookup = _internals.tweenLookup = {},
_tweenLookupNum = 0,
_reservedProps = _internals.reservedProps = { ease: 1, delay: 1, overwrite: 1, onComplete: 1, onCompleteParams: 1, onCompleteScope: 1, useFrames: 1, runBackwards: 1, startAt: 1, onUpdate: 1, onUpdateParams: 1, onUpdateScope: 1, onStart: 1, onStartParams: 1, onStartScope: 1, onReverseComplete: 1, onReverseCompleteParams: 1, onReverseCompleteScope: 1, onRepeat: 1, onRepeatParams: 1, onRepeatScope: 1, easeParams: 1, yoyo: 1, immediateRender: 1, repeat: 1, repeatDelay: 1, data: 1, paused: 1, reversed: 1, autoCSS: 1, lazy: 1, onOverwrite: 1, callbackScope: 1, stringFilter: 1, id: 1, yoyoEase: 1 },
_overwriteLookup = { none: 0, all: 1, auto: 2, concurrent: 3, allOnStart: 4, preexisting: 5, "true": 1, "false": 0 },
_rootFramesTimeline = Animation._rootFramesTimeline = new SimpleTimeline(),
_rootTimeline = Animation._rootTimeline = new SimpleTimeline(),
_nextGCFrame = 30,
_lazyRender = _internals.lazyRender = function () {
var i = _lazyTweens.length,
tween;
_lazyLookup = {};
while (--i > -1) {
tween = _lazyTweens[i];
if (tween && tween._lazy !== false) {
tween.render(tween._lazy[0], tween._lazy[1], true);
tween._lazy = false;
}
}
_lazyTweens.length = 0;
};
_rootTimeline._startTime = _ticker.time;
_rootFramesTimeline._startTime = _ticker.frame;
_rootTimeline._active = _rootFramesTimeline._active = true;
setTimeout(_lazyRender, 1); //on some mobile devices, there isn't a "tick" before code runs which means any lazy renders wouldn't run before the next official "tick".
Animation._updateRoot = TweenLite.render = function () {
var i, a, p;
if (_lazyTweens.length) {//if code is run outside of the requestAnimationFrame loop, there may be tweens queued AFTER the engine refreshed, so we need to ensure any pending renders occur before we refresh again.
_lazyRender();
}
_rootTimeline.render((_ticker.time - _rootTimeline._startTime) * _rootTimeline._timeScale, false, false);
_rootFramesTimeline.render((_ticker.frame - _rootFramesTimeline._startTime) * _rootFramesTimeline._timeScale, false, false);
if (_lazyTweens.length) {
_lazyRender();
}
if (_ticker.frame >= _nextGCFrame) {//dump garbage every 120 frames or whatever the user sets TweenLite.autoSleep to
_nextGCFrame = _ticker.frame + (parseInt(TweenLite.autoSleep, 10) || 120);
for (p in _tweenLookup) {
a = _tweenLookup[p].tweens;
i = a.length;
while (--i > -1) {
if (a[i]._gc) {
a.splice(i, 1);
}
}
if (a.length === 0) {
delete _tweenLookup[p];
}
}
//if there are no more tweens in the root timelines, or if they're all paused, make the _timer sleep to reduce load on the CPU slightly
p = _rootTimeline._first;
if (!p || p._paused) if (TweenLite.autoSleep && !_rootFramesTimeline._first && _ticker._listeners.tick.length === 1) {
while (p && p._paused) {
p = p._next;
}
if (!p) {
_ticker.sleep();
}
}
}
};
_ticker.addEventListener("tick", Animation._updateRoot);
var _register = function _register(target, tween, scrub) {
var id = target._gsTweenID,a,i;
if (!_tweenLookup[id || (target._gsTweenID = id = "t" + _tweenLookupNum++)]) {
_tweenLookup[id] = { target: target, tweens: [] };
}
if (tween) {
a = _tweenLookup[id].tweens;
a[i = a.length] = tween;
if (scrub) {
while (--i > -1) {
if (a[i] === tween) {
a.splice(i, 1);
}
}
}
}
return _tweenLookup[id].tweens;
},
_onOverwrite = function _onOverwrite(overwrittenTween, overwritingTween, target, killedProps) {
var func = overwrittenTween.vars.onOverwrite,r1,r2;
if (func) {
r1 = func(overwrittenTween, overwritingTween, target, killedProps);
}
func = TweenLite.onOverwrite;
if (func) {
r2 = func(overwrittenTween, overwritingTween, target, killedProps);
}
return r1 !== false && r2 !== false;
},
_applyOverwrite = function _applyOverwrite(target, tween, props, mode, siblings) {
var i, changed, curTween, l;
if (mode === 1 || mode >= 4) {
l = siblings.length;
for (i = 0; i < l; i++) {
if ((curTween = siblings[i]) !== tween) {
if (!curTween._gc) {
if (curTween._kill(null, target, tween)) {
changed = true;
}
}
} else if (mode === 5) {
break;
}
}
return changed;
}
//NOTE: Add 0.0000000001 to overcome floating point errors that can cause the startTime to be VERY slightly off (when a tween's time() is set for example)
var startTime = tween._startTime + _tinyNum,
overlaps = [],
oCount = 0,
zeroDur = tween._duration === 0,
globalStart;
i = siblings.length;
while (--i > -1) {
if ((curTween = siblings[i]) === tween || curTween._gc || curTween._paused) {
//ignore
} else if (curTween._timeline !== tween._timeline) {
globalStart = globalStart || _checkOverlap(tween, 0, zeroDur);
if (_checkOverlap(curTween, globalStart, zeroDur) === 0) {
overlaps[oCount++] = curTween;
}
} else if (curTween._startTime <= startTime) if (curTween._startTime + curTween.totalDuration() / curTween._timeScale > startTime) if (!((zeroDur || !curTween._initted) && startTime - curTween._startTime <= 0.0000000002)) {
overlaps[oCount++] = curTween;
}
}
i = oCount;
while (--i > -1) {
curTween = overlaps[i];
if (mode === 2) if (curTween._kill(props, target, tween)) {
changed = true;
}
if (mode !== 2 || !curTween._firstPT && curTween._initted) {
if (mode !== 2 && !_onOverwrite(curTween, tween)) {
continue;
}
if (curTween._enabled(false, false)) {//if all property tweens have been overwritten, kill the tween.
changed = true;
}
}
}
return changed;
},
_checkOverlap = function _checkOverlap(tween, reference, zeroDur) {
var tl = tween._timeline,
ts = tl._timeScale,
t = tween._startTime;
while (tl._timeline) {
t += tl._startTime;
ts *= tl._timeScale;
if (tl._paused) {
return -100;
}
tl = tl._timeline;
}
t /= ts;
return t > reference ? t - reference : zeroDur && t === reference || !tween._initted && t - reference < 2 * _tinyNum ? _tinyNum : (t += tween.totalDuration() / tween._timeScale / ts) > reference + _tinyNum ? 0 : t - reference - _tinyNum;
};
//---- TweenLite instance methods -----------------------------------------------------------------------------
p._init = function () {
var v = this.vars,
op = this._overwrittenProps,
dur = this._duration,
immediate = !!v.immediateRender,
ease = v.ease,
i,initPlugins,pt,p,startVars,l;
if (v.startAt) {
if (this._startAt) {
this._startAt.render(-1, true); //if we've run a startAt previously (when the tween instantiated), we should revert it so that the values re-instantiate correctly particularly for relative tweens. Without this, a TweenLite.fromTo(obj, 1, {x:"+=100"}, {x:"-=100"}), for example, would actually jump to +=200 because the startAt would run twice, doubling the relative change.
this._startAt.kill();
}
startVars = {};
for (p in v.startAt) {//copy the properties/values into a new object to avoid collisions, like var to = {x:0}, from = {x:500}; timeline.fromTo(e, 1, from, to).fromTo(e, 1, to, from);
startVars[p] = v.startAt[p];
}
startVars.data = "isStart";
startVars.overwrite = false;
startVars.immediateRender = true;
startVars.lazy = immediate && v.lazy !== false;
startVars.startAt = startVars.delay = null; //no nesting of startAt objects allowed (otherwise it could cause an infinite loop).
startVars.onUpdate = v.onUpdate;
startVars.onUpdateParams = v.onUpdateParams;
startVars.onUpdateScope = v.onUpdateScope || v.callbackScope || this;
this._startAt = TweenLite.to(this.target, 0, startVars);
if (immediate) {
if (this._time > 0) {
this._startAt = null; //tweens that render immediately (like most from() and fromTo() tweens) shouldn't revert when their parent timeline's playhead goes backward past the startTime because the initial render could have happened anytime and it shouldn't be directly correlated to this tween's startTime. Imagine setting up a complex animation where the beginning states of various objects are rendered immediately but the tween doesn't happen for quite some time - if we revert to the starting values as soon as the playhead goes backward past the tween's startTime, it will throw things off visually. Reversion should only happen in TimelineLite/Max instances where immediateRender was false (which is the default in the convenience methods like from()).
} else if (dur !== 0) {
return; //we skip initialization here so that overwriting doesn't occur until the tween actually begins. Otherwise, if you create several immediateRender:true tweens of the same target/properties to drop into a TimelineLite or TimelineMax, the last one created would overwrite the first ones because they didn't get placed into the timeline yet before the first render occurs and kicks in overwriting.
}
}
} else if (v.runBackwards && dur !== 0) {
//from() tweens must be handled uniquely: their beginning values must be rendered but we don't want overwriting to occur yet (when time is still 0). Wait until the tween actually begins before doing all the routines like overwriting. At that time, we should render at the END of the tween to ensure that things initialize correctly (remember, from() tweens go backwards)
if (this._startAt) {
this._startAt.render(-1, true);
this._startAt.kill();
this._startAt = null;
} else {
if (this._time !== 0) {//in rare cases (like if a from() tween runs and then is invalidate()-ed), immediateRender could be true but the initial forced-render gets skipped, so there's no need to force the render in this context when the _time is greater than 0
immediate = false;
}
pt = {};
for (p in v) {//copy props into a new object and skip any reserved props, otherwise onComplete or onUpdate or onStart could fire. We should, however, permit autoCSS to go through.
if (!_reservedProps[p] || p === "autoCSS") {
pt[p] = v[p];
}
}
pt.overwrite = 0;
pt.data = "isFromStart"; //we tag the tween with as "isFromStart" so that if [inside a plugin] we need to only do something at the very END of a tween, we have a way of identifying this tween as merely the one that's setting the beginning values for a "from()" tween. For example, clearProps in CSSPlugin should only get applied at the very END of a tween and without this tag, from(...{height:100, clearProps:"height", delay:1}) would wipe the height at the beginning of the tween and after 1 second, it'd kick back in.
pt.lazy = immediate && v.lazy !== false;
pt.immediateRender = immediate; //zero-duration tweens render immediately by default, but if we're not specifically instructed to render this tween immediately, we should skip this and merely _init() to record the starting values (rendering them immediately would push them to completion which is wasteful in that case - we'd have to render(-1) immediately after)
this._startAt = TweenLite.to(this.target, 0, pt);
if (!immediate) {
this._startAt._init(); //ensures that the initial values are recorded
this._startAt._enabled(false); //no need to have the tween render on the next cycle. Disable it because we'll always manually control the renders of the _startAt tween.
if (this.vars.immediateRender) {
this._startAt = null;
}
} else if (this._time === 0) {
return;
}
}
}
this._ease = ease = !ease ? TweenLite.defaultEase : ease instanceof Ease ? ease : typeof ease === "function" ? new Ease(ease, v.easeParams) : _easeMap[ease] || TweenLite.defaultEase;
if (v.easeParams instanceof Array && ease.config) {
this._ease = ease.config.apply(ease, v.easeParams);
}
this._easeType = this._ease._type;
this._easePower = this._ease._power;
this._firstPT = null;
if (this._targets) {
l = this._targets.length;
for (i = 0; i < l; i++) {
if (this._initProps(this._targets[i], this._propLookup[i] = {}, this._siblings[i], op ? op[i] : null, i)) {
initPlugins = true;
}
}
} else {
initPlugins = this._initProps(this.target, this._propLookup, this._siblings, op, 0);
}
if (initPlugins) {
TweenLite._onPluginEvent("_onInitAllProps", this); //reorders the array in order of priority. Uses a static TweenPlugin method in order to minimize file size in TweenLite
}
if (op) if (!this._firstPT) if (typeof this.target !== "function") {//if all tweening properties have been overwritten, kill the tween. If the target is a function, it's probably a delayedCall so let it live.
this._enabled(false, false);
}
if (v.runBackwards) {
pt = this._firstPT;
while (pt) {
pt.s += pt.c;
pt.c = -pt.c;
pt = pt._next;
}
}
this._onUpdate = v.onUpdate;
this._initted = true;
};
p._initProps = function (target, propLookup, siblings, overwrittenProps, index) {
var p, i, initPlugins, plugin, pt, v;
if (target == null) {
return false;
}
if (_lazyLookup[target._gsTweenID]) {
_lazyRender(); //if other tweens of the same target have recently initted but haven't rendered yet, we've got to force the render so that the starting values are correct (imagine populating a timeline with a bunch of sequential tweens and then jumping to the end)
}
if (!this.vars.css) if (target.style) if (target !== window && target.nodeType) if (_plugins.css) if (this.vars.autoCSS !== false) {//it's so common to use TweenLite/Max to animate the css of DOM elements, we assume that if the target is a DOM element, that's what is intended (a convenience so that users don't have to wrap things in css:{}, although we still recommend it for a slight performance boost and better specificity). Note: we cannot check "nodeType" on the window inside an iframe.
_autoCSS(this.vars, target);
}
for (p in this.vars) {
v = this.vars[p];
if (_reservedProps[p]) {
if (v) if (v instanceof Array || v.push && _isArray(v)) if (v.join("").indexOf("{self}") !== -1) {
this.vars[p] = v = this._swapSelfInParams(v, this);
}
} else if (_plugins[p] && (plugin = new _plugins[p]())._onInitTween(target, this.vars[p], this, index)) {
//t - target [object]
//p - property [string]
//s - start [number]
//c - change [number]
//f - isFunction [boolean]
//n - name [string]
//pg - isPlugin [boolean]
//pr - priority [number]
//m - mod [function | 0]
this._firstPT = pt = { _next: this._firstPT, t: plugin, p: "setRatio", s: 0, c: 1, f: 1, n: p, pg: 1, pr: plugin._priority, m: 0 };
i = plugin._overwriteProps.length;
while (--i > -1) {
propLookup[plugin._overwriteProps[i]] = this._firstPT;
}
if (plugin._priority || plugin._onInitAllProps) {
initPlugins = true;
}
if (plugin._onDisable || plugin._onEnable) {
this._notifyPluginsOfEnabled = true;
}
if (pt._next) {
pt._next._prev = pt;
}
} else {
propLookup[p] = _addPropTween.call(this, target, p, "get", v, p, 0, null, this.vars.stringFilter, index);
}
}
if (overwrittenProps) if (this._kill(overwrittenProps, target)) {//another tween may have tried to overwrite properties of this tween before init() was called (like if two tweens start at the same time, the one created second will run first)
return this._initProps(target, propLookup, siblings, overwrittenProps, index);
}
if (this._overwrite > 1) if (this._firstPT) if (siblings.length > 1) if (_applyOverwrite(target, this, propLookup, this._overwrite, siblings)) {
this._kill(propLookup, target);
return this._initProps(target, propLookup, siblings, overwrittenProps, index);
}
if (this._firstPT) if (this.vars.lazy !== false && this._duration || this.vars.lazy && !this._duration) {//zero duration tweens don't lazy render by default; everything else does.
_lazyLookup[target._gsTweenID] = true;
}
return initPlugins;
};
p.render = function (time, suppressEvents, force) {
var prevTime = this._time,
duration = this._duration,
prevRawPrevTime = this._rawPrevTime,
isComplete,callback,pt,rawPrevTime;
if (time >= duration - 0.0000001 && time >= 0) {//to work around occasional floating point math artifacts.
this._totalTime = this._time = duration;
this.ratio = this._ease._calcEnd ? this._ease.getRatio(1) : 1;
if (!this._reversed) {
isComplete = true;
callback = "onComplete";
force = force || this._timeline.autoRemoveChildren; //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline.
}
if (duration === 0) if (this._initted || !this.vars.lazy || force) {//zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered.
if (this._startTime === this._timeline._duration) {//if a zero-duration tween is at the VERY end of a timeline and that timeline renders at its end, it will typically add a tiny bit of cushion to the render time to prevent rounding errors from getting in the way of tweens rendering their VERY end. If we then reverse() that timeline, the zero-duration tween will trigger its onReverseComplete even though technically the playhead didn't pass over it again. It's a very specific edge case we must accommodate.
time = 0;
}
if (prevRawPrevTime < 0 || time <= 0 && time >= -0.0000001 || prevRawPrevTime === _tinyNum && this.data !== "isPause") if (prevRawPrevTime !== time) {//note: when this.data is "isPause", it's a callback added by addPause() on a timeline that we should not be triggered when LEAVING its exact start time. In other words, tl.addPause(1).play(1) shouldn't pause.
force = true;
if (prevRawPrevTime > _tinyNum) {
callback = "onReverseComplete";
}
}
this._rawPrevTime = rawPrevTime = !suppressEvents || time || prevRawPrevTime === time ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
}
} else if (time < 0.0000001) {//to work around occasional floating point math artifacts, round super small values to 0.
this._totalTime = this._time = 0;
this.ratio = this._ease._calcEnd ? this._ease.getRatio(0) : 0;
if (prevTime !== 0 || duration === 0 && prevRawPrevTime > 0) {
callback = "onReverseComplete";
isComplete = this._reversed;
}
if (time < 0) {
this._active = false;
if (duration === 0) if (this._initted || !this.vars.lazy || force) {//zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered.
if (prevRawPrevTime >= 0 && !(prevRawPrevTime === _tinyNum && this.data === "isPause")) {
force = true;
}
this._rawPrevTime = rawPrevTime = !suppressEvents || time || prevRawPrevTime === time ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
}
}
if (!this._initted || this._startAt && this._startAt.progress()) {//if we render the very beginning (time == 0) of a fromTo(), we must force the render (normal tweens wouldn't need to render at a time of 0 when the prevTime was also 0). This is also mandatory to make sure overwriting kicks in immediately. Also, we check progress() because if startAt has already rendered at its end, we should force a render at its beginning. Otherwise, if you put the playhead directly on top of where a fromTo({immediateRender:false}) starts, and then move it backwards, the from() won't revert its values.
force = true;
}
} else {
this._totalTime = this._time = time;
if (this._easeType) {
var r = time / duration,type = this._easeType,pow = this._easePower;
if (type === 1 || type === 3 && r >= 0.5) {
r = 1 - r;
}
if (type === 3) {
r *= 2;
}
if (pow === 1) {
r *= r;
} else if (pow === 2) {
r *= r * r;
} else if (pow === 3) {
r *= r * r * r;
} else if (pow === 4) {
r *= r * r * r * r;
}
if (type === 1) {
this.ratio = 1 - r;
} else if (type === 2) {
this.ratio = r;
} else if (time / duration < 0.5) {
this.ratio = r / 2;
} else {
this.ratio = 1 - r / 2;
}
} else {
this.ratio = this._ease.getRatio(time / duration);
}
}
if (this._time === prevTime && !force) {
return;
} else if (!this._initted) {
this._init();
if (!this._initted || this._gc) {//immediateRender tweens typically won't initialize until the playhead advances (_time is greater than 0) in order to ensure that overwriting occurs properly. Also, if all of the tweening properties have been overwritten (which would cause _gc to be true, as set in _init()), we shouldn't continue otherwise an onStart callback could be called for example.
return;
} else if (!force && this._firstPT && (this.vars.lazy !== false && this._duration || this.vars.lazy && !this._duration)) {
this._time = this._totalTime = prevTime;
this._rawPrevTime = prevRawPrevTime;
_lazyTweens.push(this);
this._lazy = [time, suppressEvents];
return;
}
//_ease is initially set to defaultEase, so now that init() has run, _ease is set properly and we need to recalculate the ratio. Overall this is faster than using conditional logic earlier in the method to avoid having to set ratio twice because we only init() once but renderTime() gets called VERY frequently.
if (this._time && !isComplete) {
this.ratio = this._ease.getRatio(this._time / duration);
} else if (isComplete && this._ease._calcEnd) {
this.ratio = this._ease.getRatio(this._time === 0 ? 0 : 1);
}
}
if (this._lazy !== false) {//in case a lazy render is pending, we should flush it because the new render is occurring now (imagine a lazy tween instantiating and then immediately the user calls tween.seek(tween.duration()), skipping to the end - the end render would be forced, and then if we didn't flush the lazy render, it'd fire AFTER the seek(), rendering it at the wrong time.
this._lazy = false;
}
if (!this._active) if (!this._paused && this._time !== prevTime && time >= 0) {
this._active = true; //so that if the user renders a tween (as opposed to the timeline rendering it), the timeline is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the tween already finished but the user manually re-renders it as halfway done.
}
if (prevTime === 0) {
if (this._startAt) {
if (time >= 0) {
this._startAt.render(time, true, force);
} else if (!callback) {
callback = "_dummyGS"; //if no callback is defined, use a dummy value just so that the condition at the end evaluates as true because _startAt should render AFTER the normal render loop when the time is negative. We could handle this in a more intuitive way, of course, but the render loop is the MOST important thing to optimize, so this technique allows us to avoid adding extra conditional logic in a high-frequency area.
}
}
if (this.vars.onStart) if (this._time !== 0 || duration === 0) if (!suppressEvents) {
this._callback("onStart");
}
}
pt = this._firstPT;
while (pt) {
if (pt.f) {
pt.t[pt.p](pt.c * this.ratio + pt.s);
} else {
pt.t[pt.p] = pt.c * this.ratio + pt.s;
}
pt = pt._next;
}
if (this._onUpdate) {
if (time < 0) if (this._startAt && time !== -0.0001) {//if the tween is positioned at the VERY beginning (_startTime 0) of its parent timeline, it's illegal for the playhead to go back further, so we should not render the recorded startAt values.
this._startAt.render(time, true, force); //note: for performance reasons, we tuck this conditional logic inside less traveled areas (most tweens don't have an onUpdate). We'd just have it at the end before the onComplete, but the values should be updated before any onUpdate is called, so we ALSO put it here and then if it's not called, we do so later near the onComplete.
}
if (!suppressEvents) if (this._time !== prevTime || isComplete || force) {
this._callback("onUpdate");
}
}
if (callback) if (!this._gc || force) {//check _gc because there's a chance that kill() could be called in an onUpdate
if (time < 0 && this._startAt && !this._onUpdate && time !== -0.0001) {//-0.0001 is a special value that we use when looping back to the beginning of a repeated TimelineMax, in which case we shouldn't render the _startAt values.
this._startAt.render(time, true, force);
}
if (isComplete) {
if (this._timeline.autoRemoveChildren) {
this._enabled(false, false);
}
this._active = false;
}
if (!suppressEvents && this.vars[callback]) {
this._callback(callback);
}
if (duration === 0 && this._rawPrevTime === _tinyNum && rawPrevTime !== _tinyNum) {//the onComplete or onReverseComplete could trigger movement of the playhead and for zero-duration tweens (which must discern direction) that land directly back on their start time, we don't want to fire again on the next render. Think of several addPause()'s in a timeline that forces the playhead to a certain spot, but what if it's already paused and another tween is tweening the "time" of the timeline? Each time it moves [forward] past that spot, it would move back, and since suppressEvents is true, it'd reset _rawPrevTime to _tinyNum so that when it begins again, the callback would fire (so ultimately it could bounce back and forth during that tween). Again, this is a very uncommon scenario, but possible nonetheless.
this._rawPrevTime = 0;
}
}
};
p._kill = function (vars, target, overwritingTween) {
if (vars === "all") {
vars = null;
}
if (vars == null) if (target == null || target === this.target) {
this._lazy = false;
return this._enabled(false, false);
}
target = typeof target !== "string" ? target || this._targets || this.target : TweenLite.selector(target) || target;
var simultaneousOverwrite = overwritingTween && this._time && overwritingTween._startTime === this._startTime && this._timeline === overwritingTween._timeline,
i,overwrittenProps,p,pt,propLookup,changed,killProps,record,killed;
if ((_isArray(target) || _isSelector(target)) && typeof target[0] !== "number") {
i = target.length;
while (--i > -1) {
if (this._kill(vars, target[i], overwritingTween)) {
changed = true;
}
}
} else {
if (this._targets) {
i = this._targets.length;
while (--i > -1) {
if (target === this._targets[i]) {
propLookup = this._propLookup[i] || {};
this._overwrittenProps = this._overwrittenProps || [];
overwrittenProps = this._overwrittenProps[i] = vars ? this._overwrittenProps[i] || {} : "all";
break;
}
}
} else if (target !== this.target) {
return false;
} else {
propLookup = this._propLookup;
overwrittenProps = this._overwrittenProps = vars ? this._overwrittenProps || {} : "all";
}
if (propLookup) {
killProps = vars || propLookup;
record = vars !== overwrittenProps && overwrittenProps !== "all" && vars !== propLookup && ((typeof vars === "undefined" ? "undefined" : _typeof(vars)) !== "object" || !vars._tempKill); //_tempKill is a super-secret way to delete a particular tweening property but NOT have it remembered as an official overwritten property (like in BezierPlugin)
if (overwritingTween && (TweenLite.onOverwrite || this.vars.onOverwrite)) {
for (p in killProps) {
if (propLookup[p]) {
if (!killed) {
killed = [];
}
killed.push(p);
}
}
if ((killed || !vars) && !_onOverwrite(this, overwritingTween, target, killed)) {//if the onOverwrite returned false, that means the user wants to override the overwriting (cancel it).
return false;
}
}
for (p in killProps) {
if (pt = propLookup[p]) {
if (simultaneousOverwrite) {//if another tween overwrites this one and they both start at exactly the same time, yet this tween has already rendered once (for example, at 0.001) because it's first in the queue, we should revert the values to where they were at 0 so that the starting values aren't contaminated on the overwriting tween.
if (pt.f) {
pt.t[pt.p](pt.s);
} else {
pt.t[pt.p] = pt.s;
}
changed = true;
}
if (pt.pg && pt.t._kill(killProps)) {
changed = true; //some plugins need to be notified so they can perform cleanup tasks first
}
if (!pt.pg || pt.t._overwriteProps.length === 0) {
if (pt._prev) {
pt._prev._next = pt._next;
} else if (pt === this._firstPT) {
this._firstPT = pt._next;
}
if (pt._next) {
pt._next._prev = pt._prev;
}
pt._next = pt._prev = null;
}
delete propLookup[p];
}
if (record) {
overwrittenProps[p] = 1;
}
}
if (!this._firstPT && this._initted) {//if all tweening properties are killed, kill the tween. Without this line, if there's a tween with multiple targets and then you killTweensOf() each target individually, the tween would technically still remain active and fire its onComplete even though there aren't any more properties tweening.
this._enabled(false, false);
}
}
}
return changed;
};
p.invalidate = function () {
if (this._notifyPluginsOfEnabled) {
TweenLite._onPluginEvent("_onDisable", this);
}
this._firstPT = this._overwrittenProps = this._startAt = this._onUpdate = null;
this._notifyPluginsOfEnabled = this._active = this._lazy = false;
this._propLookup = this._targets ? {} : [];
Animation.prototype.invalidate.call(this);
if (this.vars.immediateRender) {
this._time = -_tinyNum; //forces a render without having to set the render() "force" parameter to true because we want to allow lazying by default (using the "force" parameter always forces an immediate full render)
this.render(Math.min(0, -this._delay)); //in case delay is negative.
}
return this;
};
p._enabled = function (enabled, ignoreTimeline) {
if (!_tickerActive) {
_ticker.wake();
}
if (enabled && this._gc) {
var targets = this._targets,
i;
if (targets) {
i = targets.length;
while (--i > -1) {
this._siblings[i] = _register(targets[i], this, true);
}
} else {
this._siblings = _register(this.target, this, true);
}
}
Animation.prototype._enabled.call(this, enabled, ignoreTimeline);
if (this._notifyPluginsOfEnabled) if (this._firstPT) {
return TweenLite._onPluginEvent(enabled ? "_onEnable" : "_onDisable", this);
}
return false;
};
//----TweenLite static methods -----------------------------------------------------
TweenLite.to = function (target, duration, vars) {
return new TweenLite(target, duration, vars);
};
TweenLite.from = function (target, duration, vars) {
vars.runBackwards = true;
vars.immediateRender = vars.immediateRender != false;
return new TweenLite(target, duration, vars);
};
TweenLite.fromTo = function (target, duration, fromVars, toVars) {
toVars.startAt = fromVars;
toVars.immediateRender = toVars.immediateRender != false && fromVars.immediateRender != false;
return new TweenLite(target, duration, toVars);
};
TweenLite.delayedCall = function (delay, callback, params, scope, useFrames) {
return new TweenLite(callback, 0, { delay: delay, onComplete: callback, onCompleteParams: params, callbackScope: scope, onReverseComplete: callback, onReverseCompleteParams: params, immediateRender: false, lazy: false, useFrames: useFrames, overwrite: 0 });
};
TweenLite.set = function (target, vars) {
return new TweenLite(target, 0, vars);
};
TweenLite.getTweensOf = function (target, onlyActive) {
if (target == null) {return [];}
target = typeof target !== "string" ? target : TweenLite.selector(target) || target;
var i, a, j, t;
if ((_isArray(target) || _isSelector(target)) && typeof target[0] !== "number") {
i = target.length;
a = [];
while (--i > -1) {
a = a.concat(TweenLite.getTweensOf(target[i], onlyActive));
}
i = a.length;
//now get rid of any duplicates (tweens of arrays of objects could cause duplicates)
while (--i > -1) {
t = a[i];
j = i;
while (--j > -1) {
if (t === a[j]) {
a.splice(i, 1);
}
}
}
} else if (target._gsTweenID) {
a = _register(target).concat();
i = a.length;
while (--i > -1) {
if (a[i]._gc || onlyActive && !a[i].isActive()) {
a.splice(i, 1);
}
}
}
return a || [];
};
TweenLite.killTweensOf = TweenLite.killDelayedCallsTo = function (target, onlyActive, vars) {
if ((typeof onlyActive === "undefined" ? "undefined" : _typeof(onlyActive)) === "object") {
vars = onlyActive; //for backwards compatibility (before "onlyActive" parameter was inserted)
onlyActive = false;
}
var a = TweenLite.getTweensOf(target, onlyActive),
i = a.length;
while (--i > -1) {
a[i]._kill(vars, target);
}
};
/*
* ----------------------------------------------------------------
* TweenPlugin (could easily be split out as a separate file/class, but included for ease of use (so that people don't need to include another script call before loading plugins which is easy to forget)
* ----------------------------------------------------------------
*/
var TweenPlugin = _class("plugins.TweenPlugin", function (props, priority) {
this._overwriteProps = (props || "").split(",");
this._propName = this._overwriteProps[0];
this._priority = priority || 0;
this._super = TweenPlugin.prototype;
}, true);
p = TweenPlugin.prototype;
TweenPlugin.version = "1.19.0";
TweenPlugin.API = 2;
p._firstPT = null;
p._addTween = _addPropTween;
p.setRatio = _setRatio;
p._kill = function (lookup) {
var a = this._overwriteProps,
pt = this._firstPT,
i;
if (lookup[this._propName] != null) {
this._overwriteProps = [];
} else {
i = a.length;
while (--i > -1) {
if (lookup[a[i]] != null) {
a.splice(i, 1);
}
}
}
while (pt) {
if (lookup[pt.n] != null) {
if (pt._next) {
pt._next._prev = pt._prev;
}
if (pt._prev) {
pt._prev._next = pt._next;
pt._prev = null;
} else if (this._firstPT === pt) {
this._firstPT = pt._next;
}
}
pt = pt._next;
}
return false;
};
p._mod = p._roundProps = function (lookup) {
var pt = this._firstPT,
val;
while (pt) {
val = lookup[this._propName] || pt.n != null && lookup[pt.n.split(this._propName + "_").join("")];
if (val && typeof val === "function") {//some properties that are very plugin-specific add a prefix named after the _propName plus an underscore, so we need to ignore that extra stuff here.
if (pt.f === 2) {
pt.t._applyPT.m = val;
} else {
pt.m = val;
}
}
pt = pt._next;
}
};
TweenLite._onPluginEvent = function (type, tween) {
var pt = tween._firstPT,
changed,pt2,first,last,next;
if (type === "_onInitAllProps") {
//sorts the PropTween linked list in order of priority because some plugins need to render earlier/later than others, like MotionBlurPlugin applies its effects after all x/y/alpha tweens have rendered on each frame.
while (pt) {
next = pt._next;
pt2 = first;
while (pt2 && pt2.pr > pt.pr) {
pt2 = pt2._next;
}
if (pt._prev = pt2 ? pt2._prev : last) {
pt._prev._next = pt;
} else {
first = pt;
}
if (pt._next = pt2) {
pt2._prev = pt;
} else {
last = pt;
}
pt = next;
}
pt = tween._firstPT = first;
}
while (pt) {
if (pt.pg) if (typeof pt.t[type] === "function") if (pt.t[type]()) {
changed = true;
}
pt = pt._next;
}
return changed;
};
TweenPlugin.activate = function (plugins) {
var i = plugins.length;
while (--i > -1) {
if (plugins[i].API === TweenPlugin.API) {
_plugins[new plugins[i]()._propName] = plugins[i];
}
}
return true;
};
//provides a more concise way to define plugins that have no dependencies besides TweenPlugin and TweenLite, wrapping common boilerplate stuff into one function (added in 1.9.0). You don't NEED to use this to define a plugin - the old way still works and can be useful in certain (rare) situations.
_gsDefine.plugin = function (config) {
if (!config || !config.propName || !config.init || !config.API) {throw "illegal plugin definition.";}
var propName = config.propName,
priority = config.priority || 0,
overwriteProps = config.overwriteProps,
map = { init: "_onInitTween", set: "setRatio", kill: "_kill", round: "_mod", mod: "_mod", initAll: "_onInitAllProps" },
Plugin = _class("plugins." + propName.charAt(0).toUpperCase() + propName.substr(1) + "Plugin",
function () {
TweenPlugin.call(this, propName, priority);
this._overwriteProps = overwriteProps || [];
}, config.global === true),
p = Plugin.prototype = new TweenPlugin(propName),
prop;
p.constructor = Plugin;
Plugin.API = config.API;
for (prop in map) {
if (typeof config[prop] === "function") {
p[map[prop]] = config[prop];
}
}
Plugin.version = config.version;
TweenPlugin.activate([Plugin]);
return Plugin;
};
//now run through all the dependencies discovered and if any are missing, log that to the console as a warning. This is why it's best to have TweenLite load last - it can check all the dependencies for you.
a = window._gsQueue;
if (a) {
for (i = 0; i < a.length; i++) {
a[i]();
}
for (p in _defLookup) {
if (!_defLookup[p].func) {
window.console.log("GSAP encountered missing dependency: " + p);
}
}
}
_tickerActive = false; //ensures that the first official animation forces a ticker.tick() to update the time when it is instantiated
})(typeof module !== "undefined" && module.exports && typeof global !== "undefined" ? global : undefined || window, "TweenMax");
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_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;}; /*!
* VERSION: 1.20.4
* DATE: 2018-02-15
* UPDATES AND DOCS AT: http://greensock.com
*
* @license Copyright (c) 2008-2018, GreenSock. All rights reserved.
* This work is subject to the terms at http://greensock.com/standard-license or for
* Club GreenSock members, the software agreement that was issued with your membership.
*
* @author: Jack Doyle, jack@greensock.com
*/
(function (window, moduleName) {
"use strict";
var _exports = {},
_doc = window.document,
_globals = window.GreenSockGlobals = window.GreenSockGlobals || window;
if (_globals.TweenLite) {
return; //in case the core set of classes is already loaded, don't instantiate twice.
}
var _namespace = function _namespace(ns) {
var a = ns.split("."),
p = _globals,i;
for (i = 0; i < a.length; i++) {
p[a[i]] = p = p[a[i]] || {};
}
return p;
},
gs = _namespace("com.greensock"),
_tinyNum = 0.0000000001,
_slice = function _slice(a) {//don't use Array.prototype.slice.call(target, 0) because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll()
var b = [],
l = a.length,
i;
for (i = 0; i !== l; b.push(a[i++])) {}
return b;
},
_emptyFunc = function _emptyFunc() {},
_isArray = function () {//works around issues in iframe environments where the Array global isn't shared, thus if the object originates in a different window/iframe, "(obj instanceof Array)" will evaluate false. We added some speed optimizations to avoid Object.prototype.toString.call() unless it's absolutely necessary because it's VERY slow (like 20x slower)
var toString = Object.prototype.toString,
array = toString.call([]);
return function (obj) {
return obj != null && (obj instanceof Array || (typeof obj === "undefined" ? "undefined" : _typeof(obj)) === "object" && !!obj.push && toString.call(obj) === array);
};
}(),
a,i,p,_ticker,_tickerActive,
_defLookup = {},
/**
* @constructor
* Defines a GreenSock class, optionally with an array of dependencies that must be instantiated first and passed into the definition.
* This allows users to load GreenSock JS files in any order even if they have interdependencies (like CSSPlugin extends TweenPlugin which is
* inside TweenLite.js, but if CSSPlugin is loaded first, it should wait to run its code until TweenLite.js loads and instantiates TweenPlugin
* and then pass TweenPlugin to CSSPlugin's definition). This is all done automatically and internally.
*
* Every definition will be added to a "com.greensock" global object (typically window, but if a window.GreenSockGlobals object is found,
* it will go there as of v1.7). For example, TweenLite will be found at window.com.greensock.TweenLite and since it's a global class that should be available anywhere,
* it is ALSO referenced at window.TweenLite. However some classes aren't considered global, like the base com.greensock.core.Animation class, so
* those will only be at the package like window.com.greensock.core.Animation. Again, if you define a GreenSockGlobals object on the window, everything
* gets tucked neatly inside there instead of on the window directly. This allows you to do advanced things like load multiple versions of GreenSock
* files and put them into distinct objects (imagine a banner ad uses a newer version but the main site uses an older one). In that case, you could
* sandbox the banner one like:
*
* <script>
* var gs = window.GreenSockGlobals = {}; //the newer version we're about to load could now be referenced in a "gs" object, like gs.TweenLite.to(...). Use whatever alias you want as long as it's unique, "gs" or "banner" or whatever.
* </script>
* <script src="js/greensock/v1.7/TweenMax.js"></script>
* <script>
* window.GreenSockGlobals = window._gsQueue = window._gsDefine = null; //reset it back to null (along with the special _gsQueue variable) so that the next load of TweenMax affects the window and we can reference things directly like TweenLite.to(...)
* </script>
* <script src="js/greensock/v1.6/TweenMax.js"></script>
* <script>
* gs.TweenLite.to(...); //would use v1.7
* TweenLite.to(...); //would use v1.6
* </script>
*
* @param {!string} ns The namespace of the class definition, leaving off "com.greensock." as that's assumed. For example, "TweenLite" or "plugins.CSSPlugin" or "easing.Back".
* @param {!Array.<string>} dependencies An array of dependencies (described as their namespaces minus "com.greensock." prefix). For example ["TweenLite","plugins.TweenPlugin","core.Animation"]
* @param {!function():Object} func The function that should be called and passed the resolved dependencies which will return the actual class for this definition.
* @param {boolean=} global If true, the class will be added to the global scope (typically window unless you define a window.GreenSockGlobals object)
*/
Definition = function Definition(ns, dependencies, func, global) {
this.sc = _defLookup[ns] ? _defLookup[ns].sc : []; //subclasses
_defLookup[ns] = this;
this.gsClass = null;
this.func = func;
var _classes = [];
this.check = function (init) {
var i = dependencies.length,
missing = i,
cur,a,n,cl;
while (--i > -1) {
if ((cur = _defLookup[dependencies[i]] || new Definition(dependencies[i], [])).gsClass) {
_classes[i] = cur.gsClass;
missing--;
} else if (init) {
cur.sc.push(this);
}
}
if (missing === 0 && func) {
a = ("com.greensock." + ns).split(".");
n = a.pop();
cl = _namespace(a.join("."))[n] = this.gsClass = func.apply(func, _classes);
//exports to multiple environments
if (global) {
_globals[n] = _exports[n] = cl; //provides a way to avoid global namespace pollution. By default, the main classes like TweenLite, Power1, Strong, etc. are added to window unless a GreenSockGlobals is defined. So if you want to have things added to a custom object instead, just do something like window.GreenSockGlobals = {} before loading any GreenSock files. You can even set up an alias like window.GreenSockGlobals = windows.gs = {} so that you can access everything like gs.TweenLite. Also remember that ALL classes are added to the window.com.greensock object (in their respective packages, like com.greensock.easing.Power1, com.greensock.TweenLite, etc.)
if (typeof module !== "undefined" && module.exports) {//node
if (ns === moduleName) {
module.exports = _exports[moduleName] = cl;
for (i in _exports) {
cl[i] = _exports[i];
}
} else if (_exports[moduleName]) {
_exports[moduleName][n] = cl;
}
} else if (true) {//AMD
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {return cl;}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
}
for (i = 0; i < this.sc.length; i++) {
this.sc[i].check();
}
}
};
this.check(true);
},
//used to create Definition instances (which basically registers a class that has dependencies).
_gsDefine = window._gsDefine = function (ns, dependencies, func, global) {
return new Definition(ns, dependencies, func, global);
},
//a quick way to create a class that doesn't have any dependencies. Returns the class, but first registers it in the GreenSock namespace so that other classes can grab it (other classes might be dependent on the class).
_class = gs._class = function (ns, func, global) {
func = func || function () {};
_gsDefine(ns, [], function () {return func;}, global);
return func;
};
_gsDefine.globals = _globals;
/*
* ----------------------------------------------------------------
* Ease
* ----------------------------------------------------------------
*/
var _baseParams = [0, 0, 1, 1],
Ease = _class("easing.Ease", function (func, extraParams, type, power) {
this._func = func;
this._type = type || 0;
this._power = power || 0;
this._params = extraParams ? _baseParams.concat(extraParams) : _baseParams;
}, true),
_easeMap = Ease.map = {},
_easeReg = Ease.register = function (ease, names, types, create) {
var na = names.split(","),
i = na.length,
ta = (types || "easeIn,easeOut,easeInOut").split(","),
e,name,j,type;
while (--i > -1) {
name = na[i];
e = create ? _class("easing." + name, null, true) : gs.easing[name] || {};
j = ta.length;
while (--j > -1) {
type = ta[j];
_easeMap[name + "." + type] = _easeMap[type + name] = e[type] = ease.getRatio ? ease : ease[type] || new ease();
}
}
};
p = Ease.prototype;
p._calcEnd = false;
p.getRatio = function (p) {
if (this._func) {
this._params[0] = p;
return this._func.apply(null, this._params);
}
var t = this._type,
pw = this._power,
r = t === 1 ? 1 - p : t === 2 ? p : p < 0.5 ? p * 2 : (1 - p) * 2;
if (pw === 1) {
r *= r;
} else if (pw === 2) {
r *= r * r;
} else if (pw === 3) {
r *= r * r * r;
} else if (pw === 4) {
r *= r * r * r * r;
}
return t === 1 ? 1 - r : t === 2 ? r : p < 0.5 ? r / 2 : 1 - r / 2;
};
//create all the standard eases like Linear, Quad, Cubic, Quart, Quint, Strong, Power0, Power1, Power2, Power3, and Power4 (each with easeIn, easeOut, and easeInOut)
a = ["Linear", "Quad", "Cubic", "Quart", "Quint,Strong"];
i = a.length;
while (--i > -1) {
p = a[i] + ",Power" + i;
_easeReg(new Ease(null, null, 1, i), p, "easeOut", true);
_easeReg(new Ease(null, null, 2, i), p, "easeIn" + (i === 0 ? ",easeNone" : ""));
_easeReg(new Ease(null, null, 3, i), p, "easeInOut");
}
_easeMap.linear = gs.easing.Linear.easeIn;
_easeMap.swing = gs.easing.Quad.easeInOut; //for jQuery folks
/*
* ----------------------------------------------------------------
* EventDispatcher
* ----------------------------------------------------------------
*/
var EventDispatcher = _class("events.EventDispatcher", function (target) {
this._listeners = {};
this._eventTarget = target || this;
});
p = EventDispatcher.prototype;
p.addEventListener = function (type, callback, scope, useParam, priority) {
priority = priority || 0;
var list = this._listeners[type],
index = 0,
listener,i;
if (this === _ticker && !_tickerActive) {
_ticker.wake();
}
if (list == null) {
this._listeners[type] = list = [];
}
i = list.length;
while (--i > -1) {
listener = list[i];
if (listener.c === callback && listener.s === scope) {
list.splice(i, 1);
} else if (index === 0 && listener.pr < priority) {
index = i + 1;
}
}
list.splice(index, 0, { c: callback, s: scope, up: useParam, pr: priority });
};
p.removeEventListener = function (type, callback) {
var list = this._listeners[type],i;
if (list) {
i = list.length;
while (--i > -1) {
if (list[i].c === callback) {
list.splice(i, 1);
return;
}
}
}
};
p.dispatchEvent = function (type) {
var list = this._listeners[type],
i,t,listener;
if (list) {
i = list.length;
if (i > 1) {
list = list.slice(0); //in case addEventListener() is called from within a listener/callback (otherwise the index could change, resulting in a skip)
}
t = this._eventTarget;
while (--i > -1) {
listener = list[i];
if (listener) {
if (listener.up) {
listener.c.call(listener.s || t, { type: type, target: t });
} else {
listener.c.call(listener.s || t);
}
}
}
}
};
/*
* ----------------------------------------------------------------
* Ticker
* ----------------------------------------------------------------
*/
var _reqAnimFrame = window.requestAnimationFrame,
_cancelAnimFrame = window.cancelAnimationFrame,
_getTime = Date.now || function () {return new Date().getTime();},
_lastUpdate = _getTime();
//now try to determine the requestAnimationFrame and cancelAnimationFrame functions and if none are found, we'll use a setTimeout()/clearTimeout() polyfill.
a = ["ms", "moz", "webkit", "o"];
i = a.length;
while (--i > -1 && !_reqAnimFrame) {
_reqAnimFrame = window[a[i] + "RequestAnimationFrame"];
_cancelAnimFrame = window[a[i] + "CancelAnimationFrame"] || window[a[i] + "CancelRequestAnimationFrame"];
}
_class("Ticker", function (fps, useRAF) {
var _self = this,
_startTime = _getTime(),
_useRAF = useRAF !== false && _reqAnimFrame ? "auto" : false,
_lagThreshold = 500,
_adjustedLag = 33,
_tickWord = "tick", //helps reduce gc burden
_fps,_req,_id,_gap,_nextTime,
_tick = function _tick(manual) {
var elapsed = _getTime() - _lastUpdate,
overlap,dispatch;
if (elapsed > _lagThreshold) {
_startTime += elapsed - _adjustedLag;
}
_lastUpdate += elapsed;
_self.time = (_lastUpdate - _startTime) / 1000;
overlap = _self.time - _nextTime;
if (!_fps || overlap > 0 || manual === true) {
_self.frame++;
_nextTime += overlap + (overlap >= _gap ? 0.004 : _gap - overlap);
dispatch = true;
}
if (manual !== true) {//make sure the request is made before we dispatch the "tick" event so that timing is maintained. Otherwise, if processing the "tick" requires a bunch of time (like 15ms) and we're using a setTimeout() that's based on 16.7ms, it'd technically take 31.7ms between frames otherwise.
_id = _req(_tick);
}
if (dispatch) {
_self.dispatchEvent(_tickWord);
}
};
EventDispatcher.call(_self);
_self.time = _self.frame = 0;
_self.tick = function () {
_tick(true);
};
_self.lagSmoothing = function (threshold, adjustedLag) {
if (!arguments.length) {//if lagSmoothing() is called with no arguments, treat it like a getter that returns a boolean indicating if it's enabled or not. This is purposely undocumented and is for internal use.
return _lagThreshold < 1 / _tinyNum;
}
_lagThreshold = threshold || 1 / _tinyNum; //zero should be interpreted as basically unlimited
_adjustedLag = Math.min(adjustedLag, _lagThreshold, 0);
};
_self.sleep = function () {
if (_id == null) {
return;
}
if (!_useRAF || !_cancelAnimFrame) {
clearTimeout(_id);
} else {
_cancelAnimFrame(_id);
}
_req = _emptyFunc;
_id = null;
if (_self === _ticker) {
_tickerActive = false;
}
};
_self.wake = function (seamless) {
if (_id !== null) {
_self.sleep();
} else if (seamless) {
_startTime += -_lastUpdate + (_lastUpdate = _getTime());
} else if (_self.frame > 10) {//don't trigger lagSmoothing if we're just waking up, and make sure that at least 10 frames have elapsed because of the iOS bug that we work around below with the 1.5-second setTimout().
_lastUpdate = _getTime() - _lagThreshold + 5;
}
_req = _fps === 0 ? _emptyFunc : !_useRAF || !_reqAnimFrame ? function (f) {return setTimeout(f, (_nextTime - _self.time) * 1000 + 1 | 0);} : _reqAnimFrame;
if (_self === _ticker) {
_tickerActive = true;
}
_tick(2);
};
_self.fps = function (value) {
if (!arguments.length) {
return _fps;
}
_fps = value;
_gap = 1 / (_fps || 60);
_nextTime = this.time + _gap;
_self.wake();
};
_self.useRAF = function (value) {
if (!arguments.length) {
return _useRAF;
}
_self.sleep();
_useRAF = value;
_self.fps(_fps);
};
_self.fps(fps);
//a bug in iOS 6 Safari occasionally prevents the requestAnimationFrame from working initially, so we use a 1.5-second timeout that automatically falls back to setTimeout() if it senses this condition.
setTimeout(function () {
if (_useRAF === "auto" && _self.frame < 5 && (_doc || {}).visibilityState !== "hidden") {
_self.useRAF(false);
}
}, 1500);
});
p = gs.Ticker.prototype = new gs.events.EventDispatcher();
p.constructor = gs.Ticker;
/*
* ----------------------------------------------------------------
* Animation
* ----------------------------------------------------------------
*/
var Animation = _class("core.Animation", function (duration, vars) {
this.vars = vars = vars || {};
this._duration = this._totalDuration = duration || 0;
this._delay = Number(vars.delay) || 0;
this._timeScale = 1;
this._active = vars.immediateRender === true;
this.data = vars.data;
this._reversed = vars.reversed === true;
if (!_rootTimeline) {
return;
}
if (!_tickerActive) {//some browsers (like iOS 6 Safari) shut down JavaScript execution when the tab is disabled and they [occasionally] neglect to start up requestAnimationFrame again when returning - this code ensures that the engine starts up again properly.
_ticker.wake();
}
var tl = this.vars.useFrames ? _rootFramesTimeline : _rootTimeline;
tl.add(this, tl._time);
if (this.vars.paused) {
this.paused(true);
}
});
_ticker = Animation.ticker = new gs.Ticker();
p = Animation.prototype;
p._dirty = p._gc = p._initted = p._paused = false;
p._totalTime = p._time = 0;
p._rawPrevTime = -1;
p._next = p._last = p._onUpdate = p._timeline = p.timeline = null;
p._paused = false;
//some browsers (like iOS) occasionally drop the requestAnimationFrame event when the user switches to a different tab and then comes back again, so we use a 2-second setTimeout() to sense if/when that condition occurs and then wake() the ticker.
var _checkTimeout = function _checkTimeout() {
if (_tickerActive && _getTime() - _lastUpdate > 2000 && ((_doc || {}).visibilityState !== "hidden" || !_ticker.lagSmoothing())) {//note: if the tab is hidden, we should still wake if lagSmoothing has been disabled.
_ticker.wake();
}
var t = setTimeout(_checkTimeout, 2000);
if (t.unref) {
// allows a node process to exit even if the timeout’s callback hasn't been invoked. Without it, the node process could hang as this function is called every two seconds.
t.unref();
}
};
_checkTimeout();
p.play = function (from, suppressEvents) {
if (from != null) {
this.seek(from, suppressEvents);
}
return this.reversed(false).paused(false);
};
p.pause = function (atTime, suppressEvents) {
if (atTime != null) {
this.seek(atTime, suppressEvents);
}
return this.paused(true);
};
p.resume = function (from, suppressEvents) {
if (from != null) {
this.seek(from, suppressEvents);
}
return this.paused(false);
};
p.seek = function (time, suppressEvents) {
return this.totalTime(Number(time), suppressEvents !== false);
};
p.restart = function (includeDelay, suppressEvents) {
return this.reversed(false).paused(false).totalTime(includeDelay ? -this._delay : 0, suppressEvents !== false, true);
};
p.reverse = function (from, suppressEvents) {
if (from != null) {
this.seek(from || this.totalDuration(), suppressEvents);
}
return this.reversed(true).paused(false);
};
p.render = function (time, suppressEvents, force) {
//stub - we override this method in subclasses.
};
p.invalidate = function () {
this._time = this._totalTime = 0;
this._initted = this._gc = false;
this._rawPrevTime = -1;
if (this._gc || !this.timeline) {
this._enabled(true);
}
return this;
};
p.isActive = function () {
var tl = this._timeline, //the 2 root timelines won't have a _timeline; they're always active.
startTime = this._startTime,
rawTime;
return !tl || !this._gc && !this._paused && tl.isActive() && (rawTime = tl.rawTime(true)) >= startTime && rawTime < startTime + this.totalDuration() / this._timeScale - 0.0000001;
};
p._enabled = function (enabled, ignoreTimeline) {
if (!_tickerActive) {
_ticker.wake();
}
this._gc = !enabled;
this._active = this.isActive();
if (ignoreTimeline !== true) {
if (enabled && !this.timeline) {
this._timeline.add(this, this._startTime - this._delay);
} else if (!enabled && this.timeline) {
this._timeline._remove(this, true);
}
}
return false;
};
p._kill = function (vars, target) {
return this._enabled(false, false);
};
p.kill = function (vars, target) {
this._kill(vars, target);
return this;
};
p._uncache = function (includeSelf) {
var tween = includeSelf ? this : this.timeline;
while (tween) {
tween._dirty = true;
tween = tween.timeline;
}
return this;
};
p._swapSelfInParams = function (params) {
var i = params.length,
copy = params.concat();
while (--i > -1) {
if (params[i] === "{self}") {
copy[i] = this;
}
}
return copy;
};
p._callback = function (type) {
var v = this.vars,
callback = v[type],
params = v[type + "Params"],
scope = v[type + "Scope"] || v.callbackScope || this,
l = params ? params.length : 0;
switch (l) {//speed optimization; call() is faster than apply() so use it when there are only a few parameters (which is by far most common). Previously we simply did var v = this.vars; v[type].apply(v[type + "Scope"] || v.callbackScope || this, v[type + "Params"] || _blankArray);
case 0:callback.call(scope);break;
case 1:callback.call(scope, params[0]);break;
case 2:callback.call(scope, params[0], params[1]);break;
default:callback.apply(scope, params);}
};
//----Animation getters/setters --------------------------------------------------------
p.eventCallback = function (type, callback, params, scope) {
if ((type || "").substr(0, 2) === "on") {
var v = this.vars;
if (arguments.length === 1) {
return v[type];
}
if (callback == null) {
delete v[type];
} else {
v[type] = callback;
v[type + "Params"] = _isArray(params) && params.join("").indexOf("{self}") !== -1 ? this._swapSelfInParams(params) : params;
v[type + "Scope"] = scope;
}
if (type === "onUpdate") {
this._onUpdate = callback;
}
}
return this;
};
p.delay = function (value) {
if (!arguments.length) {
return this._delay;
}
if (this._timeline.smoothChildTiming) {
this.startTime(this._startTime + value - this._delay);
}
this._delay = value;
return this;
};
p.duration = function (value) {
if (!arguments.length) {
this._dirty = false;
return this._duration;
}
this._duration = this._totalDuration = value;
this._uncache(true); //true in case it's a TweenMax or TimelineMax that has a repeat - we'll need to refresh the totalDuration.
if (this._timeline.smoothChildTiming) if (this._time > 0) if (this._time < this._duration) if (value !== 0) {
this.totalTime(this._totalTime * (value / this._duration), true);
}
return this;
};
p.totalDuration = function (value) {
this._dirty = false;
return !arguments.length ? this._totalDuration : this.duration(value);
};
p.time = function (value, suppressEvents) {
if (!arguments.length) {
return this._time;
}
if (this._dirty) {
this.totalDuration();
}
return this.totalTime(value > this._duration ? this._duration : value, suppressEvents);
};
p.totalTime = function (time, suppressEvents, uncapped) {
if (!_tickerActive) {
_ticker.wake();
}
if (!arguments.length) {
return this._totalTime;
}
if (this._timeline) {
if (time < 0 && !uncapped) {
time += this.totalDuration();
}
if (this._timeline.smoothChildTiming) {
if (this._dirty) {
this.totalDuration();
}
var totalDuration = this._totalDuration,
tl = this._timeline;
if (time > totalDuration && !uncapped) {
time = totalDuration;
}
this._startTime = (this._paused ? this._pauseTime : tl._time) - (!this._reversed ? time : totalDuration - time) / this._timeScale;
if (!tl._dirty) {//for performance improvement. If the parent's cache is already dirty, it already took care of marking the ancestors as dirty too, so skip the function call here.
this._uncache(false);
}
//in case any of the ancestor timelines had completed but should now be enabled, we should reset their totalTime() which will also ensure that they're lined up properly and enabled. Skip for animations that are on the root (wasteful). Example: a TimelineLite.exportRoot() is performed when there's a paused tween on the root, the export will not complete until that tween is unpaused, but imagine a child gets restarted later, after all [unpaused] tweens have completed. The startTime of that child would get pushed out, but one of the ancestors may have completed.
if (tl._timeline) {
while (tl._timeline) {
if (tl._timeline._time !== (tl._startTime + tl._totalTime) / tl._timeScale) {
tl.totalTime(tl._totalTime, true);
}
tl = tl._timeline;
}
}
}
if (this._gc) {
this._enabled(true, false);
}
if (this._totalTime !== time || this._duration === 0) {
if (_lazyTweens.length) {
_lazyRender();
}
this.render(time, suppressEvents, false);
if (_lazyTweens.length) {//in case rendering caused any tweens to lazy-init, we should render them because typically when someone calls seek() or time() or progress(), they expect an immediate render.
_lazyRender();
}
}
}
return this;
};
p.progress = p.totalProgress = function (value, suppressEvents) {
var duration = this.duration();
return !arguments.length ? duration ? this._time / duration : this.ratio : this.totalTime(duration * value, suppressEvents);
};
p.startTime = function (value) {
if (!arguments.length) {
return this._startTime;
}
if (value !== this._startTime) {
this._startTime = value;
if (this.timeline) if (this.timeline._sortChildren) {
this.timeline.add(this, value - this._delay); //ensures that any necessary re-sequencing of Animations in the timeline occurs to make sure the rendering order is correct.
}
}
return this;
};
p.endTime = function (includeRepeats) {
return this._startTime + (includeRepeats != false ? this.totalDuration() : this.duration()) / this._timeScale;
};
p.timeScale = function (value) {
if (!arguments.length) {
return this._timeScale;
}
var pauseTime, t;
value = value || _tinyNum; //can't allow zero because it'll throw the math off
if (this._timeline && this._timeline.smoothChildTiming) {
pauseTime = this._pauseTime;
t = pauseTime || pauseTime === 0 ? pauseTime : this._timeline.totalTime();
this._startTime = t - (t - this._startTime) * this._timeScale / value;
}
this._timeScale = value;
t = this.timeline;
while (t && t.timeline) {//must update the duration/totalDuration of all ancestor timelines immediately in case in the middle of a render loop, one tween alters another tween's timeScale which shoves its startTime before 0, forcing the parent timeline to shift around and shiftChildren() which could affect that next tween's render (startTime). Doesn't matter for the root timeline though.
t._dirty = true;
t.totalDuration();
t = t.timeline;
}
return this;
};
p.reversed = function (value) {
if (!arguments.length) {
return this._reversed;
}
if (value != this._reversed) {
this._reversed = value;
this.totalTime(this._timeline && !this._timeline.smoothChildTiming ? this.totalDuration() - this._totalTime : this._totalTime, true);
}
return this;
};
p.paused = function (value) {
if (!arguments.length) {
return this._paused;
}
var tl = this._timeline,
raw,elapsed;
if (value != this._paused) if (tl) {
if (!_tickerActive && !value) {
_ticker.wake();
}
raw = tl.rawTime();
elapsed = raw - this._pauseTime;
if (!value && tl.smoothChildTiming) {
this._startTime += elapsed;
this._uncache(false);
}
this._pauseTime = value ? raw : null;
this._paused = value;
this._active = this.isActive();
if (!value && elapsed !== 0 && this._initted && this.duration()) {
raw = tl.smoothChildTiming ? this._totalTime : (raw - this._startTime) / this._timeScale;
this.render(raw, raw === this._totalTime, true); //in case the target's properties changed via some other tween or manual update by the user, we should force a render.
}
}
if (this._gc && !value) {
this._enabled(true, false);
}
return this;
};
/*
* ----------------------------------------------------------------
* SimpleTimeline
* ----------------------------------------------------------------
*/
var SimpleTimeline = _class("core.SimpleTimeline", function (vars) {
Animation.call(this, 0, vars);
this.autoRemoveChildren = this.smoothChildTiming = true;
});
p = SimpleTimeline.prototype = new Animation();
p.constructor = SimpleTimeline;
p.kill()._gc = false;
p._first = p._last = p._recent = null;
p._sortChildren = false;
p.add = p.insert = function (child, position, align, stagger) {
var prevTween, st;
child._startTime = Number(position || 0) + child._delay;
if (child._paused) if (this !== child._timeline) {//we only adjust the _pauseTime if it wasn't in this timeline already. Remember, sometimes a tween will be inserted again into the same timeline when its startTime is changed so that the tweens in the TimelineLite/Max are re-ordered properly in the linked list (so everything renders in the proper order).
child._pauseTime = child._startTime + (this.rawTime() - child._startTime) / child._timeScale;
}
if (child.timeline) {
child.timeline._remove(child, true); //removes from existing timeline so that it can be properly added to this one.
}
child.timeline = child._timeline = this;
if (child._gc) {
child._enabled(true, true);
}
prevTween = this._last;
if (this._sortChildren) {
st = child._startTime;
while (prevTween && prevTween._startTime > st) {
prevTween = prevTween._prev;
}
}
if (prevTween) {
child._next = prevTween._next;
prevTween._next = child;
} else {
child._next = this._first;
this._first = child;
}
if (child._next) {
child._next._prev = child;
} else {
this._last = child;
}
child._prev = prevTween;
this._recent = child;
if (this._timeline) {
this._uncache(true);
}
return this;
};
p._remove = function (tween, skipDisable) {
if (tween.timeline === this) {
if (!skipDisable) {
tween._enabled(false, true);
}
if (tween._prev) {
tween._prev._next = tween._next;
} else if (this._first === tween) {
this._first = tween._next;
}
if (tween._next) {
tween._next._prev = tween._prev;
} else if (this._last === tween) {
this._last = tween._prev;
}
tween._next = tween._prev = tween.timeline = null;
if (tween === this._recent) {
this._recent = this._last;
}
if (this._timeline) {
this._uncache(true);
}
}
return this;
};
p.render = function (time, suppressEvents, force) {
var tween = this._first,
next;
this._totalTime = this._time = this._rawPrevTime = time;
while (tween) {
next = tween._next; //record it here because the value could change after rendering...
if (tween._active || time >= tween._startTime && !tween._paused && !tween._gc) {
if (!tween._reversed) {
tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
} else {
tween.render((!tween._dirty ? tween._totalDuration : tween.totalDuration()) - (time - tween._startTime) * tween._timeScale, suppressEvents, force);
}
}
tween = next;
}
};
p.rawTime = function () {
if (!_tickerActive) {
_ticker.wake();
}
return this._totalTime;
};
/*
* ----------------------------------------------------------------
* TweenLite
* ----------------------------------------------------------------
*/
var TweenLite = _class("TweenLite", function (target, duration, vars) {
Animation.call(this, duration, vars);
this.render = TweenLite.prototype.render; //speed optimization (avoid prototype lookup on this "hot" method)
if (target == null) {
throw "Cannot tween a null target.";
}
this.target = target = typeof target !== "string" ? target : TweenLite.selector(target) || target;
var isSelector = target.jquery || target.length && target !== window && target[0] && (target[0] === window || target[0].nodeType && target[0].style && !target.nodeType),
overwrite = this.vars.overwrite,
i,targ,targets;
this._overwrite = overwrite = overwrite == null ? _overwriteLookup[TweenLite.defaultOverwrite] : typeof overwrite === "number" ? overwrite >> 0 : _overwriteLookup[overwrite];
if ((isSelector || target instanceof Array || target.push && _isArray(target)) && typeof target[0] !== "number") {
this._targets = targets = _slice(target); //don't use Array.prototype.slice.call(target, 0) because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll()
this._propLookup = [];
this._siblings = [];
for (i = 0; i < targets.length; i++) {
targ = targets[i];
if (!targ) {
targets.splice(i--, 1);
continue;
} else if (typeof targ === "string") {
targ = targets[i--] = TweenLite.selector(targ); //in case it's an array of strings
if (typeof targ === "string") {
targets.splice(i + 1, 1); //to avoid an endless loop (can't imagine why the selector would return a string, but just in case)
}
continue;
} else if (targ.length && targ !== window && targ[0] && (targ[0] === window || targ[0].nodeType && targ[0].style && !targ.nodeType)) {//in case the user is passing in an array of selector objects (like jQuery objects), we need to check one more level and pull things out if necessary. Also note that <select> elements pass all the criteria regarding length and the first child having style, so we must also check to ensure the target isn't an HTML node itself.
targets.splice(i--, 1);
this._targets = targets = targets.concat(_slice(targ));
continue;
}
this._siblings[i] = _register(targ, this, false);
if (overwrite === 1) if (this._siblings[i].length > 1) {
_applyOverwrite(targ, this, null, 1, this._siblings[i]);
}
}
} else {
this._propLookup = {};
this._siblings = _register(target, this, false);
if (overwrite === 1) if (this._siblings.length > 1) {
_applyOverwrite(target, this, null, 1, this._siblings);
}
}
if (this.vars.immediateRender || duration === 0 && this._delay === 0 && this.vars.immediateRender !== false) {
this._time = -_tinyNum; //forces a render without having to set the render() "force" parameter to true because we want to allow lazying by default (using the "force" parameter always forces an immediate full render)
this.render(Math.min(0, -this._delay)); //in case delay is negative
}
}, true),
_isSelector = function _isSelector(v) {
return v && v.length && v !== window && v[0] && (v[0] === window || v[0].nodeType && v[0].style && !v.nodeType); //we cannot check "nodeType" if the target is window from within an iframe, otherwise it will trigger a security error in some browsers like Firefox.
},
_autoCSS = function _autoCSS(vars, target) {
var css = {},
p;
for (p in vars) {
if (!_reservedProps[p] && (!(p in target) || p === "transform" || p === "x" || p === "y" || p === "width" || p === "height" || p === "className" || p === "border") && (!_plugins[p] || _plugins[p] && _plugins[p]._autoCSS)) {//note: <img> elements contain read-only "x" and "y" properties. We should also prioritize editing css width/height rather than the element's properties.
css[p] = vars[p];
delete vars[p];
}
}
vars.css = css;
};
p = TweenLite.prototype = new Animation();
p.constructor = TweenLite;
p.kill()._gc = false;
//----TweenLite defaults, overwrite management, and root updates ----------------------------------------------------
p.ratio = 0;
p._firstPT = p._targets = p._overwrittenProps = p._startAt = null;
p._notifyPluginsOfEnabled = p._lazy = false;
TweenLite.version = "1.20.4";
TweenLite.defaultEase = p._ease = new Ease(null, null, 1, 1);
TweenLite.defaultOverwrite = "auto";
TweenLite.ticker = _ticker;
TweenLite.autoSleep = 120;
TweenLite.lagSmoothing = function (threshold, adjustedLag) {
_ticker.lagSmoothing(threshold, adjustedLag);
};
TweenLite.selector = window.$ || window.jQuery || function (e) {
var selector = window.$ || window.jQuery;
if (selector) {
TweenLite.selector = selector;
return selector(e);
}
return typeof _doc === "undefined" ? e : _doc.querySelectorAll ? _doc.querySelectorAll(e) : _doc.getElementById(e.charAt(0) === "#" ? e.substr(1) : e);
};
var _lazyTweens = [],
_lazyLookup = {},
_numbersExp = /(?:(-|-=|\+=)?\d*\.?\d*(?:e[\-+]?\d+)?)[0-9]/ig,
_relExp = /[\+-]=-?[\.\d]/,
//_nonNumbersExp = /(?:([\-+](?!(\d|=)))|[^\d\-+=e]|(e(?![\-+][\d])))+/ig,
_setRatio = function _setRatio(v) {
var pt = this._firstPT,
min = 0.000001,
val;
while (pt) {
val = !pt.blob ? pt.c * v + pt.s : v === 1 && this.end != null ? this.end : v ? this.join("") : this.start;
if (pt.m) {
val = pt.m(val, this._target || pt.t);
} else if (val < min) if (val > -min && !pt.blob) {//prevents issues with converting very small numbers to strings in the browser
val = 0;
}
if (!pt.f) {
pt.t[pt.p] = val;
} else if (pt.fp) {
pt.t[pt.p](pt.fp, val);
} else {
pt.t[pt.p](val);
}
pt = pt._next;
}
},
//compares two strings (start/end), finds the numbers that are different and spits back an array representing the whole value but with the changing values isolated as elements. For example, "rgb(0,0,0)" and "rgb(100,50,0)" would become ["rgb(", 0, ",", 50, ",0)"]. Notice it merges the parts that are identical (performance optimization). The array also has a linked list of PropTweens attached starting with _firstPT that contain the tweening data (t, p, s, c, f, etc.). It also stores the starting value as a "start" property so that we can revert to it if/when necessary, like when a tween rewinds fully. If the quantity of numbers differs between the start and end, it will always prioritize the end value(s). The pt parameter is optional - it's for a PropTween that will be appended to the end of the linked list and is typically for actually setting the value after all of the elements have been updated (with array.join("")).
_blobDif = function _blobDif(start, end, filter, pt) {
var a = [],
charIndex = 0,
s = "",
color = 0,
startNums,endNums,num,i,l,nonNumbers,currentNum;
a.start = start;
a.end = end;
start = a[0] = start + ""; //ensure values are strings
end = a[1] = end + "";
if (filter) {
filter(a); //pass an array with the starting and ending values and let the filter do whatever it needs to the values.
start = a[0];
end = a[1];
}
a.length = 0;
startNums = start.match(_numbersExp) || [];
endNums = end.match(_numbersExp) || [];
if (pt) {
pt._next = null;
pt.blob = 1;
a._firstPT = a._applyPT = pt; //apply last in the linked list (which means inserting it first)
}
l = endNums.length;
for (i = 0; i < l; i++) {
currentNum = endNums[i];
nonNumbers = end.substr(charIndex, end.indexOf(currentNum, charIndex) - charIndex);
s += nonNumbers || !i ? nonNumbers : ","; //note: SVG spec allows omission of comma/space when a negative sign is wedged between two numbers, like 2.5-5.3 instead of 2.5,-5.3 but when tweening, the negative value may switch to positive, so we insert the comma just in case.
charIndex += nonNumbers.length;
if (color) {//sense rgba() values and round them.
color = (color + 1) % 5;
} else if (nonNumbers.substr(-5) === "rgba(") {
color = 1;
}
if (currentNum === startNums[i] || startNums.length <= i) {
s += currentNum;
} else {
if (s) {
a.push(s);
s = "";
}
num = parseFloat(startNums[i]);
a.push(num);
a._firstPT = { _next: a._firstPT, t: a, p: a.length - 1, s: num, c: (currentNum.charAt(1) === "=" ? parseInt(currentNum.charAt(0) + "1", 10) * parseFloat(currentNum.substr(2)) : parseFloat(currentNum) - num) || 0, f: 0, m: color && color < 4 ? Math.round : 0 };
//note: we don't set _prev because we'll never need to remove individual PropTweens from this list.
}
charIndex += currentNum.length;
}
s += end.substr(charIndex);
if (s) {
a.push(s);
}
a.setRatio = _setRatio;
if (_relExp.test(end)) {//if the end string contains relative values, delete it so that on the final render (in _setRatio()), we don't actually set it to the string with += or -= characters (forces it to use the calculated value).
a.end = null;
}
return a;
},
//note: "funcParam" is only necessary for function-based getters/setters that require an extra parameter like getAttribute("width") and setAttribute("width", value). In this example, funcParam would be "width". Used by AttrPlugin for example.
_addPropTween = function _addPropTween(target, prop, start, end, overwriteProp, mod, funcParam, stringFilter, index) {
if (typeof end === "function") {
end = end(index || 0, target);
}
var type = _typeof(target[prop]),
getterName = type !== "function" ? "" : prop.indexOf("set") || typeof target["get" + prop.substr(3)] !== "function" ? prop : "get" + prop.substr(3),
s = start !== "get" ? start : !getterName ? target[prop] : funcParam ? target[getterName](funcParam) : target[getterName](),
isRelative = typeof end === "string" && end.charAt(1) === "=",
pt = { t: target, p: prop, s: s, f: type === "function", pg: 0, n: overwriteProp || prop, m: !mod ? 0 : typeof mod === "function" ? mod : Math.round, pr: 0, c: isRelative ? parseInt(end.charAt(0) + "1", 10) * parseFloat(end.substr(2)) : parseFloat(end) - s || 0 },
blob;
if (typeof s !== "number" || typeof end !== "number" && !isRelative) {
if (funcParam || isNaN(s) || !isRelative && isNaN(end) || typeof s === "boolean" || typeof end === "boolean") {
//a blob (string that has multiple numbers in it)
pt.fp = funcParam;
blob = _blobDif(s, isRelative ? parseFloat(pt.s) + pt.c + (pt.s + "").replace(/[0-9\-\.]/g, "") : end, stringFilter || TweenLite.defaultStringFilter, pt);
pt = { t: blob, p: "setRatio", s: 0, c: 1, f: 2, pg: 0, n: overwriteProp || prop, pr: 0, m: 0 }; //"2" indicates it's a Blob property tween. Needed for RoundPropsPlugin for example.
} else {
pt.s = parseFloat(s);
if (!isRelative) {
pt.c = parseFloat(end) - pt.s || 0;
}
}
}
if (pt.c) {//only add it to the linked list if there's a change.
if (pt._next = this._firstPT) {
pt._next._prev = pt;
}
this._firstPT = pt;
return pt;
}
},
_internals = TweenLite._internals = { isArray: _isArray, isSelector: _isSelector, lazyTweens: _lazyTweens, blobDif: _blobDif }, //gives us a way to expose certain private values to other GreenSock classes without contaminating tha main TweenLite object.
_plugins = TweenLite._plugins = {},
_tweenLookup = _internals.tweenLookup = {},
_tweenLookupNum = 0,
_reservedProps = _internals.reservedProps = { ease: 1, delay: 1, overwrite: 1, onComplete: 1, onCompleteParams: 1, onCompleteScope: 1, useFrames: 1, runBackwards: 1, startAt: 1, onUpdate: 1, onUpdateParams: 1, onUpdateScope: 1, onStart: 1, onStartParams: 1, onStartScope: 1, onReverseComplete: 1, onReverseCompleteParams: 1, onReverseCompleteScope: 1, onRepeat: 1, onRepeatParams: 1, onRepeatScope: 1, easeParams: 1, yoyo: 1, immediateRender: 1, repeat: 1, repeatDelay: 1, data: 1, paused: 1, reversed: 1, autoCSS: 1, lazy: 1, onOverwrite: 1, callbackScope: 1, stringFilter: 1, id: 1, yoyoEase: 1 },
_overwriteLookup = { none: 0, all: 1, auto: 2, concurrent: 3, allOnStart: 4, preexisting: 5, "true": 1, "false": 0 },
_rootFramesTimeline = Animation._rootFramesTimeline = new SimpleTimeline(),
_rootTimeline = Animation._rootTimeline = new SimpleTimeline(),
_nextGCFrame = 30,
_lazyRender = _internals.lazyRender = function () {
var i = _lazyTweens.length,
tween;
_lazyLookup = {};
while (--i > -1) {
tween = _lazyTweens[i];
if (tween && tween._lazy !== false) {
tween.render(tween._lazy[0], tween._lazy[1], true);
tween._lazy = false;
}
}
_lazyTweens.length = 0;
};
_rootTimeline._startTime = _ticker.time;
_rootFramesTimeline._startTime = _ticker.frame;
_rootTimeline._active = _rootFramesTimeline._active = true;
setTimeout(_lazyRender, 1); //on some mobile devices, there isn't a "tick" before code runs which means any lazy renders wouldn't run before the next official "tick".
Animation._updateRoot = TweenLite.render = function () {
var i, a, p;
if (_lazyTweens.length) {//if code is run outside of the requestAnimationFrame loop, there may be tweens queued AFTER the engine refreshed, so we need to ensure any pending renders occur before we refresh again.
_lazyRender();
}
_rootTimeline.render((_ticker.time - _rootTimeline._startTime) * _rootTimeline._timeScale, false, false);
_rootFramesTimeline.render((_ticker.frame - _rootFramesTimeline._startTime) * _rootFramesTimeline._timeScale, false, false);
if (_lazyTweens.length) {
_lazyRender();
}
if (_ticker.frame >= _nextGCFrame) {//dump garbage every 120 frames or whatever the user sets TweenLite.autoSleep to
_nextGCFrame = _ticker.frame + (parseInt(TweenLite.autoSleep, 10) || 120);
for (p in _tweenLookup) {
a = _tweenLookup[p].tweens;
i = a.length;
while (--i > -1) {
if (a[i]._gc) {
a.splice(i, 1);
}
}
if (a.length === 0) {
delete _tweenLookup[p];
}
}
//if there are no more tweens in the root timelines, or if they're all paused, make the _timer sleep to reduce load on the CPU slightly
p = _rootTimeline._first;
if (!p || p._paused) if (TweenLite.autoSleep && !_rootFramesTimeline._first && _ticker._listeners.tick.length === 1) {
while (p && p._paused) {
p = p._next;
}
if (!p) {
_ticker.sleep();
}
}
}
};
_ticker.addEventListener("tick", Animation._updateRoot);
var _register = function _register(target, tween, scrub) {
var id = target._gsTweenID,a,i;
if (!_tweenLookup[id || (target._gsTweenID = id = "t" + _tweenLookupNum++)]) {
_tweenLookup[id] = { target: target, tweens: [] };
}
if (tween) {
a = _tweenLookup[id].tweens;
a[i = a.length] = tween;
if (scrub) {
while (--i > -1) {
if (a[i] === tween) {
a.splice(i, 1);
}
}
}
}
return _tweenLookup[id].tweens;
},
_onOverwrite = function _onOverwrite(overwrittenTween, overwritingTween, target, killedProps) {
var func = overwrittenTween.vars.onOverwrite,r1,r2;
if (func) {
r1 = func(overwrittenTween, overwritingTween, target, killedProps);
}
func = TweenLite.onOverwrite;
if (func) {
r2 = func(overwrittenTween, overwritingTween, target, killedProps);
}
return r1 !== false && r2 !== false;
},
_applyOverwrite = function _applyOverwrite(target, tween, props, mode, siblings) {
var i, changed, curTween, l;
if (mode === 1 || mode >= 4) {
l = siblings.length;
for (i = 0; i < l; i++) {
if ((curTween = siblings[i]) !== tween) {
if (!curTween._gc) {
if (curTween._kill(null, target, tween)) {
changed = true;
}
}
} else if (mode === 5) {
break;
}
}
return changed;
}
//NOTE: Add 0.0000000001 to overcome floating point errors that can cause the startTime to be VERY slightly off (when a tween's time() is set for example)
var startTime = tween._startTime + _tinyNum,
overlaps = [],
oCount = 0,
zeroDur = tween._duration === 0,
globalStart;
i = siblings.length;
while (--i > -1) {
if ((curTween = siblings[i]) === tween || curTween._gc || curTween._paused) {
//ignore
} else if (curTween._timeline !== tween._timeline) {
globalStart = globalStart || _checkOverlap(tween, 0, zeroDur);
if (_checkOverlap(curTween, globalStart, zeroDur) === 0) {
overlaps[oCount++] = curTween;
}
} else if (curTween._startTime <= startTime) if (curTween._startTime + curTween.totalDuration() / curTween._timeScale > startTime) if (!((zeroDur || !curTween._initted) && startTime - curTween._startTime <= 0.0000000002)) {
overlaps[oCount++] = curTween;
}
}
i = oCount;
while (--i > -1) {
curTween = overlaps[i];
if (mode === 2) if (curTween._kill(props, target, tween)) {
changed = true;
}
if (mode !== 2 || !curTween._firstPT && curTween._initted) {
if (mode !== 2 && !_onOverwrite(curTween, tween)) {
continue;
}
if (curTween._enabled(false, false)) {//if all property tweens have been overwritten, kill the tween.
changed = true;
}
}
}
return changed;
},
_checkOverlap = function _checkOverlap(tween, reference, zeroDur) {
var tl = tween._timeline,
ts = tl._timeScale,
t = tween._startTime;
while (tl._timeline) {
t += tl._startTime;
ts *= tl._timeScale;
if (tl._paused) {
return -100;
}
tl = tl._timeline;
}
t /= ts;
return t > reference ? t - reference : zeroDur && t === reference || !tween._initted && t - reference < 2 * _tinyNum ? _tinyNum : (t += tween.totalDuration() / tween._timeScale / ts) > reference + _tinyNum ? 0 : t - reference - _tinyNum;
};
//---- TweenLite instance methods -----------------------------------------------------------------------------
p._init = function () {
var v = this.vars,
op = this._overwrittenProps,
dur = this._duration,
immediate = !!v.immediateRender,
ease = v.ease,
i,initPlugins,pt,p,startVars,l;
if (v.startAt) {
if (this._startAt) {
this._startAt.render(-1, true); //if we've run a startAt previously (when the tween instantiated), we should revert it so that the values re-instantiate correctly particularly for relative tweens. Without this, a TweenLite.fromTo(obj, 1, {x:"+=100"}, {x:"-=100"}), for example, would actually jump to +=200 because the startAt would run twice, doubling the relative change.
this._startAt.kill();
}
startVars = {};
for (p in v.startAt) {//copy the properties/values into a new object to avoid collisions, like var to = {x:0}, from = {x:500}; timeline.fromTo(e, 1, from, to).fromTo(e, 1, to, from);
startVars[p] = v.startAt[p];
}
startVars.data = "isStart";
startVars.overwrite = false;
startVars.immediateRender = true;
startVars.lazy = immediate && v.lazy !== false;
startVars.startAt = startVars.delay = null; //no nesting of startAt objects allowed (otherwise it could cause an infinite loop).
startVars.onUpdate = v.onUpdate;
startVars.onUpdateParams = v.onUpdateParams;
startVars.onUpdateScope = v.onUpdateScope || v.callbackScope || this;
this._startAt = TweenLite.to(this.target, 0, startVars);
if (immediate) {
if (this._time > 0) {
this._startAt = null; //tweens that render immediately (like most from() and fromTo() tweens) shouldn't revert when their parent timeline's playhead goes backward past the startTime because the initial render could have happened anytime and it shouldn't be directly correlated to this tween's startTime. Imagine setting up a complex animation where the beginning states of various objects are rendered immediately but the tween doesn't happen for quite some time - if we revert to the starting values as soon as the playhead goes backward past the tween's startTime, it will throw things off visually. Reversion should only happen in TimelineLite/Max instances where immediateRender was false (which is the default in the convenience methods like from()).
} else if (dur !== 0) {
return; //we skip initialization here so that overwriting doesn't occur until the tween actually begins. Otherwise, if you create several immediateRender:true tweens of the same target/properties to drop into a TimelineLite or TimelineMax, the last one created would overwrite the first ones because they didn't get placed into the timeline yet before the first render occurs and kicks in overwriting.
}
}
} else if (v.runBackwards && dur !== 0) {
//from() tweens must be handled uniquely: their beginning values must be rendered but we don't want overwriting to occur yet (when time is still 0). Wait until the tween actually begins before doing all the routines like overwriting. At that time, we should render at the END of the tween to ensure that things initialize correctly (remember, from() tweens go backwards)
if (this._startAt) {
this._startAt.render(-1, true);
this._startAt.kill();
this._startAt = null;
} else {
if (this._time !== 0) {//in rare cases (like if a from() tween runs and then is invalidate()-ed), immediateRender could be true but the initial forced-render gets skipped, so there's no need to force the render in this context when the _time is greater than 0
immediate = false;
}
pt = {};
for (p in v) {//copy props into a new object and skip any reserved props, otherwise onComplete or onUpdate or onStart could fire. We should, however, permit autoCSS to go through.
if (!_reservedProps[p] || p === "autoCSS") {
pt[p] = v[p];
}
}
pt.overwrite = 0;
pt.data = "isFromStart"; //we tag the tween with as "isFromStart" so that if [inside a plugin] we need to only do something at the very END of a tween, we have a way of identifying this tween as merely the one that's setting the beginning values for a "from()" tween. For example, clearProps in CSSPlugin should only get applied at the very END of a tween and without this tag, from(...{height:100, clearProps:"height", delay:1}) would wipe the height at the beginning of the tween and after 1 second, it'd kick back in.
pt.lazy = immediate && v.lazy !== false;
pt.immediateRender = immediate; //zero-duration tweens render immediately by default, but if we're not specifically instructed to render this tween immediately, we should skip this and merely _init() to record the starting values (rendering them immediately would push them to completion which is wasteful in that case - we'd have to render(-1) immediately after)
this._startAt = TweenLite.to(this.target, 0, pt);
if (!immediate) {
this._startAt._init(); //ensures that the initial values are recorded
this._startAt._enabled(false); //no need to have the tween render on the next cycle. Disable it because we'll always manually control the renders of the _startAt tween.
if (this.vars.immediateRender) {
this._startAt = null;
}
} else if (this._time === 0) {
return;
}
}
}
this._ease = ease = !ease ? TweenLite.defaultEase : ease instanceof Ease ? ease : typeof ease === "function" ? new Ease(ease, v.easeParams) : _easeMap[ease] || TweenLite.defaultEase;
if (v.easeParams instanceof Array && ease.config) {
this._ease = ease.config.apply(ease, v.easeParams);
}
this._easeType = this._ease._type;
this._easePower = this._ease._power;
this._firstPT = null;
if (this._targets) {
l = this._targets.length;
for (i = 0; i < l; i++) {
if (this._initProps(this._targets[i], this._propLookup[i] = {}, this._siblings[i], op ? op[i] : null, i)) {
initPlugins = true;
}
}
} else {
initPlugins = this._initProps(this.target, this._propLookup, this._siblings, op, 0);
}
if (initPlugins) {
TweenLite._onPluginEvent("_onInitAllProps", this); //reorders the array in order of priority. Uses a static TweenPlugin method in order to minimize file size in TweenLite
}
if (op) if (!this._firstPT) if (typeof this.target !== "function") {//if all tweening properties have been overwritten, kill the tween. If the target is a function, it's probably a delayedCall so let it live.
this._enabled(false, false);
}
if (v.runBackwards) {
pt = this._firstPT;
while (pt) {
pt.s += pt.c;
pt.c = -pt.c;
pt = pt._next;
}
}
this._onUpdate = v.onUpdate;
this._initted = true;
};
p._initProps = function (target, propLookup, siblings, overwrittenProps, index) {
var p, i, initPlugins, plugin, pt, v;
if (target == null) {
return false;
}
if (_lazyLookup[target._gsTweenID]) {
_lazyRender(); //if other tweens of the same target have recently initted but haven't rendered yet, we've got to force the render so that the starting values are correct (imagine populating a timeline with a bunch of sequential tweens and then jumping to the end)
}
if (!this.vars.css) if (target.style) if (target !== window && target.nodeType) if (_plugins.css) if (this.vars.autoCSS !== false) {//it's so common to use TweenLite/Max to animate the css of DOM elements, we assume that if the target is a DOM element, that's what is intended (a convenience so that users don't have to wrap things in css:{}, although we still recommend it for a slight performance boost and better specificity). Note: we cannot check "nodeType" on the window inside an iframe.
_autoCSS(this.vars, target);
}
for (p in this.vars) {
v = this.vars[p];
if (_reservedProps[p]) {
if (v) if (v instanceof Array || v.push && _isArray(v)) if (v.join("").indexOf("{self}") !== -1) {
this.vars[p] = v = this._swapSelfInParams(v, this);
}
} else if (_plugins[p] && (plugin = new _plugins[p]())._onInitTween(target, this.vars[p], this, index)) {
//t - target [object]
//p - property [string]
//s - start [number]
//c - change [number]
//f - isFunction [boolean]
//n - name [string]
//pg - isPlugin [boolean]
//pr - priority [number]
//m - mod [function | 0]
this._firstPT = pt = { _next: this._firstPT, t: plugin, p: "setRatio", s: 0, c: 1, f: 1, n: p, pg: 1, pr: plugin._priority, m: 0 };
i = plugin._overwriteProps.length;
while (--i > -1) {
propLookup[plugin._overwriteProps[i]] = this._firstPT;
}
if (plugin._priority || plugin._onInitAllProps) {
initPlugins = true;
}
if (plugin._onDisable || plugin._onEnable) {
this._notifyPluginsOfEnabled = true;
}
if (pt._next) {
pt._next._prev = pt;
}
} else {
propLookup[p] = _addPropTween.call(this, target, p, "get", v, p, 0, null, this.vars.stringFilter, index);
}
}
if (overwrittenProps) if (this._kill(overwrittenProps, target)) {//another tween may have tried to overwrite properties of this tween before init() was called (like if two tweens start at the same time, the one created second will run first)
return this._initProps(target, propLookup, siblings, overwrittenProps, index);
}
if (this._overwrite > 1) if (this._firstPT) if (siblings.length > 1) if (_applyOverwrite(target, this, propLookup, this._overwrite, siblings)) {
this._kill(propLookup, target);
return this._initProps(target, propLookup, siblings, overwrittenProps, index);
}
if (this._firstPT) if (this.vars.lazy !== false && this._duration || this.vars.lazy && !this._duration) {//zero duration tweens don't lazy render by default; everything else does.
_lazyLookup[target._gsTweenID] = true;
}
return initPlugins;
};
p.render = function (time, suppressEvents, force) {
var prevTime = this._time,
duration = this._duration,
prevRawPrevTime = this._rawPrevTime,
isComplete,callback,pt,rawPrevTime;
if (time >= duration - 0.0000001 && time >= 0) {//to work around occasional floating point math artifacts.
this._totalTime = this._time = duration;
this.ratio = this._ease._calcEnd ? this._ease.getRatio(1) : 1;
if (!this._reversed) {
isComplete = true;
callback = "onComplete";
force = force || this._timeline.autoRemoveChildren; //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline.
}
if (duration === 0) if (this._initted || !this.vars.lazy || force) {//zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered.
if (this._startTime === this._timeline._duration) {//if a zero-duration tween is at the VERY end of a timeline and that timeline renders at its end, it will typically add a tiny bit of cushion to the render time to prevent rounding errors from getting in the way of tweens rendering their VERY end. If we then reverse() that timeline, the zero-duration tween will trigger its onReverseComplete even though technically the playhead didn't pass over it again. It's a very specific edge case we must accommodate.
time = 0;
}
if (prevRawPrevTime < 0 || time <= 0 && time >= -0.0000001 || prevRawPrevTime === _tinyNum && this.data !== "isPause") if (prevRawPrevTime !== time) {//note: when this.data is "isPause", it's a callback added by addPause() on a timeline that we should not be triggered when LEAVING its exact start time. In other words, tl.addPause(1).play(1) shouldn't pause.
force = true;
if (prevRawPrevTime > _tinyNum) {
callback = "onReverseComplete";
}
}
this._rawPrevTime = rawPrevTime = !suppressEvents || time || prevRawPrevTime === time ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
}
} else if (time < 0.0000001) {//to work around occasional floating point math artifacts, round super small values to 0.
this._totalTime = this._time = 0;
this.ratio = this._ease._calcEnd ? this._ease.getRatio(0) : 0;
if (prevTime !== 0 || duration === 0 && prevRawPrevTime > 0) {
callback = "onReverseComplete";
isComplete = this._reversed;
}
if (time < 0) {
this._active = false;
if (duration === 0) if (this._initted || !this.vars.lazy || force) {//zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered.
if (prevRawPrevTime >= 0 && !(prevRawPrevTime === _tinyNum && this.data === "isPause")) {
force = true;
}
this._rawPrevTime = rawPrevTime = !suppressEvents || time || prevRawPrevTime === time ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
}
}
if (!this._initted || this._startAt && this._startAt.progress()) {//if we render the very beginning (time == 0) of a fromTo(), we must force the render (normal tweens wouldn't need to render at a time of 0 when the prevTime was also 0). This is also mandatory to make sure overwriting kicks in immediately. Also, we check progress() because if startAt has already rendered at its end, we should force a render at its beginning. Otherwise, if you put the playhead directly on top of where a fromTo({immediateRender:false}) starts, and then move it backwards, the from() won't revert its values.
force = true;
}
} else {
this._totalTime = this._time = time;
if (this._easeType) {
var r = time / duration,type = this._easeType,pow = this._easePower;
if (type === 1 || type === 3 && r >= 0.5) {
r = 1 - r;
}
if (type === 3) {
r *= 2;
}
if (pow === 1) {
r *= r;
} else if (pow === 2) {
r *= r * r;
} else if (pow === 3) {
r *= r * r * r;
} else if (pow === 4) {
r *= r * r * r * r;
}
if (type === 1) {
this.ratio = 1 - r;
} else if (type === 2) {
this.ratio = r;
} else if (time / duration < 0.5) {
this.ratio = r / 2;
} else {
this.ratio = 1 - r / 2;
}
} else {
this.ratio = this._ease.getRatio(time / duration);
}
}
if (this._time === prevTime && !force) {
return;
} else if (!this._initted) {
this._init();
if (!this._initted || this._gc) {//immediateRender tweens typically won't initialize until the playhead advances (_time is greater than 0) in order to ensure that overwriting occurs properly. Also, if all of the tweening properties have been overwritten (which would cause _gc to be true, as set in _init()), we shouldn't continue otherwise an onStart callback could be called for example.
return;
} else if (!force && this._firstPT && (this.vars.lazy !== false && this._duration || this.vars.lazy && !this._duration)) {
this._time = this._totalTime = prevTime;
this._rawPrevTime = prevRawPrevTime;
_lazyTweens.push(this);
this._lazy = [time, suppressEvents];
return;
}
//_ease is initially set to defaultEase, so now that init() has run, _ease is set properly and we need to recalculate the ratio. Overall this is faster than using conditional logic earlier in the method to avoid having to set ratio twice because we only init() once but renderTime() gets called VERY frequently.
if (this._time && !isComplete) {
this.ratio = this._ease.getRatio(this._time / duration);
} else if (isComplete && this._ease._calcEnd) {
this.ratio = this._ease.getRatio(this._time === 0 ? 0 : 1);
}
}
if (this._lazy !== false) {//in case a lazy render is pending, we should flush it because the new render is occurring now (imagine a lazy tween instantiating and then immediately the user calls tween.seek(tween.duration()), skipping to the end - the end render would be forced, and then if we didn't flush the lazy render, it'd fire AFTER the seek(), rendering it at the wrong time.
this._lazy = false;
}
if (!this._active) if (!this._paused && this._time !== prevTime && time >= 0) {
this._active = true; //so that if the user renders a tween (as opposed to the timeline rendering it), the timeline is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the tween already finished but the user manually re-renders it as halfway done.
}
if (prevTime === 0) {
if (this._startAt) {
if (time >= 0) {
this._startAt.render(time, true, force);
} else if (!callback) {
callback = "_dummyGS"; //if no callback is defined, use a dummy value just so that the condition at the end evaluates as true because _startAt should render AFTER the normal render loop when the time is negative. We could handle this in a more intuitive way, of course, but the render loop is the MOST important thing to optimize, so this technique allows us to avoid adding extra conditional logic in a high-frequency area.
}
}
if (this.vars.onStart) if (this._time !== 0 || duration === 0) if (!suppressEvents) {
this._callback("onStart");
}
}
pt = this._firstPT;
while (pt) {
if (pt.f) {
pt.t[pt.p](pt.c * this.ratio + pt.s);
} else {
pt.t[pt.p] = pt.c * this.ratio + pt.s;
}
pt = pt._next;
}
if (this._onUpdate) {
if (time < 0) if (this._startAt && time !== -0.0001) {//if the tween is positioned at the VERY beginning (_startTime 0) of its parent timeline, it's illegal for the playhead to go back further, so we should not render the recorded startAt values.
this._startAt.render(time, true, force); //note: for performance reasons, we tuck this conditional logic inside less traveled areas (most tweens don't have an onUpdate). We'd just have it at the end before the onComplete, but the values should be updated before any onUpdate is called, so we ALSO put it here and then if it's not called, we do so later near the onComplete.
}
if (!suppressEvents) if (this._time !== prevTime || isComplete || force) {
this._callback("onUpdate");
}
}
if (callback) if (!this._gc || force) {//check _gc because there's a chance that kill() could be called in an onUpdate
if (time < 0 && this._startAt && !this._onUpdate && time !== -0.0001) {//-0.0001 is a special value that we use when looping back to the beginning of a repeated TimelineMax, in which case we shouldn't render the _startAt values.
this._startAt.render(time, true, force);
}
if (isComplete) {
if (this._timeline.autoRemoveChildren) {
this._enabled(false, false);
}
this._active = false;
}
if (!suppressEvents && this.vars[callback]) {
this._callback(callback);
}
if (duration === 0 && this._rawPrevTime === _tinyNum && rawPrevTime !== _tinyNum) {//the onComplete or onReverseComplete could trigger movement of the playhead and for zero-duration tweens (which must discern direction) that land directly back on their start time, we don't want to fire again on the next render. Think of several addPause()'s in a timeline that forces the playhead to a certain spot, but what if it's already paused and another tween is tweening the "time" of the timeline? Each time it moves [forward] past that spot, it would move back, and since suppressEvents is true, it'd reset _rawPrevTime to _tinyNum so that when it begins again, the callback would fire (so ultimately it could bounce back and forth during that tween). Again, this is a very uncommon scenario, but possible nonetheless.
this._rawPrevTime = 0;
}
}
};
p._kill = function (vars, target, overwritingTween) {
if (vars === "all") {
vars = null;
}
if (vars == null) if (target == null || target === this.target) {
this._lazy = false;
return this._enabled(false, false);
}
target = typeof target !== "string" ? target || this._targets || this.target : TweenLite.selector(target) || target;
var simultaneousOverwrite = overwritingTween && this._time && overwritingTween._startTime === this._startTime && this._timeline === overwritingTween._timeline,
i,overwrittenProps,p,pt,propLookup,changed,killProps,record,killed;
if ((_isArray(target) || _isSelector(target)) && typeof target[0] !== "number") {
i = target.length;
while (--i > -1) {
if (this._kill(vars, target[i], overwritingTween)) {
changed = true;
}
}
} else {
if (this._targets) {
i = this._targets.length;
while (--i > -1) {
if (target === this._targets[i]) {
propLookup = this._propLookup[i] || {};
this._overwrittenProps = this._overwrittenProps || [];
overwrittenProps = this._overwrittenProps[i] = vars ? this._overwrittenProps[i] || {} : "all";
break;
}
}
} else if (target !== this.target) {
return false;
} else {
propLookup = this._propLookup;
overwrittenProps = this._overwrittenProps = vars ? this._overwrittenProps || {} : "all";
}
if (propLookup) {
killProps = vars || propLookup;
record = vars !== overwrittenProps && overwrittenProps !== "all" && vars !== propLookup && ((typeof vars === "undefined" ? "undefined" : _typeof(vars)) !== "object" || !vars._tempKill); //_tempKill is a super-secret way to delete a particular tweening property but NOT have it remembered as an official overwritten property (like in BezierPlugin)
if (overwritingTween && (TweenLite.onOverwrite || this.vars.onOverwrite)) {
for (p in killProps) {
if (propLookup[p]) {
if (!killed) {
killed = [];
}
killed.push(p);
}
}
if ((killed || !vars) && !_onOverwrite(this, overwritingTween, target, killed)) {//if the onOverwrite returned false, that means the user wants to override the overwriting (cancel it).
return false;
}
}
for (p in killProps) {
if (pt = propLookup[p]) {
if (simultaneousOverwrite) {//if another tween overwrites this one and they both start at exactly the same time, yet this tween has already rendered once (for example, at 0.001) because it's first in the queue, we should revert the values to where they were at 0 so that the starting values aren't contaminated on the overwriting tween.
if (pt.f) {
pt.t[pt.p](pt.s);
} else {
pt.t[pt.p] = pt.s;
}
changed = true;
}
if (pt.pg && pt.t._kill(killProps)) {
changed = true; //some plugins need to be notified so they can perform cleanup tasks first
}
if (!pt.pg || pt.t._overwriteProps.length === 0) {
if (pt._prev) {
pt._prev._next = pt._next;
} else if (pt === this._firstPT) {
this._firstPT = pt._next;
}
if (pt._next) {
pt._next._prev = pt._prev;
}
pt._next = pt._prev = null;
}
delete propLookup[p];
}
if (record) {
overwrittenProps[p] = 1;
}
}
if (!this._firstPT && this._initted) {//if all tweening properties are killed, kill the tween. Without this line, if there's a tween with multiple targets and then you killTweensOf() each target individually, the tween would technically still remain active and fire its onComplete even though there aren't any more properties tweening.
this._enabled(false, false);
}
}
}
return changed;
};
p.invalidate = function () {
if (this._notifyPluginsOfEnabled) {
TweenLite._onPluginEvent("_onDisable", this);
}
this._firstPT = this._overwrittenProps = this._startAt = this._onUpdate = null;
this._notifyPluginsOfEnabled = this._active = this._lazy = false;
this._propLookup = this._targets ? {} : [];
Animation.prototype.invalidate.call(this);
if (this.vars.immediateRender) {
this._time = -_tinyNum; //forces a render without having to set the render() "force" parameter to true because we want to allow lazying by default (using the "force" parameter always forces an immediate full render)
this.render(Math.min(0, -this._delay)); //in case delay is negative.
}
return this;
};
p._enabled = function (enabled, ignoreTimeline) {
if (!_tickerActive) {
_ticker.wake();
}
if (enabled && this._gc) {
var targets = this._targets,
i;
if (targets) {
i = targets.length;
while (--i > -1) {
this._siblings[i] = _register(targets[i], this, true);
}
} else {
this._siblings = _register(this.target, this, true);
}
}
Animation.prototype._enabled.call(this, enabled, ignoreTimeline);
if (this._notifyPluginsOfEnabled) if (this._firstPT) {
return TweenLite._onPluginEvent(enabled ? "_onEnable" : "_onDisable", this);
}
return false;
};
//----TweenLite static methods -----------------------------------------------------
TweenLite.to = function (target, duration, vars) {
return new TweenLite(target, duration, vars);
};
TweenLite.from = function (target, duration, vars) {
vars.runBackwards = true;
vars.immediateRender = vars.immediateRender != false;
return new TweenLite(target, duration, vars);
};
TweenLite.fromTo = function (target, duration, fromVars, toVars) {
toVars.startAt = fromVars;
toVars.immediateRender = toVars.immediateRender != false && fromVars.immediateRender != false;
return new TweenLite(target, duration, toVars);
};
TweenLite.delayedCall = function (delay, callback, params, scope, useFrames) {
return new TweenLite(callback, 0, { delay: delay, onComplete: callback, onCompleteParams: params, callbackScope: scope, onReverseComplete: callback, onReverseCompleteParams: params, immediateRender: false, lazy: false, useFrames: useFrames, overwrite: 0 });
};
TweenLite.set = function (target, vars) {
return new TweenLite(target, 0, vars);
};
TweenLite.getTweensOf = function (target, onlyActive) {
if (target == null) {return [];}
target = typeof target !== "string" ? target : TweenLite.selector(target) || target;
var i, a, j, t;
if ((_isArray(target) || _isSelector(target)) && typeof target[0] !== "number") {
i = target.length;
a = [];
while (--i > -1) {
a = a.concat(TweenLite.getTweensOf(target[i], onlyActive));
}
i = a.length;
//now get rid of any duplicates (tweens of arrays of objects could cause duplicates)
while (--i > -1) {
t = a[i];
j = i;
while (--j > -1) {
if (t === a[j]) {
a.splice(i, 1);
}
}
}
} else if (target._gsTweenID) {
a = _register(target).concat();
i = a.length;
while (--i > -1) {
if (a[i]._gc || onlyActive && !a[i].isActive()) {
a.splice(i, 1);
}
}
}
return a || [];
};
TweenLite.killTweensOf = TweenLite.killDelayedCallsTo = function (target, onlyActive, vars) {
if ((typeof onlyActive === "undefined" ? "undefined" : _typeof(onlyActive)) === "object") {
vars = onlyActive; //for backwards compatibility (before "onlyActive" parameter was inserted)
onlyActive = false;
}
var a = TweenLite.getTweensOf(target, onlyActive),
i = a.length;
while (--i > -1) {
a[i]._kill(vars, target);
}
};
/*
* ----------------------------------------------------------------
* TweenPlugin (could easily be split out as a separate file/class, but included for ease of use (so that people don't need to include another script call before loading plugins which is easy to forget)
* ----------------------------------------------------------------
*/
var TweenPlugin = _class("plugins.TweenPlugin", function (props, priority) {
this._overwriteProps = (props || "").split(",");
this._propName = this._overwriteProps[0];
this._priority = priority || 0;
this._super = TweenPlugin.prototype;
}, true);
p = TweenPlugin.prototype;
TweenPlugin.version = "1.19.0";
TweenPlugin.API = 2;
p._firstPT = null;
p._addTween = _addPropTween;
p.setRatio = _setRatio;
p._kill = function (lookup) {
var a = this._overwriteProps,
pt = this._firstPT,
i;
if (lookup[this._propName] != null) {
this._overwriteProps = [];
} else {
i = a.length;
while (--i > -1) {
if (lookup[a[i]] != null) {
a.splice(i, 1);
}
}
}
while (pt) {
if (lookup[pt.n] != null) {
if (pt._next) {
pt._next._prev = pt._prev;
}
if (pt._prev) {
pt._prev._next = pt._next;
pt._prev = null;
} else if (this._firstPT === pt) {
this._firstPT = pt._next;
}
}
pt = pt._next;
}
return false;
};
p._mod = p._roundProps = function (lookup) {
var pt = this._firstPT,
val;
while (pt) {
val = lookup[this._propName] || pt.n != null && lookup[pt.n.split(this._propName + "_").join("")];
if (val && typeof val === "function") {//some properties that are very plugin-specific add a prefix named after the _propName plus an underscore, so we need to ignore that extra stuff here.
if (pt.f === 2) {
pt.t._applyPT.m = val;
} else {
pt.m = val;
}
}
pt = pt._next;
}
};
TweenLite._onPluginEvent = function (type, tween) {
var pt = tween._firstPT,
changed,pt2,first,last,next;
if (type === "_onInitAllProps") {
//sorts the PropTween linked list in order of priority because some plugins need to render earlier/later than others, like MotionBlurPlugin applies its effects after all x/y/alpha tweens have rendered on each frame.
while (pt) {
next = pt._next;
pt2 = first;
while (pt2 && pt2.pr > pt.pr) {
pt2 = pt2._next;
}
if (pt._prev = pt2 ? pt2._prev : last) {
pt._prev._next = pt;
} else {
first = pt;
}
if (pt._next = pt2) {
pt2._prev = pt;
} else {
last = pt;
}
pt = next;
}
pt = tween._firstPT = first;
}
while (pt) {
if (pt.pg) if (typeof pt.t[type] === "function") if (pt.t[type]()) {
changed = true;
}
pt = pt._next;
}
return changed;
};
TweenPlugin.activate = function (plugins) {
var i = plugins.length;
while (--i > -1) {
if (plugins[i].API === TweenPlugin.API) {
_plugins[new plugins[i]()._propName] = plugins[i];
}
}
return true;
};
//provides a more concise way to define plugins that have no dependencies besides TweenPlugin and TweenLite, wrapping common boilerplate stuff into one function (added in 1.9.0). You don't NEED to use this to define a plugin - the old way still works and can be useful in certain (rare) situations.
_gsDefine.plugin = function (config) {
if (!config || !config.propName || !config.init || !config.API) {throw "illegal plugin definition.";}
var propName = config.propName,
priority = config.priority || 0,
overwriteProps = config.overwriteProps,
map = { init: "_onInitTween", set: "setRatio", kill: "_kill", round: "_mod", mod: "_mod", initAll: "_onInitAllProps" },
Plugin = _class("plugins." + propName.charAt(0).toUpperCase() + propName.substr(1) + "Plugin",
function () {
TweenPlugin.call(this, propName, priority);
this._overwriteProps = overwriteProps || [];
}, config.global === true),
p = Plugin.prototype = new TweenPlugin(propName),
prop;
p.constructor = Plugin;
Plugin.API = config.API;
for (prop in map) {
if (typeof config[prop] === "function") {
p[map[prop]] = config[prop];
}
}
Plugin.version = config.version;
TweenPlugin.activate([Plugin]);
return Plugin;
};
//now run through all the dependencies discovered and if any are missing, log that to the console as a warning. This is why it's best to have TweenLite load last - it can check all the dependencies for you.
a = window._gsQueue;
if (a) {
for (i = 0; i < a.length; i++) {
a[i]();
}
for (p in _defLookup) {
if (!_defLookup[p].func) {
window.console.log("GSAP encountered missing dependency: " + p);
}
}
}
_tickerActive = false; //ensures that the first official animation forces a ticker.tick() to update the time when it is instantiated
})(typeof module !== "undefined" && module.exports && typeof global !== "undefined" ? global : undefined || window, "TweenLite");
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"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;};}(); /* jshint esversion: 6, browser: true, devel: true, indent: 2, curly: true, eqeqeq: true, futurehostile: true, latedef: true, undef: true, unused: true */
/* global $, document */
// Import dependencies
// Import style
__webpack_require__(6);var _shop = __webpack_require__(7);var _shop2 = _interopRequireDefault(_shop);var _ajaxy = __webpack_require__(11);var _ajaxy2 = _interopRequireDefault(_ajaxy);var _stockists = __webpack_require__(12);var _stockists2 = _interopRequireDefault(_stockists);var _cube = __webpack_require__(13);var _cube2 = _interopRequireDefault(_cube);var _mailchimp = __webpack_require__(14);var _mailchimp2 = _interopRequireDefault(_mailchimp);var _ageCheck = __webpack_require__(15);var _ageCheck2 = _interopRequireDefault(_ageCheck);var _lazysizes = __webpack_require__(17);var _lazysizes2 = _interopRequireDefault(_lazysizes);var _scrollmagic = __webpack_require__(2);var _scrollmagic2 = _interopRequireDefault(_scrollmagic);var _animationGsap = __webpack_require__(19);var _animationGsap2 = _interopRequireDefault(_animationGsap);var _gsap = __webpack_require__(3);var _gsap2 = _interopRequireDefault(_gsap);__webpack_require__(21);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function _classCallCheck(instance, Constructor) {if (!(instance instanceof Constructor)) {throw new TypeError("Cannot call a class as a function");}}var
Site = function () {
function Site() {_classCallCheck(this, Site);
this.mobileThreshold = 601;
$(window).
resize(this.onResize.bind(this)).
on('ajaxySuccess', this.onReady.bind(this));
$(document).ready(this.onReady.bind(this));
}_createClass(Site, [{ key: 'onReady', value: function onReady()
{
_lazysizes2.default.init();
this.$window = $(window);
this.$document = $(document);
this.$body = $('body');
this.$header = $('#header');
this.$mainContent = $('.main-content');
this.$headerSpacer = $('.header-spacer');
this.$covervidVideo = $('.covervid-video');
this.windowHeight = this.$window.outerHeight();
this.bindMobileNavTrigger();
this.initCoverVid();
this.animateBottleSprite();
} }, { key: 'onResize', value: function onResize()
{
} }, { key: 'fixWidows', value: function fixWidows()
{
// utility class mainly for use on headines to avoid widows [single words on a new line]
$('.js-fix-widows').each(function () {
var string = $(this).html();
string = string.replace(/ ([^ ]*)$/, ' $1');
$(this).html(string);
});
} }, { key: 'initCoverVid', value: function initCoverVid()
{
if (this.$covervidVideo.length) {
this.$covervidVideo.each(function (index, element) {
$(element).coverVid(1920, 1080).addClass('show');
});
}
} }, { key: 'bindMobileNavTrigger', value: function bindMobileNavTrigger()
{var _this = this;
var $mobileNav = $('#mobile-nav');
$('.js-mobile-nav-toggle').on('click', function () {
_this.$body.toggleClass('mobile-active');
});
} }, { key: 'animateBottleSprite', value: function animateBottleSprite()
{
if ($('#bottle-sprite').length) {
var controller = new _scrollmagic2.default.Controller();
// create Tween
var tween = _gsap2.default.to("#bottle-sprite", 1.0, {
backgroundPosition: "100% 0", // property we're stepping to
ease: SteppedEase.config(99) // 100 frames - 1
});
// build scene
var scene = new _scrollmagic2.default.Scene({ duration: this.windowHeight }).
triggerElement('#bottle-sprite').
triggerHook("onCenter").
setTween(tween).
addTo(controller);
}
} }]);return Site;}();
var Material = new Site();
var MaterialShop = new _shop2.default();
var MaterialAjaxy = new _ajaxy2.default();
var MaterialStockists = new _stockists2.default();
var MaterialCube = new _cube2.default();
var MaterialMailchimp = new _mailchimp2.default();
var MaterialAgeCheck = new _ageCheck2.default(MaterialMailchimp.handleMailchimpAjax);
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _coverVid = function _coverVid(elem, width, height) {
// call sizeVideo on load
sizeVideo();
// debounce for resize function
function debounce(fn, delay) {
var timer = null;
return function () {
var context = this,
args = arguments;
window.clearTimeout(timer);
timer = window.setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
// call sizeVideo on resize
window.addEventListener('resize', debounce(sizeVideo, 50));
// Set necessary styles to position video "center center"
elem.style.position = 'absolute';
elem.style.top = '50%';
elem.style.left = '50%';
elem.style['-webkit-transform'] = 'translate(-50%, -50%)';
elem.style['-ms-transform'] = 'translate(-50%, -50%)';
elem.style.transform = 'translate(-50%, -50%)';
// Set overflow hidden on parent element
elem.parentNode.style.overflow = 'hidden';
// Get image defined on poster attribute of video
var posterImage = elem.getAttribute('poster');
// Remove poster to disable
elem.removeAttribute('poster');
// Set poster image as a background cover image on parent element
elem.parentNode.style.backgroundImage = 'url(' + posterImage + ')';
elem.parentNode.style.backgroundSize = 'cover';
elem.parentNode.style.backgroundPosition = 'center center';
// Define the attached selector
function sizeVideo() {
// Get parent element height and width
var parentHeight = elem.parentNode.offsetHeight;
var parentWidth = elem.parentNode.offsetWidth;
// Get native video width and height
var nativeWidth = width;
var nativeHeight = height;
// Get the scale factors
var heightScaleFactor = parentHeight / nativeHeight;
var widthScaleFactor = parentWidth / nativeWidth;
// Based on highest scale factor set width and height
if (widthScaleFactor > heightScaleFactor) {
elem.style.height = 'auto';
elem.style.width = parentWidth + 'px';
} else {
elem.style.height = parentHeight + 'px';
elem.style.width = 'auto';
}
}
// Check for video support
var supportsVideo = typeof elem.canPlayType != 'undefined' ? true : false;
// Check if mobile
var isMobile = false;
if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0, 4)))
isMobile = true;
// Remove video if not supported or mobile
if (!supportsVideo || isMobile) {
elem && elem.parentNode && elem.parentNode.removeChild(elem);
}
};
if (window.jQuery) {
jQuery.fn.extend({
'coverVid': function coverVid() {
_coverVid(this[0], arguments[0], arguments[1]);
return this;
} });
}
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });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;};}(); /* jshint esversion: 6, browser: true, devel: true, indent: 2, curly: true, eqeqeq: true, futurehostile: true, latedef: true, undef: true, unused: true */
/* global $, document, WP */
var _shopifyBuy = __webpack_require__(8);var _shopifyBuy2 = _interopRequireDefault(_shopifyBuy);
var _jsCookie = __webpack_require__(1);var _jsCookie2 = _interopRequireDefault(_jsCookie);
var _slickCarousel = __webpack_require__(9);var _slickCarousel2 = _interopRequireDefault(_slickCarousel);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function _classCallCheck(instance, Constructor) {if (!(instance instanceof Constructor)) {throw new TypeError("Cannot call a class as a function");}}var
Shop = function () {
function Shop() {_classCallCheck(this, Shop);
this.mobileThreshold = 601;
$(window).
resize(this.onResize.bind(this)) // Bind resize
.on('ajaxySuccess', this.onReady.bind(this)); // Bind ajaxSuccess (custom event, comes from Ajaxy)
$(document).ready(this.onReady.bind(this));
}_createClass(Shop, [{ key: 'onResize', value: function onResize()
{
} }, { key: 'onReady', value: function onReady()
{
// Check shopify api data
if (WP.shopify.domain !== null && WP.shopify.storefrontAccessToken !== null) {var _WP$shopify =
WP.shopify,domain = _WP$shopify.domain,storefrontAccessToken = _WP$shopify.storefrontAccessToken;
// Init Shopify client
this.client = _shopifyBuy2.default.buildClient({
domain: domain,
storefrontAccessToken: storefrontAccessToken });
this.initCheckout();
if ($('.single-product').length) {// Single product page
this.initSingleProduct();
}
if ($('#cart').length) {// Cart is present
this.bindCartToggle();
this.initCartSection();
}
this.initCarousel();
} else {
console.error('Shopify URL and/or token missing');
}
} }, { key: 'bindCartToggle', value: function bindCartToggle()
{
$('.js-cart-toggle').on('click', function () {
$('#cart').toggleClass('active');
});
}
/**
* Init the Shopify checkout, current or new
*/ }, { key: 'initCheckout', value: function initCheckout()
{var _this = this;
// Get cart link DOM elements
this.$cartCounter = $('#cart-counter');
// Get shopifyCheckoutId from cookies
var checkoutId = _jsCookie2.default.get('shopifyCheckoutId');
// If shopifyCheckoutId already exists (means there was already a cart initiated before)
if (checkoutId) {
// Fetch existing checkout by its checkoutId
this.client.checkout.fetch(checkoutId).
then(function (checkout) {
// Do something with the checkout
// console.log('EXISTING CHECKOUT', checkout);
// Save the checkout in object
_this.checkout = checkout;
// Update cart display
_this.updateCart(checkout);
}).catch(function (error) {
console.log(error);
});
} else {// Non existing checkout
// Create an empty checkout
this.client.checkout.create().
then(function (checkout) {
// Do something with the checkout
// console.log('EMPTY CHECKOUT CREATED', checkout);
// Save checkout in object
_this.checkout = checkout;
// Save the shopifyCheckoutId in a cookie
_jsCookie2.default.set('shopifyCheckoutId', checkout.id, { expires: 7 }); // Expires in 7 days
});
}
} }, { key: 'initSingleProduct', value: function initSingleProduct()
{
this.productHandle = $('#shopify-handle').attr('data-shopify-handle');
if (this.productHandle) {
this.fetchProductMeta(this.productHandle);
}
} }, { key: 'initCartSection', value: function initCartSection()
{
// Get DOM elements
this.$itemsContainer = $('#items-container');
this.$checkoutContainer = $('#checkout-container');
this.$subtotalContainer = $('#subtotal-container');
// Bind functions
this.handleCartQuantity = this.handleCartQuantity.bind(this); // Bind the quantity selector
this.handleRemoveItems = this.handleRemoveItems.bind(this); // Bind remove item button
}
/**
* Fetch a product data from shopiy
* @param {string} productHandle - The product handle
*/ }, { key: 'fetchProductMeta', value: function fetchProductMeta(
productHandle) {var _this2 = this;
// Fetch data from shopify. Returns a promise
this.client.product.fetchByHandle(productHandle).
then(function (product) {
// Get DOM elements
_this2.$price = $('.single-product-price');
_this2.$quantitySelect = $('#quantity');
_this2.$quantityLabel = $('#quantity-select-label');
_this2.$variationSelect = $('#variation-select');
_this2.$variationLabel = $('#variation-select-label');
// Display price
_this2.showPrice(product, _this2.$price);
// Generate variation selector
_this2.generateOptions(product);
// Bind functions
_this2.handleAddToCart = _this2.handleAddToCart.bind(_this2, product);
// Bind AddToCart button
$('.add-to-cart').on('click', _this2.handleAddToCart);
}).
catch(function (error) {
console.log(error);
});
}
/**
* Update cart
* @param {object} checkout - The updated shopify checkout object
*/ }, { key: 'updateCart', value: function updateCart(
checkout) {var
lineItems = checkout.lineItems,webUrl = checkout.webUrl,subtotalPrice = checkout.subtotalPrice;
// Update cart items in header
this.$cartCounter.html(lineItems.length);
// Update page Cart content
if ($('#cart').length) {
this.clearCartMarkup();
if (lineItems.length > 0) {
this.generateCartItemsRow(lineItems);
this.bindCartInputs(lineItems);
this.generateCheckout(webUrl);
this.generateSubtotal();
this.updateSubtotal(subtotalPrice);
this.$removeItem = $('.remove-item');
this.bindRemoveItems();
}
}
}
/**
* Clear HTML from Cart to prepare for update
*/ }, { key: 'clearCartMarkup', value: function clearCartMarkup()
{
this.$itemsContainer.html('');
this.$subtotalContainer.html('');
this.$checkoutContainer.html('');
}
/**
* Show price in an DOM element
* @param {object} product - Shopify product object
* @param {object} $element - jQuery DOM object to update
*/ }, { key: 'showPrice', value: function showPrice(
product, $element) {
// Update the element with the price of the first variant
$element.html('$ ' + product.attrs.variants[0].price);
}
/**
* Add item to Cart
*/ }, { key: 'handleAddToCart', value: function handleAddToCart(
product) {var _this3 = this;
var itemsToAdd = this.getQuantityAndVariant(product);
if (itemsToAdd.variantId) {
// Add an item to the checkout in shopify
this.client.checkout.addLineItems(this.checkout.id, [itemsToAdd]).
then(function (checkout) {
// Do something with the updated checkout
// Update the cart with the updated checkout
_this3.updateCart(checkout);
}).
catch(function (error) {
console.log(error);
});
} else {
$('#out-of-stock').addClass('show');
}
}
/*
* Generate cart items rows markup
* @param {object} items - Shopify items object
*/ }, { key: 'generateCartItemsRow', value: function generateCartItemsRow(
items) {var _this4 = this;
if (items.length) {
items.map(function (item) {
var image = item.variant.image.src ? '<img alt="' + item.title + '" src="' + item.variant.image.src + '" />' : '';
var variant = item.variant.title === 'Default Title' ? '' : item.variant.title;
_this4.$itemsContainer.append('\n <div class="grid-row margin-bottom-basic">\n <div class="grid-item item-s-3">\n ' +
image + '\n </div>\n <div class="grid-item item-s-9 grid-row no-gutter">\n <div class="grid-item item-s-12">\n <h3>' +
item.title + '</h3>\n <span>' +
variant + '</span>\n </div>\n <div class="grid-item item-s-12 grid-row no-gutter padding-top-tiny">\n <div class="grid-item item-s-4 font-size-small">\n Qty: <input class="cart-item-quantity font-size-basic" type="number" max="9" min="1" value="' +
item.attrs.quantity.value + '" data-product-id="' + item.id + '" />\n </div>\n <div class="grid-item item-s-4">\n <span>$' +
item.variant.price + '</span>\n </div>\n <div class="grid-item item-s-4 text-align-right">\n <button class="remove-item font-size-small font-uppercase button-no-padding" data-product-id="' +
item.id + '" >Remove</button>\n </div>\n </div>\n </div>\n </div>\n ');
});
} else {
this.$itemsContainer.append('\n <div class="grid-row">\n <div class="grid-item item-s-12">\n <h3 class="font-uppercase">Bag is empty</h3>\n </div>\n </div>\n ');
}
} }, { key: 'generateCheckout', value: function generateCheckout(
checkoutUrl) {
this.$checkoutContainer.append('<a href="' + checkoutUrl + '" class="font-uppercase font-medium">Checkout</a>');
} }, { key: 'generateSubtotal', value: function generateSubtotal()
{
this.$subtotalContainer.append('\n <div class="grid-item item-s-8 text-align-right font-uppercase">\n Subtotal:\n </div>\n <div class="grid-item item-s-4">\n $<span id="subtotal"></span>\n </div>\n ');
} }, { key: 'updateSubtotal', value: function updateSubtotal(
price) {
$('#subtotal').text(price);
} }, { key: 'bindCartInputs', value: function bindCartInputs()
{
$('.cart-item-quantity').on('change', this.handleCartQuantity);
} }, { key: 'handleCartQuantity', value: function handleCartQuantity(
event) {var _this5 = this;
var productId = event.target.dataset.productId;
var quantity = parseInt(event.target.value);
var productToUpdate = {
id: productId,
quantity: quantity };
// Update the line item on the checkout (change the quantity or variant)
this.client.checkout.updateLineItems(this.checkout.id, [productToUpdate]).
then(function (checkout) {
// Do something with the updated checkout
console.log(checkout); // Quantity of line item 'Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0Lzc4NTc5ODkzODQ=' updated to 2
_this5.updateSubtotal(checkout.subtotalPrice);
});
} }, { key: 'generateOptions', value: function generateOptions(
product) {
product.options.map(function (option) {
var hidden = '';
if (option.name === 'Title') {
hidden = 'u-hidden';
}
var optionHtml = '\n <div class="grid-item item-s-12 no-gutter grid-row margin-bottom-basic align-items-center ' +
hidden + '">\n <div class="grid-item item-s-6 text-align-right">\n <label for="option-' +
option.name + '" class="font-uppercase font-size-small">' + option.name + '</label>\n </div>\n <div class="grid-item item-s-6">\n <select id="option-' +
option.name + '" class="product-variant-select font-uppercase">';
option.values.map(function (option) {
optionHtml += '<option value="' + option.value + '">' + option.value + '</option>';
});
optionHtml += '\n </select>\n </div>\n </div>';
$('#product-options').append(optionHtml);
});
} }, { key: 'bindRemoveItems', value: function bindRemoveItems()
{
this.$removeItem.on('click', this.handleRemoveItems);
} }, { key: 'handleRemoveItems', value: function handleRemoveItems(
event) {var _this6 = this;
var productId = event.target.dataset.productId;
this.client.checkout.removeLineItems(this.checkout.id, [productId]).then(function (checkout) {
_this6.updateCart(checkout);
});
} }, { key: 'getVariantId', value: function getVariantId(
product) {
// Map values of form select inputs to array
var selectedOptions = $('.product-variant-select').map(function (index, elem) {
return $(elem).val();
});
var variants = product.variants;
// Set defaults for variant search
var matchFound = false;
var variantId = false;
// Loop through product variants
// example: Small/White, Medium/White, Small/Black, ...
for (var i = 0; i < variants.length; i++) {
var variantOptions = variants[i].selectedOptions;
variantId = variants[i].id;
// initiate selectedOptions counter
var v = 0;
// Loop through options of each variant
// example: Small, White
for (var j = 0; j < variantOptions.length; j++) {
// Loop through values retrieved from form select inputs.
// See if they correspond to this variant's options
for (var k = 0; k < selectedOptions.length; k++) {
// TRUE if this variant option matches the selected option
matchFound = variantOptions[j].value == selectedOptions[v];
if (matchFound) {
// If this is the last selected option
// and match found is still true
if (v === selectedOptions.length - 1) {
return variantId;
}
// Otherwise just iterate to next selected option
v++;
}
}
}
}
} }, { key: 'getQuantityAndVariant', value: function getQuantityAndVariant(
product) {
var variantId = this.getVariantId(product);
var quantity = parseInt(this.$quantitySelect.val());
// Has to be an array
return {
variantId: variantId,
quantity: quantity };
} }, { key: 'initCarousel', value: function initCarousel()
{
if ($('#slick-carousel').length) {
$('#slick-carousel').slick({
infinite: true,
speed: 300,
slidesToShow: 1,
centerMode: false,
variableWidth: true,
dots: false,
arrows: false,
focusOnSelect: true,
rows: 0 });
// TODO
// Advance carousel on-click
/*$('.slick-slide').on('click', () => {
console.log($('#slick-carousel').slick('slickCurrentSlide'));
});*/
}
} }]);return Shop;}();exports.default =
Shop;
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/*
The MIT License (MIT)
Copyright (c) 2016 Shopify Inc.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var _typeof2 = 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 _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};
var classCallCheck$1 = function classCallCheck$1(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass$1 = 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 inherits$1 = function inherits$1(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof2(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 possibleConstructorReturn$1 = function possibleConstructorReturn$1(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && ((typeof call === "undefined" ? "undefined" : _typeof2(call)) === "object" || typeof call === "function") ? call : self;
};
/*
The MIT License (MIT)
Copyright (c) 2016 Shopify Inc.
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.
*/
function join() {
for (var _len = arguments.length, fields = Array(_len), _key = 0; _key < _len; _key++) {
fields[_key] = arguments[_key];
}
return fields.join(' ');
}
function isObject(value) {
return Boolean(value) && Object.prototype.toString.call(value.valueOf()) === '[object Object]';
}
function deepFreezeCopyExcept(predicate, structure) {
if (predicate(structure)) {
return structure;
} else if (isObject(structure)) {
return Object.freeze(Object.keys(structure).reduce(function (copy, key) {
copy[key] = deepFreezeCopyExcept(predicate, structure[key]);
return copy;
}, {}));
} else if (Array.isArray(structure)) {
return Object.freeze(structure.map(function (item) {
return deepFreezeCopyExcept(predicate, item);
}));
} else {
return structure;
}
}
function schemaForType(typeBundle, typeName) {
var type = typeBundle.types[typeName];
if (type) {
return type;
}
throw new Error("No type of " + typeName + " found in schema");
}
var classCallCheck = function classCallCheck(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 inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _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 possibleConstructorReturn = function possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && ((typeof call === 'undefined' ? 'undefined' : _typeof(call)) === "object" || typeof call === "function") ? call : self;
};
var slicedToArray = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
var toConsumableArray = function toConsumableArray(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}return arr2;
} else {
return Array.from(arr);
}
};
var VariableDefinition = function () {
/**
* This constructor should not be invoked directly.
* Use the factory function {@link Client#variable} to create a VariableDefinition.
*
* @param {String} name The name of the variable.
* @param {String} type The GraphQL type of the variable.
* @param {*} [defaultValue] The default value of the variable.
*/
function VariableDefinition(name, type, defaultValue) {
classCallCheck(this, VariableDefinition);
this.name = name;
this.type = type;
this.defaultValue = defaultValue;
Object.freeze(this);
}
/**
* Returns the GraphQL query string for the variable as an input value (e.g. `$variableName`).
*
* @return {String} The GraphQL query string for the variable as an input value.
*/
createClass(VariableDefinition, [{
key: 'toInputValueString',
value: function toInputValueString() {
return '$' + this.name;
}
/**
* Returns the GraphQL query string for the variable (e.g. `$variableName:VariableType = defaultValue`).
*
* @return {String} The GraphQL query string for the variable.
*/ },
{
key: 'toString',
value: function toString() {
var defaultValueString = this.defaultValue ? ' = ' + formatInputValue(this.defaultValue) : '';
return '$' + this.name + ':' + this.type + defaultValueString;
} }]);
return VariableDefinition;
}();
function isVariable(value) {
return VariableDefinition.prototype.isPrototypeOf(value);
}
function variable(name, type, defaultValue) {
return new VariableDefinition(name, type, defaultValue);
}
var Enum = function () {
/**
* This constructor should not be invoked directly.
* Use the factory function {@link Client#enum} to create an Enum.
*
* @param {String} key The key of the enum.
*/
function Enum(key) {
classCallCheck(this, Enum);
this.key = key;
}
/**
* Returns the GraphQL query string for the enum (e.g. `enumKey`).
*
* @return {String} The GraphQL query string for the enum.
*/
createClass(Enum, [{
key: "toString",
value: function toString() {
return this.key;
} },
{
key: "valueOf",
value: function valueOf() {
return this.key.valueOf();
} }]);
return Enum;
}();
var enumFunction = function enumFunction(key) {
return new Enum(key);
};
var Scalar = function () {
function Scalar(value) {
classCallCheck(this, Scalar);
this.value = value;
}
createClass(Scalar, [{
key: "toString",
value: function toString() {
return this.value.toString();
} },
{
key: "valueOf",
value: function valueOf() {
return this.value.valueOf();
} },
{
key: "unwrapped",
get: function get$$1() {
return this.value;
} }]);
return Scalar;
}();
function formatInputValue(value) {
if (VariableDefinition.prototype.isPrototypeOf(value)) {
return value.toInputValueString();
} else if (Enum.prototype.isPrototypeOf(value)) {
return String(value);
} else if (Scalar.prototype.isPrototypeOf(value)) {
return JSON.stringify(value.valueOf());
} else if (Array.isArray(value)) {
return '[' + join.apply(undefined, toConsumableArray(value.map(formatInputValue))) + ']';
} else if (isObject(value)) {
return formatObject(value, '{', '}');
} else {
return JSON.stringify(value);
}
}
function formatObject(value) {
var openChar = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var closeChar = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
var argPairs = Object.keys(value).map(function (key) {
return key + ': ' + formatInputValue(value[key]);
});
return '' + openChar + join.apply(undefined, toConsumableArray(argPairs)) + closeChar;
}
function formatArgs(args) {
if (!Object.keys(args).length) {
return '';
}
return ' (' + formatObject(args) + ')';
}
// eslint-disable-next-line no-empty-function
var noop = function noop() {};
var Profiler = {
trackTypeDependency: noop,
trackFieldDependency: noop };
var trackTypeDependency = Profiler.trackTypeDependency;
var trackFieldDependency = Profiler.trackFieldDependency;
function parseFieldCreationArgs(creationArgs) {
var callback = noop;
var options = {};
var selectionSet = null;
if (creationArgs.length === 2) {
if (typeof creationArgs[1] === 'function') {
var _creationArgs = slicedToArray(creationArgs, 2);
options = _creationArgs[0];
callback = _creationArgs[1];
} else {
var _creationArgs2 = slicedToArray(creationArgs, 2);
options = _creationArgs2[0];
selectionSet = _creationArgs2[1];
}
} else if (creationArgs.length === 1) {
// SelectionSet is defined before this function is called since it's
// called by SelectionSet
// eslint-disable-next-line no-use-before-define
if (SelectionSet.prototype.isPrototypeOf(creationArgs[0])) {
selectionSet = creationArgs[0];
} else if (typeof creationArgs[0] === 'function') {
callback = creationArgs[0];
} else {
options = creationArgs[0];
}
}
return { options: options, selectionSet: selectionSet, callback: callback };
}
var emptyArgs = Object.freeze({});
var Field = function () {
/**
* This constructor should not be invoked directly.
* Fields are added to a selection by {@link SelectionSetBuilder#add}, {@link SelectionSetBuilder#addConnection}
* and {@link SelectionSetBuilder#addInlineFragmentOn}.
*
* @param {String} name The name of the field.
* @param {Object} [options] An options object containing:
* @param {Object} [options.args] Arguments for the field.
* @param {String} [options.alias] An alias for the field.
* @param {SelectionSet} selectionSet The selection set on the field.
*/
function Field(name, options, selectionSet) {
classCallCheck(this, Field);
this.name = name;
this.alias = options.alias || null;
this.responseKey = this.alias || this.name;
this.args = options.args ? deepFreezeCopyExcept(isVariable, options.args) : emptyArgs;
this.selectionSet = selectionSet;
Object.freeze(this);
}
/**
* Returns the GraphQL query string for the Field (e.g. `catAlias: cat(size: 'small') { name }` or `name`).
*
* @return {String} The GraphQL query string for the Field.
*/
createClass(Field, [{
key: 'toString',
value: function toString() {
var aliasPrefix = this.alias ? this.alias + ': ' : '';
return '' + aliasPrefix + this.name + formatArgs(this.args) + this.selectionSet;
} }]);
return Field;
}();
// This is an interface that defines a usage, and simplifies type checking
var Spread = function Spread() {
classCallCheck(this, Spread);
};
var InlineFragment = function (_Spread) {
inherits(InlineFragment, _Spread);
/**
* This constructor should not be invoked directly.
* Use the factory function {@link SelectionSetBuilder#addInlineFragmentOn} to create an InlineFragment.
*
* @param {String} typeName The type of the fragment.
* @param {SelectionSet} selectionSet The selection set on the fragment.
*/
function InlineFragment(typeName, selectionSet) {
classCallCheck(this, InlineFragment);
var _this = possibleConstructorReturn(this, (InlineFragment.__proto__ || Object.getPrototypeOf(InlineFragment)).call(this));
_this.typeName = typeName;
_this.selectionSet = selectionSet;
Object.freeze(_this);
return _this;
}
/**
* Returns the GraphQL query string for the InlineFragment (e.g. `... on Cat { name }`).
*
* @return {String} The GraphQL query string for the InlineFragment.
*/
createClass(InlineFragment, [{
key: 'toString',
value: function toString() {
return '... on ' + this.typeName + this.selectionSet;
} }]);
return InlineFragment;
}(Spread);
var FragmentSpread = function (_Spread2) {
inherits(FragmentSpread, _Spread2);
/**
* This constructor should not be invoked directly.
* Use the factory function {@link Document#defineFragment} to create a FragmentSpread.
*
* @param {FragmentDefinition} fragmentDefinition The corresponding fragment definition.
*/
function FragmentSpread(fragmentDefinition) {
classCallCheck(this, FragmentSpread);
var _this2 = possibleConstructorReturn(this, (FragmentSpread.__proto__ || Object.getPrototypeOf(FragmentSpread)).call(this));
_this2.name = fragmentDefinition.name;
_this2.selectionSet = fragmentDefinition.selectionSet;
Object.freeze(_this2);
return _this2;
}
/**
* Returns the GraphQL query string for the FragmentSpread (e.g. `...catName`).
*
* @return {String} The GraphQL query string for the FragmentSpread.
*/
createClass(FragmentSpread, [{
key: 'toString',
value: function toString() {
return '...' + this.name;
} },
{
key: 'toDefinition',
value: function toDefinition() {
// eslint-disable-next-line no-use-before-define
return new FragmentDefinition(this.name, this.selectionSet.typeSchema.name, this.selectionSet);
} }]);
return FragmentSpread;
}(Spread);
var FragmentDefinition = function () {
/**
* This constructor should not be invoked directly.
* Use the factory function {@link Document#defineFragment} to create a FragmentDefinition on a {@link Document}.
*
* @param {String} name The name of the fragment definition.
* @param {String} typeName The type of the fragment.
*/
function FragmentDefinition(name, typeName, selectionSet) {
classCallCheck(this, FragmentDefinition);
this.name = name;
this.typeName = typeName;
this.selectionSet = selectionSet;
this.spread = new FragmentSpread(this);
Object.freeze(this);
}
/**
* Returns the GraphQL query string for the FragmentDefinition (e.g. `fragment catName on Cat { name }`).
*
* @return {String} The GraphQL query string for the FragmentDefinition.
*/
createClass(FragmentDefinition, [{
key: 'toString',
value: function toString() {
return 'fragment ' + this.name + ' on ' + this.typeName + ' ' + this.selectionSet;
} }]);
return FragmentDefinition;
}();
function selectionsHaveIdField(selections) {
return selections.some(function (fieldOrFragment) {
if (Field.prototype.isPrototypeOf(fieldOrFragment)) {
return fieldOrFragment.name === 'id';
} else if (Spread.prototype.isPrototypeOf(fieldOrFragment) && fieldOrFragment.selectionSet.typeSchema.implementsNode) {
return selectionsHaveIdField(fieldOrFragment.selectionSet.selections);
}
return false;
});
}
function selectionsHaveTypenameField(selections) {
return selections.some(function (fieldOrFragment) {
if (Field.prototype.isPrototypeOf(fieldOrFragment)) {
return fieldOrFragment.name === '__typename';
} else if (Spread.prototype.isPrototypeOf(fieldOrFragment) && fieldOrFragment.selectionSet.typeSchema.implementsNode) {
return selectionsHaveTypenameField(fieldOrFragment.selectionSet.selections);
}
return false;
});
}
function indexSelectionsByResponseKey(selections) {
function assignOrPush(obj, key, value) {
if (Array.isArray(obj[key])) {
obj[key].push(value);
} else {
obj[key] = [value];
}
}
var unfrozenObject = selections.reduce(function (acc, selection) {
if (selection.responseKey) {
assignOrPush(acc, selection.responseKey, selection);
} else {
var responseKeys = Object.keys(selection.selectionSet.selectionsByResponseKey);
responseKeys.forEach(function (responseKey) {
assignOrPush(acc, responseKey, selection);
});
}
return acc;
}, {});
Object.keys(unfrozenObject).forEach(function (key) {
Object.freeze(unfrozenObject[key]);
});
return Object.freeze(unfrozenObject);
}
/**
* Class that specifies the full selection of data to query.
*/
var SelectionSet = function () {
/**
* This constructor should not be invoked directly. SelectionSets are created when building queries/mutations.
*
* @param {Object} typeBundle A set of ES6 modules generated by {@link https://github.com/Shopify/graphql-js-schema|graphql-js-schema}.
* @param {(Object|String)} type The type of the current selection.
* @param {Function} builderFunction Callback function used to build the SelectionSet.
* The callback takes a {@link SelectionSetBuilder} as its argument.
*/
function SelectionSet(typeBundle, type, builderFunction) {
classCallCheck(this, SelectionSet);
if (typeof type === 'string') {
this.typeSchema = schemaForType(typeBundle, type);
} else {
this.typeSchema = type;
}
trackTypeDependency(this.typeSchema.name);
this.typeBundle = typeBundle;
this.selections = [];
if (builderFunction) {
// eslint-disable-next-line no-use-before-define
builderFunction(new SelectionSetBuilder(this.typeBundle, this.typeSchema, this.selections));
}
if (this.typeSchema.implementsNode || this.typeSchema.name === 'Node') {
if (!selectionsHaveIdField(this.selections)) {
this.selections.unshift(new Field('id', {}, new SelectionSet(typeBundle, 'ID')));
}
}
if (this.typeSchema.kind === 'INTERFACE') {
if (!selectionsHaveTypenameField(this.selections)) {
this.selections.unshift(new Field('__typename', {}, new SelectionSet(typeBundle, 'String')));
}
}
this.selectionsByResponseKey = indexSelectionsByResponseKey(this.selections);
Object.freeze(this.selections);
Object.freeze(this);
}
/**
* Returns the GraphQL query string for the SelectionSet (e.g. `{ cat { name } }`).
*
* @return {String} The GraphQL query string for the SelectionSet.
*/
createClass(SelectionSet, [{
key: 'toString',
value: function toString() {
if (this.typeSchema.kind === 'SCALAR' || this.typeSchema.kind === 'ENUM') {
return '';
} else {
return ' { ' + join(this.selections) + ' }';
}
} }]);
return SelectionSet;
}();
var SelectionSetBuilder = function () {
/**
* This constructor should not be invoked directly. SelectionSetBuilders are created when building queries/mutations.
*
* @param {Object} typeBundle A set of ES6 modules generated by {@link https://github.com/Shopify/graphql-js-schema|graphql-js-schema}.
* @param {Object} typeSchema The schema object for the type of the current selection.
* @param {Field[]} selections The fields on the current selection.
*/
function SelectionSetBuilder(typeBundle, typeSchema, selections) {
classCallCheck(this, SelectionSetBuilder);
this.typeBundle = typeBundle;
this.typeSchema = typeSchema;
this.selections = selections;
}
createClass(SelectionSetBuilder, [{
key: 'hasSelectionWithResponseKey',
value: function hasSelectionWithResponseKey(responseKey) {
return this.selections.some(function (field) {
return field.responseKey === responseKey;
});
}
/**
* Adds a field to be queried on the current selection.
*
* @example
* client.query((root) => {
* root.add('cat', {args: {id: '123456'}, alias: 'meow'}, (cat) => {
* cat.add('name');
* });
* });
*
* @param {SelectionSet|String} selectionOrFieldName The selection or name of the field to add.
* @param {Object} [options] Options on the query including:
* @param {Object} [options.args] Arguments on the query (e.g. `{id: '123456'}`).
* @param {String} [options.alias] Alias for the field being added.
* @param {Function|SelectionSet} [callbackOrSelectionSet] Either a callback which will be used to create a new {@link SelectionSet}, or an existing {@link SelectionSet}.
*/ },
{
key: 'add',
value: function add(selectionOrFieldName) {
var selection = void 0;
if (Object.prototype.toString.call(selectionOrFieldName) === '[object String]') {
trackFieldDependency(this.typeSchema.name, selectionOrFieldName);
for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
rest[_key - 1] = arguments[_key];
}
selection = this.field.apply(this, [selectionOrFieldName].concat(rest));
} else {
if (Field.prototype.isPrototypeOf(selectionOrFieldName)) {
trackFieldDependency(this.typeSchema.name, selectionOrFieldName.name);
}
selection = selectionOrFieldName;
}
if (selection.responseKey && this.hasSelectionWithResponseKey(selection.responseKey)) {
throw new Error('The field name or alias \'' + selection.responseKey + '\' has already been added.');
}
this.selections.push(selection);
} },
{
key: 'field',
value: function field(name) {
for (var _len2 = arguments.length, creationArgs = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
creationArgs[_key2 - 1] = arguments[_key2];
}
var parsedArgs = parseFieldCreationArgs(creationArgs);
var options = parsedArgs.options,
callback = parsedArgs.callback;
var selectionSet = parsedArgs.selectionSet;
if (!selectionSet) {
if (!this.typeSchema.fieldBaseTypes[name]) {
throw new Error('No field of name "' + name + '" found on type "' + this.typeSchema.name + '" in schema');
}
var fieldBaseType = schemaForType(this.typeBundle, this.typeSchema.fieldBaseTypes[name]);
selectionSet = new SelectionSet(this.typeBundle, fieldBaseType, callback);
}
return new Field(name, options, selectionSet);
}
/**
* Creates an inline fragment.
*
* @access private
* @param {String} typeName The type the inline fragment.
* @param {Function|SelectionSet} [callbackOrSelectionSet] Either a callback which will be used to create a new {@link SelectionSet}, or an existing {@link SelectionSet}.
* @return {InlineFragment} An inline fragment.
*/ },
{
key: 'inlineFragmentOn',
value: function inlineFragmentOn(typeName) {
var builderFunctionOrSelectionSet = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
var selectionSet = void 0;
if (SelectionSet.prototype.isPrototypeOf(builderFunctionOrSelectionSet)) {
selectionSet = builderFunctionOrSelectionSet;
} else {
selectionSet = new SelectionSet(this.typeBundle, schemaForType(this.typeBundle, typeName), builderFunctionOrSelectionSet);
}
return new InlineFragment(typeName, selectionSet);
}
/**
* Adds a field to be queried on the current selection.
*
* @access private
* @param {String} name The name of the field to add to the query.
* @param {Object} [options] Options on the query including:
* @param {Object} [options.args] Arguments on the query (e.g. `{id: '123456'}`).
* @param {String} [options.alias] Alias for the field being added.
* @param {Function} [callback] Callback which will be used to create a new {@link SelectionSet} for the field added.
*/ },
{
key: 'addField',
value: function addField(name) {
for (var _len3 = arguments.length, creationArgs = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
creationArgs[_key3 - 1] = arguments[_key3];
}
this.add.apply(this, [name].concat(creationArgs));
}
/**
* Adds a connection to be queried on the current selection.
* This adds all the fields necessary for pagination.
*
* @example
* client.query((root) => {
* root.add('cat', (cat) => {
* cat.addConnection('friends', {args: {first: 10}, alias: 'coolCats'}, (friends) => {
* friends.add('name');
* });
* });
* });
*
* @param {String} name The name of the connection to add to the query.
* @param {Object} [options] Options on the query including:
* @param {Object} [options.args] Arguments on the query (e.g. `{first: 10}`).
* @param {String} [options.alias] Alias for the field being added.
* @param {Function|SelectionSet} [callbackOrSelectionSet] Either a callback which will be used to create a new {@link SelectionSet}, or an existing {@link SelectionSet}.
*/ },
{
key: 'addConnection',
value: function addConnection(name) {
for (var _len4 = arguments.length, creationArgs = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
creationArgs[_key4 - 1] = arguments[_key4];
}
var _parseFieldCreationAr = parseFieldCreationArgs(creationArgs),
options = _parseFieldCreationAr.options,
callback = _parseFieldCreationAr.callback,
selectionSet = _parseFieldCreationAr.selectionSet;
this.add(name, options, function (connection) {
connection.add('pageInfo', {}, function (pageInfo) {
pageInfo.add('hasNextPage');
pageInfo.add('hasPreviousPage');
});
connection.add('edges', {}, function (edges) {
edges.add('cursor');
edges.addField('node', {}, selectionSet || callback); // This is bad. Don't do this
});
});
}
/**
* Adds an inline fragment on the current selection.
*
* @example
* client.query((root) => {
* root.add('animal', (animal) => {
* animal.addInlineFragmentOn('cat', (cat) => {
* cat.add('name');
* });
* });
* });
*
* @param {String} typeName The name of the type of the inline fragment.
* @param {Function|SelectionSet} [callbackOrSelectionSet] Either a callback which will be used to create a new {@link SelectionSet}, or an existing {@link SelectionSet}.
*/ },
{
key: 'addInlineFragmentOn',
value: function addInlineFragmentOn(typeName) {
var fieldTypeCb = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
this.add(this.inlineFragmentOn(typeName, fieldTypeCb));
}
/**
* Adds a fragment spread on the current selection.
*
* @example
* client.query((root) => {
* root.addFragment(catFragmentSpread);
* });
*
* @param {FragmentSpread} fragmentSpread The fragment spread to add.
*/ },
{
key: 'addFragment',
value: function addFragment(fragmentSpread) {
this.add(fragmentSpread);
} }]);
return SelectionSetBuilder;
}();
function parseArgs(args) {
var name = void 0;
var variables = void 0;
var selectionSetCallback = void 0;
if (args.length === 3) {
var _args = slicedToArray(args, 3);
name = _args[0];
variables = _args[1];
selectionSetCallback = _args[2];
} else if (args.length === 2) {
if (Object.prototype.toString.call(args[0]) === '[object String]') {
name = args[0];
variables = null;
} else if (Array.isArray(args[0])) {
variables = args[0];
name = null;
}
selectionSetCallback = args[1];
} else {
selectionSetCallback = args[0];
name = null;
}
return { name: name, variables: variables, selectionSetCallback: selectionSetCallback };
}
var VariableDefinitions = function () {
function VariableDefinitions(variableDefinitions) {
classCallCheck(this, VariableDefinitions);
this.variableDefinitions = variableDefinitions ? [].concat(toConsumableArray(variableDefinitions)) : [];
Object.freeze(this.variableDefinitions);
Object.freeze(this);
}
createClass(VariableDefinitions, [{
key: 'toString',
value: function toString() {
if (this.variableDefinitions.length === 0) {
return '';
}
return ' (' + join(this.variableDefinitions) + ') ';
} }]);
return VariableDefinitions;
}();
/**
* Base class for {@link Query} and {@link Mutation}.
* @abstract
*/
var Operation = function () {
/**
* This constructor should not be invoked. The subclasses {@link Query} and {@link Mutation} should be used instead.
*/
function Operation(typeBundle, operationType) {
classCallCheck(this, Operation);
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
var _parseArgs = parseArgs(args),
name = _parseArgs.name,
variables = _parseArgs.variables,
selectionSetCallback = _parseArgs.selectionSetCallback;
this.typeBundle = typeBundle;
this.name = name;
this.variableDefinitions = new VariableDefinitions(variables);
this.operationType = operationType;
if (operationType === 'query') {
this.selectionSet = new SelectionSet(typeBundle, typeBundle.queryType, selectionSetCallback);
this.typeSchema = schemaForType(typeBundle, typeBundle.queryType);
} else {
this.selectionSet = new SelectionSet(typeBundle, typeBundle.mutationType, selectionSetCallback);
this.typeSchema = schemaForType(typeBundle, typeBundle.mutationType);
}
Object.freeze(this);
}
/**
* Whether the operation is anonymous (i.e. has no name).
*/
createClass(Operation, [{
key: 'toString',
/**
* Returns the GraphQL query or mutation string (e.g. `query myQuery { cat { name } }`).
*
* @return {String} The GraphQL query or mutation string.
*/
value: function toString() {
var nameString = this.name ? ' ' + this.name : '';
return '' + this.operationType + nameString + this.variableDefinitions + this.selectionSet;
} },
{
key: 'isAnonymous',
get: function get$$1() {
return !this.name;
} }]);
return Operation;
}();
/**
* GraphQL Query class.
* @extends Operation
*/
var Query = function (_Operation) {
inherits(Query, _Operation);
/**
* This constructor should not be invoked directly.
* Use the factory functions {@link Client#query} or {@link Document#addQuery} to create a Query.
*
* @param {Object} typeBundle A set of ES6 modules generated by {@link https://github.com/Shopify/graphql-js-schema|graphql-js-schema}.
* @param {String} [name] A name for the query.
* @param {Object[]} [variables] A list of variables in the query. See {@link Client#variable}.
* @param {Function} selectionSetCallback The query builder callback.
* A {@link SelectionSet} is created using this callback.
*/
function Query(typeBundle) {
var _ref;
classCallCheck(this, Query);
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return possibleConstructorReturn(this, (_ref = Query.__proto__ || Object.getPrototypeOf(Query)).call.apply(_ref, [this, typeBundle, 'query'].concat(args)));
}
return Query;
}(Operation);
/**
* GraphQL Mutation class.
* @extends Operation
*/
var Mutation = function (_Operation) {
inherits(Mutation, _Operation);
/**
* This constructor should not be invoked directly.
* Use the factory functions {@link Client#mutation} or {@link Document#addMutation} to create a Mutation.
*
* @param {Object} typeBundle A set of ES6 modules generated by {@link https://github.com/Shopify/graphql-js-schema|graphql-js-schema}.
* @param {String} [name] A name for the mutation.
* @param {Object[]} [variables] A list of variables in the mutation. See {@link Client#variable}.
* @param {Function} selectionSetCallback The mutation builder callback.
* A {@link SelectionSet} is created using this callback.
*/
function Mutation(typeBundle) {
var _ref;
classCallCheck(this, Mutation);
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return possibleConstructorReturn(this, (_ref = Mutation.__proto__ || Object.getPrototypeOf(Mutation)).call.apply(_ref, [this, typeBundle, 'mutation'].concat(args)));
}
return Mutation;
}(Operation);
function isAnonymous(operation) {
return operation.isAnonymous;
}
function hasAnonymousOperations(operations) {
return operations.some(isAnonymous);
}
function hasDuplicateOperationNames(operations) {
var names = operations.map(function (operation) {
return operation.name;
});
return names.reduce(function (hasDuplicates, name, index) {
return hasDuplicates || names.indexOf(name) !== index;
}, false);
}
function extractOperation(typeBundle, operationType) {
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
if (Operation.prototype.isPrototypeOf(args[0])) {
return args[0];
}
if (operationType === 'query') {
return new (Function.prototype.bind.apply(Query, [null].concat([typeBundle], args)))();
} else {
return new (Function.prototype.bind.apply(Mutation, [null].concat([typeBundle], args)))();
}
}
function isInvalidOperationCombination(operations) {
if (operations.length === 1) {
return false;
}
return hasAnonymousOperations(operations) || hasDuplicateOperationNames(operations);
}
function fragmentNameIsNotUnique(existingDefinitions, name) {
return existingDefinitions.some(function (definition) {
return definition.name === name;
});
}
var Document = function () {
/**
* This constructor should not be invoked directly.
* Use the factory function {@link Client#document} to create a Document.
* @param {Object} typeBundle A set of ES6 modules generated by {@link https://github.com/Shopify/graphql-js-schema|graphql-js-schema}.
*/
function Document(typeBundle) {
classCallCheck(this, Document);
this.typeBundle = typeBundle;
this.definitions = [];
}
/**
* Returns the GraphQL query string for the Document (e.g. `query queryOne { ... } query queryTwo { ... }`).
*
* @return {String} The GraphQL query string for the Document.
*/
createClass(Document, [{
key: 'toString',
value: function toString() {
return join(this.definitions);
}
/**
* Adds an operation to the Document.
*
* @private
* @param {String} operationType The type of the operation. Either 'query' or 'mutation'.
* @param {(Operation|String)} [query|queryName] Either an instance of an operation
* object, or the name of an operation. Both are optional.
* @param {Object[]} [variables] A list of variables in the operation. See {@link Client#variable}.
* @param {Function} [callback] The query builder callback. If an operation
* instance is passed, this callback will be ignored.
* A {@link SelectionSet} is created using this callback.
*/ },
{
key: 'addOperation',
value: function addOperation(operationType) {
for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
var operation = extractOperation.apply(undefined, [this.typeBundle, operationType].concat(args));
if (isInvalidOperationCombination(this.operations.concat(operation))) {
throw new Error('All operations must be uniquely named on a multi-operation document');
}
this.definitions.push(operation);
}
/**
* Adds a query to the Document.
*
* @example
* document.addQuery('myQuery', (root) => {
* root.add('cat', (cat) => {
* cat.add('name');
* });
* });
*
* @param {(Query|String)} [query|queryName] Either an instance of a query
* object, or the name of a query. Both are optional.
* @param {Object[]} [variables] A list of variables in the query. See {@link Client#variable}.
* @param {Function} [callback] The query builder callback. If a query
* instance is passed, this callback will be ignored.
* A {@link SelectionSet} is created using this callback.
*/ },
{
key: 'addQuery',
value: function addQuery() {
for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
this.addOperation.apply(this, ['query'].concat(args));
}
/**
* Adds a mutation to the Document.
*
* @example
* const input = client.variable('input', 'CatCreateInput!');
*
* document.addMutation('myMutation', [input], (root) => {
* root.add('catCreate', {args: {input}}, (catCreate) => {
* catCreate.add('cat', (cat) => {
* cat.add('name');
* });
* });
* });
*
* @param {(Mutation|String)} [mutation|mutationName] Either an instance of a mutation
* object, or the name of a mutation. Both are optional.
* @param {Object[]} [variables] A list of variables in the mutation. See {@link Client#variable}.
* @param {Function} [callback] The mutation builder callback. If a mutation
* instance is passed, this callback will be ignored.
* A {@link SelectionSet} is created using this callback.
*/ },
{
key: 'addMutation',
value: function addMutation() {
for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
this.addOperation.apply(this, ['mutation'].concat(args));
}
/**
* Defines a fragment on the Document.
*
* @param {String} name The name of the fragment.
* @param {String} onType The type the fragment is on.
* @param {Function} [builderFunction] The query builder callback.
* A {@link SelectionSet} is created using this callback.
* @return {FragmentSpread} A {@link FragmentSpread} to be used with {@link SelectionSetBuilder#addFragment}.
*/ },
{
key: 'defineFragment',
value: function defineFragment(name, onType, builderFunction) {
if (fragmentNameIsNotUnique(this.fragmentDefinitions, name)) {
throw new Error('All fragments must be uniquely named on a multi-fragment document');
}
var selectionSet = new SelectionSet(this.typeBundle, onType, builderFunction);
var fragment = new FragmentDefinition(name, onType, selectionSet);
this.definitions.push(fragment);
return fragment.spread;
}
/**
* All operations ({@link Query} and {@link Mutation}) on the Document.
*/ },
{
key: 'operations',
get: function get$$1() {
return this.definitions.filter(function (definition) {
return Operation.prototype.isPrototypeOf(definition);
});
}
/**
* All {@link FragmentDefinition}s on the Document.
*/ },
{
key: 'fragmentDefinitions',
get: function get$$1() {
return this.definitions.filter(function (definition) {
return FragmentDefinition.prototype.isPrototypeOf(definition);
});
} }]);
return Document;
}();
/**
* The base class used when deserializing response data.
* Provides rich features, like functions to generate queries to refetch a node or fetch the next page.
*
* @class
*/
var GraphModel =
/**
* @param {Object} attrs Attributes on the GraphModel.
*/
function GraphModel(attrs) {
var _this = this;
classCallCheck(this, GraphModel);
Object.defineProperty(this, 'attrs', { value: attrs, enumerable: false });
Object.keys(this.attrs).filter(function (key) {
return !(key in _this);
}).forEach(function (key) {
var descriptor = void 0;
if (attrs[key] === null) {
descriptor = {
enumerable: true,
get: function get$$1() {
return null;
} };
} else {
descriptor = {
enumerable: true,
get: function get$$1() {
return this.attrs[key].valueOf();
} };
}
Object.defineProperty(_this, key, descriptor);
});
};
/**
* A registry of classes used to deserialize the response data. Uses {@link GraphModel} by default.
*/
var ClassRegistry = function () {
function ClassRegistry() {
classCallCheck(this, ClassRegistry);
this.classStore = {};
}
/**
* Registers a class for a GraphQL type in the registry.
*
* @param {Class} constructor The constructor of the class.
* @param {String} type The GraphQL type of the object to deserialize into the class.
*/
createClass(ClassRegistry, [{
key: 'registerClassForType',
value: function registerClassForType(constructor, type) {
this.classStore[type] = constructor;
}
/**
* Unregisters a class for a GraphQL type in the registry.
*
* @param {String} type The GraphQL type to unregister.
*/ },
{
key: 'unregisterClassForType',
value: function unregisterClassForType(type) {
delete this.classStore[type];
}
/**
* Returns the class for the given GraphQL type.
*
* @param {String} type The GraphQL type to look up.
* @return {Class|GraphModel} The class for the given GraphQL type. Defaults to {@link GraphModel} if no class is registered for the GraphQL type.
*/ },
{
key: 'classForType',
value: function classForType(type) {
return this.classStore[type] || GraphModel;
} }]);
return ClassRegistry;
}();
function isValue(arg) {
return Object.prototype.toString.call(arg) !== '[object Null]' && Object.prototype.toString.call(arg) !== '[object Undefined]';
}
function isNodeContext(context) {
return context.selection.selectionSet.typeSchema.implementsNode;
}
function isConnection(context) {
return context.selection.selectionSet.typeSchema.name.endsWith('Connection');
}
function nearestNode(context) {
if (context == null) {
return null;
} else if (isNodeContext(context)) {
return context;
} else {
return nearestNode(context.parent);
}
}
function contextsFromRoot(context) {
if (context.parent) {
return contextsFromRoot(context.parent).concat(context);
} else {
return [context];
}
}
function contextsFromNearestNode(context) {
if (context.selection.selectionSet.typeSchema.implementsNode) {
return [context];
} else {
return contextsFromNearestNode(context.parent).concat(context);
}
}
function initializeDocumentAndVars(currentContext, contextChain) {
var lastInChain = contextChain[contextChain.length - 1];
var first = lastInChain.selection.args.first;
var variableDefinitions = Object.keys(lastInChain.selection.args).filter(function (key) {
return isVariable(lastInChain.selection.args[key]);
}).map(function (key) {
return lastInChain.selection.args[key];
});
var firstVar = variableDefinitions.find(function (definition) {
return definition.name === 'first';
});
if (!firstVar) {
firstVar = variable('first', 'Int', first);
variableDefinitions.push(firstVar);
}
var document = new Document(currentContext.selection.selectionSet.typeBundle);
return [document, variableDefinitions, firstVar];
}
function addNextFieldTo(currentSelection, contextChain, path, cursor) {
// There are always at least two. When we start, it's the root context, and the first set
var nextContext = contextChain.shift();
path.push(nextContext.selection.responseKey);
if (contextChain.length) {
currentSelection.add(nextContext.selection.name, { alias: nextContext.selection.alias, args: nextContext.selection.args }, function (newSelection) {
addNextFieldTo(newSelection, contextChain, path, cursor);
});
} else {
var edgesField = nextContext.selection.selectionSet.selections.find(function (field) {
return field.name === 'edges';
});
var nodeField = edgesField.selectionSet.selections.find(function (field) {
return field.name === 'node';
});
var first = void 0;
if (isVariable(nextContext.selection.args.first)) {
first = nextContext.selection.args.first;
} else {
first = variable('first', 'Int', nextContext.selection.args.first);
}
var options = {
alias: nextContext.selection.alias,
args: Object.assign({}, nextContext.selection.args, { after: cursor, first: first }) };
currentSelection.addConnection(nextContext.selection.name, options, nodeField.selectionSet);
}
}
function collectFragments(selections) {
return selections.reduce(function (fragmentDefinitions, field) {
if (FragmentSpread.prototype.isPrototypeOf(field)) {
fragmentDefinitions.push(field.toDefinition());
}
fragmentDefinitions.push.apply(fragmentDefinitions, toConsumableArray(collectFragments(field.selectionSet.selections)));
return fragmentDefinitions;
}, []);
}
function nextPageQueryAndPath(context, cursor) {
var nearestNodeContext = nearestNode(context);
if (nearestNodeContext) {
return function () {
var _document$definitions;
var path = [];
var nodeType = nearestNodeContext.selection.selectionSet.typeSchema;
var nodeId = nearestNodeContext.responseData.id;
var contextChain = contextsFromNearestNode(context);
var _initializeDocumentAn = initializeDocumentAndVars(context, contextChain),
_initializeDocumentAn2 = slicedToArray(_initializeDocumentAn, 2),
document = _initializeDocumentAn2[0],
variableDefinitions = _initializeDocumentAn2[1];
document.addQuery(variableDefinitions, function (root) {
path.push('node');
root.add('node', { args: { id: nodeId } }, function (node) {
node.addInlineFragmentOn(nodeType.name, function (fragment) {
addNextFieldTo(fragment, contextChain.slice(1), path, cursor);
});
});
});
var fragments = collectFragments(document.operations[0].selectionSet.selections);
(_document$definitions = document.definitions).unshift.apply(_document$definitions, toConsumableArray(fragments));
return [document, path];
};
} else {
return function () {
var _document$definitions2;
var path = [];
var contextChain = contextsFromRoot(context);
var _initializeDocumentAn3 = initializeDocumentAndVars(context, contextChain),
_initializeDocumentAn4 = slicedToArray(_initializeDocumentAn3, 2),
document = _initializeDocumentAn4[0],
variableDefinitions = _initializeDocumentAn4[1];
document.addQuery(variableDefinitions, function (root) {
addNextFieldTo(root, contextChain.slice(1), path, cursor);
});
var fragments = collectFragments(document.operations[0].selectionSet.selections);
(_document$definitions2 = document.definitions).unshift.apply(_document$definitions2, toConsumableArray(fragments));
return [document, path];
};
}
}
function hasNextPage$1(connection, edge) {
if (edge !== connection.edges[connection.edges.length - 1]) {
return new Scalar(true);
}
return connection.pageInfo.hasNextPage;
}
function hasPreviousPage(connection, edge) {
if (edge !== connection.edges[0]) {
return new Scalar(true);
}
return connection.pageInfo.hasPreviousPage;
}
function transformConnections(variableValues) {
return function (context, value) {
if (isConnection(context)) {
if (!(value.pageInfo && value.pageInfo.hasOwnProperty('hasNextPage') && value.pageInfo.hasOwnProperty('hasPreviousPage'))) {
throw new Error('Connections must include the selections "pageInfo { hasNextPage, hasPreviousPage }".');
}
return value.edges.map(function (edge) {
return Object.assign(edge.node, {
nextPageQueryAndPath: nextPageQueryAndPath(context, edge.cursor),
hasNextPage: hasNextPage$1(value, edge),
hasPreviousPage: hasPreviousPage(value, edge),
variableValues: variableValues });
});
} else {
return value;
}
};
}
/* eslint-disable no-warning-comments */
var DecodingContext = function () {
function DecodingContext(selection, responseData) {
var parent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
classCallCheck(this, DecodingContext);
this.selection = selection;
this.responseData = responseData;
this.parent = parent;
Object.freeze(this);
}
createClass(DecodingContext, [{
key: 'contextForObjectProperty',
value: function contextForObjectProperty(responseKey) {
var nestedSelections = this.selection.selectionSet.selectionsByResponseKey[responseKey];
var nextSelection = nestedSelections && nestedSelections[0];
var nextContext = void 0;
// fragment spreads operate inside the current context, so we recurse to get the proper
// selection set, but retain the current response context
if (Spread.prototype.isPrototypeOf(nextSelection)) {
nextContext = new DecodingContext(nextSelection, this.responseData, this.parent);
} else {
nextContext = new DecodingContext(nextSelection, this.responseData[responseKey], this);
}
if (!nextSelection) {
throw new Error('Unexpected response key "' + responseKey + '", not found in selection set: ' + this.selection.selectionSet);
}
if (Field.prototype.isPrototypeOf(nextSelection)) {
return nextContext;
} else {
return nextContext.contextForObjectProperty(responseKey);
}
} },
{
key: 'contextForArrayItem',
value: function contextForArrayItem(item) {
return new DecodingContext(this.selection, item, this.parent);
} }]);
return DecodingContext;
}();
function decodeArrayItems(context, transformers) {
return context.responseData.map(function (item) {
return decodeContext(context.contextForArrayItem(item), transformers);
});
}
function decodeObjectValues(context, transformers) {
return Object.keys(context.responseData).reduce(function (acc, responseKey) {
acc[responseKey] = decodeContext(context.contextForObjectProperty(responseKey), transformers);
return acc;
}, {});
}
function runTransformers(transformers, context, value) {
return transformers.reduce(function (acc, transformer) {
return transformer(context, acc);
}, value);
}
function decodeContext(context, transformers) {
var value = context.responseData;
if (Array.isArray(value)) {
value = decodeArrayItems(context, transformers);
} else if (isObject(value)) {
value = decodeObjectValues(context, transformers);
}
return runTransformers(transformers, context, value);
}
function generateRefetchQueries(context, value) {
if (isValue(value) && isNodeContext(context)) {
value.refetchQuery = function () {
return new Query(context.selection.selectionSet.typeBundle, function (root) {
root.add('node', { args: { id: context.responseData.id } }, function (node) {
node.addInlineFragmentOn(context.selection.selectionSet.typeSchema.name, context.selection.selectionSet);
});
});
};
}
return value;
}
function transformPojosToClassesWithRegistry(classRegistry) {
return function transformPojosToClasses(context, value) {
if (isObject(value)) {
var Klass = classRegistry.classForType(context.selection.selectionSet.typeSchema.name);
return new Klass(value);
} else {
return value;
}
};
}
function transformScalars(context, value) {
if (isValue(value)) {
if (context.selection.selectionSet.typeSchema.kind === 'SCALAR') {
return new Scalar(value);
} else if (context.selection.selectionSet.typeSchema.kind === 'ENUM') {
return new Enum(value);
}
}
return value;
}
function recordTypeInformation(context, value) {
if (isValue(value)) {
if (value.__typename) {
value.type = schemaForType(context.selection.selectionSet.typeBundle, value.__typename);
} else {
value.type = context.selection.selectionSet.typeSchema;
}
}
return value;
}
function defaultTransformers(_ref) {
var _ref$classRegistry = _ref.classRegistry,
classRegistry = _ref$classRegistry === undefined ? new ClassRegistry() : _ref$classRegistry,
variableValues = _ref.variableValues;
return [transformScalars, generateRefetchQueries, transformConnections(variableValues), recordTypeInformation, transformPojosToClassesWithRegistry(classRegistry)];
}
/**
* A function used to decode the response data.
*
* @function decode
* @param {SelectionSet} selection The selection set used to query the response data.
* @param {Object} responseData The response data returned.
* @param {Object} [options] Options to use when decoding including:
* @param {ClassRegistry} [options.classRegistry] A class registry to use when deserializing the data into classes.
* @return {GraphModel} The decoded response data.
*/
function decode(selection, responseData) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var transformers = options.transformers || defaultTransformers(options);
var context = new DecodingContext(selection, responseData);
return decodeContext(context, transformers);
}
function httpFetcher(url) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return function fetcher(graphQLParams) {
return fetch(url, _extends({
body: JSON.stringify(graphQLParams),
method: 'POST',
mode: 'cors' },
options, {
headers: _extends({
'Content-Type': 'application/json',
Accept: 'application/json' },
options.headers) })).
then(function (response) {
return response.json();
});
};
}
function hasNextPage(paginatedModels) {
return paginatedModels && paginatedModels.length && paginatedModels[paginatedModels.length - 1].hasNextPage;
}
/**
* The Client class used to create and send GraphQL documents, fragments, queries and mutations.
*/
var Client$2 = function () {
/**
* @param {Object} typeBundle A set of ES6 modules generated by {@link https://github.com/Shopify/graphql-js-schema|graphql-js-schema}.
* @param {Object} options An options object. Must include either `url` and optional `fetcherOptions` OR a `fetcher` function.
* @param {(String|Function)} options.url|fetcher Either the URL of the GraphQL API endpoint, or a custom fetcher function for further customization.
* @param {Object} [options.fetcherOptions] Additional options to use with `fetch`, like headers. Do not specify this argument if `fetcher` is specified.
* @param {ClassRegistry} [options.registry=new ClassRegistry()] A {@link ClassRegistry} used to decode the response data.
*/
function Client(typeBundle, _ref) {
var url = _ref.url,
fetcherOptions = _ref.fetcherOptions,
fetcher = _ref.fetcher,
_ref$registry = _ref.registry,
registry = _ref$registry === undefined ? new ClassRegistry() : _ref$registry;
classCallCheck(this, Client);
this.typeBundle = typeBundle;
this.classRegistry = registry;
if (url && fetcher) {
throw new Error('Arguments not supported: supply either `url` and optional `fetcherOptions` OR use a `fetcher` function for further customization.');
}
if (url) {
this.fetcher = httpFetcher(url, fetcherOptions);
} else if (fetcher) {
if (fetcherOptions) {
throw new Error('Arguments not supported: when specifying your own `fetcher`, set options through it and not with `fetcherOptions`');
}
this.fetcher = fetcher;
} else {
throw new Error('Invalid arguments: one of `url` or `fetcher` is needed.');
}
}
/**
* Creates a GraphQL document.
*
* @example
* const document = client.document();
*
* @return {Document} A GraphQL document.
*/
createClass(Client, [{
key: 'document',
value: function document() {
return new Document(this.typeBundle);
}
/**
* Creates a GraphQL query.
*
* @example
* const query = client.query('myQuery', (root) => {
* root.add('cat', (cat) => {
* cat.add('name');
* });
* });
*
* @param {String} [name] A name for the query.
* @param {VariableDefinition[]} [variables] A list of variables in the query. See {@link Client#variable}.
* @param {Function} selectionSetCallback The query builder callback.
* A {@link SelectionSet} is created using this callback.
* @return {Query} A GraphQL query.
*/ },
{
key: 'query',
value: function query() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return new (Function.prototype.bind.apply(Query, [null].concat([this.typeBundle], args)))();
}
/**
* Creates a GraphQL mutation.
*
* @example
* const input = client.variable('input', 'CatCreateInput!');
*
* const mutation = client.mutation('myMutation', [input], (root) => {
* root.add('catCreate', {args: {input}}, (catCreate) => {
* catCreate.add('cat', (cat) => {
* cat.add('name');
* });
* });
* });
*
* @param {String} [name] A name for the mutation.
* @param {VariableDefinition[]} [variables] A list of variables in the mutation. See {@link Client#variable}.
* @param {Function} selectionSetCallback The mutation builder callback.
* A {@link SelectionSet} is created using this callback.
* @return {Mutation} A GraphQL mutation.
*/ },
{
key: 'mutation',
value: function mutation() {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return new (Function.prototype.bind.apply(Mutation, [null].concat([this.typeBundle], args)))();
}
/**
* Sends a GraphQL operation (query or mutation) or a document.
*
* @example
* client.send(query, {id: '12345'}).then((result) => {
* // Do something with the returned result
* console.log(result);
* });
*
* @param {(Query|Mutation|Document|Function)} request The operation or document to send. If represented
* as a function, it must return `Query`, `Mutation`, or `Document` and recieve the client as the only param.
* @param {Object} [variableValues] The values for variables in the operation or document.
* @param {Object} [otherProperties] Other properties to send with the query. For example, a custom operation name.
* @return {Promise.<Object>} A promise resolving to an object containing the response data.
*/ },
{
key: 'send',
value: function send(request) {
var _this = this;
var variableValues = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var otherProperties = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var operationOrDocument = void 0;
if (Function.prototype.isPrototypeOf(request)) {
operationOrDocument = request(this);
} else {
operationOrDocument = request;
}
var graphQLParams = { query: operationOrDocument.toString() };
if (variableValues) {
graphQLParams.variables = variableValues;
}
Object.assign(graphQLParams, otherProperties);
var operation = void 0;
if (Operation.prototype.isPrototypeOf(operationOrDocument)) {
operation = operationOrDocument;
} else {
var document = operationOrDocument;
if (document.operations.length === 1) {
operation = document.operations[0];
} else if (otherProperties.operationName) {
operation = document.operations.find(function (documentOperation) {
return documentOperation.name === otherProperties.operationName;
});
} else {
throw new Error('\n A document must contain exactly one operation, or an operationName\n must be specified. Example:\n\n client.send(document, null, {operationName: \'myFancyQuery\'});\n ');
}
}
return this.fetcher(graphQLParams).then(function (response) {
if (response.data) {
response.model = decode(operation, response.data, {
classRegistry: _this.classRegistry,
variableValues: variableValues });
}
return response;
});
}
/**
* Fetches the next page of a paginated node or array of nodes.
*
* @example
* client.fetchNextPage(node, {first: 10}).then((result) => {
* // Do something with the next page
* console.log(result);
* });
*
* @param {(GraphModel|GraphModel[])} nodeOrNodes The node or list of nodes on which to fetch the next page.
* @param {Object} [options] Options object containing:
* @param {Integer} [options.first] The number of nodes to query on the next page. Defaults to the page size of the previous query.
* @return {Promise.<GraphModel[]>} A promise resolving with the next page of {@link GraphModel}s.
*/ },
{
key: 'fetchNextPage',
value: function fetchNextPage(nodeOrNodes, options) {
var node = void 0;
if (Array.isArray(nodeOrNodes)) {
node = nodeOrNodes[nodeOrNodes.length - 1];
} else {
node = nodeOrNodes;
}
var _node$nextPageQueryAn = node.nextPageQueryAndPath(),
_node$nextPageQueryAn2 = slicedToArray(_node$nextPageQueryAn, 2),
query = _node$nextPageQueryAn2[0],
path = _node$nextPageQueryAn2[1];
var variableValues = void 0;
if (node.variableValues || options) {
variableValues = Object.assign({}, node.variableValues, options);
}
return this.send(query, variableValues).then(function (response) {
response.model = path.reduce(function (object, key) {
return object[key];
}, response.model);
return response;
});
}
/**
* Fetches all subsequent pages of a paginated array of nodes.
*
* @example
* client.fetchAllPages(nodes, {pageSize: 20}).then((result) => {
* // Do something with all the models
* console.log(result);
* });
*
* @param {GraphModel[]} paginatedModels The list of nodes on which to fetch all pages.
* @param {Object} options Options object containing:
* @param {Integer} options.pageSize The number of nodes to query on each page.
* @return {Promise.<GraphModel[]>} A promise resolving with all pages of {@link GraphModel}s, including the original list.
*/ },
{
key: 'fetchAllPages',
value: function fetchAllPages(paginatedModels, _ref2) {
var _this2 = this;
var pageSize = _ref2.pageSize;
if (hasNextPage(paginatedModels)) {
return this.fetchNextPage(paginatedModels, { first: pageSize }).then(function (_ref3) {
var model = _ref3.model;
var pages = paginatedModels.concat(model);
return _this2.fetchAllPages(pages, { pageSize: pageSize });
});
}
return Promise.resolve(paginatedModels);
}
/**
* Refetches a {@link GraphModel} whose type implements `Node`.
*
* @example
* client.refetch(node).then((result) => {
* // Do something with the refetched node
* console.log(result);
* });
*
* @param {GraphModel} nodeType A {@link GraphModel} whose type implements `Node`.
* @return {Promise.<GraphModel>} The refetched {@link GraphModel}.
*/ },
{
key: 'refetch',
value: function refetch(nodeType) {
if (!nodeType) {
throw new Error('\'client#refetch\' must be called with a non-null instance of a Node.');
} else if (!nodeType.type.implementsNode) {
throw new Error('\'client#refetch\' must be called with a type that implements Node. Received ' + nodeType.type.name + '.');
}
return this.send(nodeType.refetchQuery()).then(function (_ref4) {
var model = _ref4.model;
return model.node;
});
}
/**
* Creates a variable to be used in a {@link Query} or {@link Mutation}.
*
* @example
* const idVariable = client.variable('id', 'ID!', '12345');
*
* @param {String} name The name of the variable.
* @param {String} type The GraphQL type of the variable.
* @param {*} [defaultValue] The default value of the variable.
* @return {VariableDefinition} A variable object that can be used in a {@link Query} or {@link Mutation}.
*/ },
{
key: 'variable',
value: function variable$$1(name, type, defaultValue) {
return variable(name, type, defaultValue);
}
/**
* Creates an enum to be used in a {@link Query} or {@link Mutation}.
*
* @example
* const titleEnum = client.enum('TITLE');
*
* @param {String} key The key of the enum.
* @return {Enum} An enum object that can be used in a {@link Query} or {@link Mutation}.
*/ },
{
key: 'enum',
value: function _enum(key) {
return enumFunction(key);
} }]);
return Client;
}();
/**
* The class used to configure the JS Buy SDK Client.
* @class
*/
var Config = function () {
createClass$1(Config, [{
key: 'requiredProperties',
/**
* Properties that must be set on initializations
* @attribute requiredProperties
* @default ['storefrontAccessToken', 'domain']
* @type Array
* @private
*/
get: function get$$1() {
return ['storefrontAccessToken', 'domain'];
}
/**
* Deprecated properties that map directly to required properties
* @attribute deprecatedProperties
* @default {'accessToken': 'storefrontAccessToken', 'apiKey': 'storefrontAccessToken'}
* @type Object
* @private
*/ },
{
key: 'deprecatedProperties',
get: function get$$1() {
return {
accessToken: 'storefrontAccessToken',
apiKey: 'storefrontAccessToken' };
}
/**
* @constructs Config
* @param {Object} attrs An object specifying the configuration. Requires the following properties:
* @param {String} attrs.storefrontAccessToken The {@link https://help.shopify.com/api/reference/storefront_access_token|Storefront access token} for the shop.
* @param {String} attrs.domain The `myshopify` domain for the shop (e.g. `graphql.myshopify.com`).
*/ }]);
function Config(attrs) {
var _this = this;
classCallCheck$1(this, Config);
Object.keys(this.deprecatedProperties).forEach(function (key) {
if (!attrs.hasOwnProperty(key)) {
return;
}
// eslint-disable-next-line no-console
console.warn('[ShopifyBuy] Config property ' + key + ' is deprecated as of v1.0, please use ' + _this.deprecatedProperties[key] + ' instead.');
attrs[_this.deprecatedProperties[key]] = attrs[key];
});
this.requiredProperties.forEach(function (key) {
if (attrs.hasOwnProperty(key)) {
_this[key] = attrs[key];
} else {
throw new Error('new Config() requires the option \'' + key + '\'');
}
});
}
return Config;
}();
var Resource = function Resource(client) {
classCallCheck$1(this, Resource);
this.graphQLClient = client;
};
var defaultErrors = [{ message: 'an unknown error has occured.' }];
function defaultResolver(path) {
var keys = path.split('.');
return function (_ref) {
var model = _ref.model,
errors = _ref.errors;
return new Promise(function (resolve, reject) {
try {
var result = keys.reduce(function (ref, key) {
return ref[key];
}, model);
resolve(result);
} catch (_) {
if (errors) {
reject(errors);
} else {
reject(defaultErrors);
}
}
});
};
}
function fetchResourcesForProducts(productOrProduct, client) {
var products = [].concat(productOrProduct);
return Promise.all(products.reduce(function (promiseAcc, product) {
// Fetch the rest of the images and variants for this product
promiseAcc.push(client.fetchAllPages(product.images, { pageSize: 250 }).then(function (images) {
product.attrs.images = images;
}));
promiseAcc.push(client.fetchAllPages(product.variants, { pageSize: 250 }).then(function (variants) {
product.attrs.variants = variants;
}));
return promiseAcc;
}, []));
}
function paginateProductConnectionsAndResolve(client) {
return function (products) {
return fetchResourcesForProducts(products, client).then(function () {
return products;
});
};
}
function paginateCollectionsProductConnectionsAndResolve(client) {
return function (collectionOrCollections) {
var collections = [].concat(collectionOrCollections);
return Promise.all(collections.reduce(function (promiseAcc, collection) {
return promiseAcc.concat(fetchResourcesForProducts(collection.products, client));
}, [])).then(function () {
return collectionOrCollections;
});
};
}
/**
* @namespace ProductHelpers
*/
var productHelpers = {
/**
* Returns the variant of a product corresponding to the options given.
*
* @example
* const selectedVariant = client.product.variantForOptions(product, {
* size: "Small",
* color: "Red"
* });
*
* @memberof ProductHelpers
* @method variantForOptions
* @param {GraphModel} product The product to find the variant on. Must include `variants`.
* @param {Object} options An object containing the options for the variant.
* @return {GraphModel} The variant corresponding to the options given.
*/
variantForOptions: function variantForOptions(product, options) {
return product.variants.find(function (variant) {
return variant.selectedOptions.every(function (selectedOption) {
return options[selectedOption.name] === selectedOption.value.valueOf();
});
});
} };
function query(client) {
var document = client.document();
var spreads = {};
var variables = {};
variables.__defaultOperation__ = {};
variables.__defaultOperation__.id = client.variable("id", "ID!");
spreads.VariantFragment = document.defineFragment("VariantFragment", "ProductVariant", function (root) {
root.add("id");
root.add("title");
root.add("price");
root.add("weight");
root.add("available");
root.add("sku");
root.add("compareAtPrice");
root.add("image", function (image) {
image.add("id");
image.add("src");
image.add("altText");
});
root.add("selectedOptions", function (selectedOptions) {
selectedOptions.add("name");
selectedOptions.add("value");
});
});
spreads.ProductFragment = document.defineFragment("ProductFragment", "Product", function (root) {
root.add("id");
root.add("createdAt");
root.add("updatedAt");
root.add("descriptionHtml");
root.add("description");
root.add("handle");
root.add("productType");
root.add("title");
root.add("vendor");
root.add("tags");
root.add("publishedAt");
root.add("onlineStoreUrl");
root.add("options", function (options) {
options.add("name");
options.add("values");
});
root.add("images", {
args: {
first: 250 } },
function (images) {
images.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
images.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.add("id");
node.add("src");
node.add("altText");
});
});
});
root.add("variants", {
args: {
first: 250 } },
function (variants) {
variants.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
variants.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.addFragment(spreads.VariantFragment);
});
});
});
});
document.addQuery([variables.__defaultOperation__.id], function (root) {
root.add("node", {
args: {
id: variables.__defaultOperation__.id } },
function (node) {
node.addFragment(spreads.ProductFragment);
});
});
return document;
}
function query$1(client) {
var document = client.document();
var spreads = {};
var variables = {};
variables.__defaultOperation__ = {};
variables.__defaultOperation__.ids = client.variable("ids", "[ID!]!");
spreads.VariantFragment = document.defineFragment("VariantFragment", "ProductVariant", function (root) {
root.add("id");
root.add("title");
root.add("price");
root.add("weight");
root.add("available");
root.add("sku");
root.add("compareAtPrice");
root.add("image", function (image) {
image.add("id");
image.add("src");
image.add("altText");
});
root.add("selectedOptions", function (selectedOptions) {
selectedOptions.add("name");
selectedOptions.add("value");
});
});
spreads.ProductFragment = document.defineFragment("ProductFragment", "Product", function (root) {
root.add("id");
root.add("createdAt");
root.add("updatedAt");
root.add("descriptionHtml");
root.add("description");
root.add("handle");
root.add("productType");
root.add("title");
root.add("vendor");
root.add("tags");
root.add("publishedAt");
root.add("onlineStoreUrl");
root.add("options", function (options) {
options.add("name");
options.add("values");
});
root.add("images", {
args: {
first: 250 } },
function (images) {
images.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
images.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.add("id");
node.add("src");
node.add("altText");
});
});
});
root.add("variants", {
args: {
first: 250 } },
function (variants) {
variants.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
variants.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.addFragment(spreads.VariantFragment);
});
});
});
});
document.addQuery([variables.__defaultOperation__.ids], function (root) {
root.add("nodes", {
args: {
ids: variables.__defaultOperation__.ids } },
function (nodes) {
nodes.addFragment(spreads.ProductFragment);
});
});
return document;
}
function query$2(client) {
var document = client.document();
var spreads = {};
var variables = {};
variables.__defaultOperation__ = {};
variables.__defaultOperation__.first = client.variable("first", "Int!");
variables.__defaultOperation__.query = client.variable("query", "String");
variables.__defaultOperation__.sortKey = client.variable("sortKey", "ProductSortKeys");
variables.__defaultOperation__.reverse = client.variable("reverse", "Boolean");
spreads.VariantFragment = document.defineFragment("VariantFragment", "ProductVariant", function (root) {
root.add("id");
root.add("title");
root.add("price");
root.add("weight");
root.add("available");
root.add("sku");
root.add("compareAtPrice");
root.add("image", function (image) {
image.add("id");
image.add("src");
image.add("altText");
});
root.add("selectedOptions", function (selectedOptions) {
selectedOptions.add("name");
selectedOptions.add("value");
});
});
spreads.ProductFragment = document.defineFragment("ProductFragment", "Product", function (root) {
root.add("id");
root.add("createdAt");
root.add("updatedAt");
root.add("descriptionHtml");
root.add("description");
root.add("handle");
root.add("productType");
root.add("title");
root.add("vendor");
root.add("tags");
root.add("publishedAt");
root.add("onlineStoreUrl");
root.add("options", function (options) {
options.add("name");
options.add("values");
});
root.add("images", {
args: {
first: 250 } },
function (images) {
images.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
images.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.add("id");
node.add("src");
node.add("altText");
});
});
});
root.add("variants", {
args: {
first: 250 } },
function (variants) {
variants.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
variants.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.addFragment(spreads.VariantFragment);
});
});
});
});
document.addQuery([variables.__defaultOperation__.first, variables.__defaultOperation__.query, variables.__defaultOperation__.sortKey, variables.__defaultOperation__.reverse], function (root) {
root.add("shop", function (shop) {
shop.add("products", {
args: {
first: variables.__defaultOperation__.first,
query: variables.__defaultOperation__.query,
sortKey: variables.__defaultOperation__.sortKey,
reverse: variables.__defaultOperation__.reverse } },
function (products) {
products.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
products.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.addFragment(spreads.ProductFragment);
});
});
});
});
});
return document;
}
function query$3(client) {
var document = client.document();
var spreads = {};
var variables = {};
variables.__defaultOperation__ = {};
variables.__defaultOperation__.handle = client.variable("handle", "String!");
spreads.VariantFragment = document.defineFragment("VariantFragment", "ProductVariant", function (root) {
root.add("id");
root.add("title");
root.add("price");
root.add("weight");
root.add("available");
root.add("sku");
root.add("compareAtPrice");
root.add("image", function (image) {
image.add("id");
image.add("src");
image.add("altText");
});
root.add("selectedOptions", function (selectedOptions) {
selectedOptions.add("name");
selectedOptions.add("value");
});
});
spreads.ProductFragment = document.defineFragment("ProductFragment", "Product", function (root) {
root.add("id");
root.add("createdAt");
root.add("updatedAt");
root.add("descriptionHtml");
root.add("description");
root.add("handle");
root.add("productType");
root.add("title");
root.add("vendor");
root.add("tags");
root.add("publishedAt");
root.add("onlineStoreUrl");
root.add("options", function (options) {
options.add("name");
options.add("values");
});
root.add("images", {
args: {
first: 250 } },
function (images) {
images.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
images.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.add("id");
node.add("src");
node.add("altText");
});
});
});
root.add("variants", {
args: {
first: 250 } },
function (variants) {
variants.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
variants.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.addFragment(spreads.VariantFragment);
});
});
});
});
document.addQuery([variables.__defaultOperation__.handle], function (root) {
root.add("shop", function (shop) {
shop.add("productByHandle", {
args: {
handle: variables.__defaultOperation__.handle } },
function (productByHandle) {
productByHandle.addFragment(spreads.ProductFragment);
});
});
});
return document;
}
// GraphQL
/**
* The JS Buy SDK product resource
* @class
*/
var ProductResource = function (_Resource) {
inherits$1(ProductResource, _Resource);
function ProductResource() {
classCallCheck$1(this, ProductResource);
return possibleConstructorReturn$1(this, (ProductResource.__proto__ || Object.getPrototypeOf(ProductResource)).apply(this, arguments));
}
createClass$1(ProductResource, [{
key: 'fetchAll',
/**
* Fetches all products on the shop.
*
* @example
* client.product.fetchAll().then((products) => {
* // Do something with the products
* });
*
* @param {Int} [pageSize] The number of products to fetch per page
* @return {Promise|GraphModel[]} A promise resolving with an array of `GraphModel`s of the products.
*/
value: function fetchAll() {
var first = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 20;
return this.graphQLClient.send(query$2, { first: first }).then(defaultResolver('shop.products')).then(paginateProductConnectionsAndResolve(this.graphQLClient));
}
/**
* Fetches a single product by ID on the shop.
*
* @example
* client.product.fetch('Xk9lM2JkNzFmNzIQ4NTIY4ZDFi9DaGVja291dC9lM2JkN==').then((product) => {
* // Do something with the product
* });
*
* @param {String} id The id of the product to fetch.
* @return {Promise|GraphModel} A promise resolving with a `GraphModel` of the product.
*/ },
{
key: 'fetch',
value: function fetch(id) {
return this.graphQLClient.send(query, { id: id }).then(defaultResolver('node')).then(paginateProductConnectionsAndResolve(this.graphQLClient));
}
/**
* Fetches multiple products by ID on the shop.
*
* @example
* const ids = ['Xk9lM2JkNzFmNzIQ4NTIY4ZDFi9DaGVja291dC9lM2JkN==', 'Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0Lzc4NTc5ODkzODQ='];
* client.product.fetchMultiple(ids).then((products) => {
* // Do something with the products
* });
*
* @param {String[]} ids The ids of the products to fetch
* @return {Promise|GraphModel[]} A promise resolving with a `GraphModel` of the product.
*/ },
{
key: 'fetchMultiple',
value: function fetchMultiple(ids) {
return this.graphQLClient.send(query$1, { ids: ids }).then(defaultResolver('nodes')).then(paginateProductConnectionsAndResolve(this.graphQLClient));
}
/**
* Fetches a single product by handle on the shop.
*
* @example
* client.product.fetchByHandle('my-product').then((product) => {
* // Do something with the product
* });
*
* @param {String} handle The handle of the product to fetch.
* @return {Promise|GraphModel} A promise resolving with a `GraphModel` of the product.
*/ },
{
key: 'fetchByHandle',
value: function fetchByHandle(handle) {
return this.graphQLClient.send(query$3, { handle: handle }).then(defaultResolver('shop.productByHandle')).then(paginateProductConnectionsAndResolve(this.graphQLClient));
}
/**
* Fetches all products on the shop that match the query.
*
* @example
* client.product.fetchQuery({first: 20, sortKey: 'CREATED_AT', reverse: true}).then((products) => {
* // Do something with the first 10 products sorted by title in ascending order
* });
*
* @param {Object} [args] An object specifying the query data containing zero or more of:
* @param {Int} [args.first=20] The relay `first` param. This specifies page size.
* @param {String} [args.sortKey=ID] The key to sort results by. Available values are
* documented as {@link https://help.shopify.com/api/storefront-api/reference/enum/productsortkeys|Product Sort Keys}.
* @param {String} [args.query] A query string. See full documentation {@link https://help.shopify.com/api/storefront-api/reference/object/shop#products|here}
* @param {Boolean} [args.reverse] Whether or not to reverse the sort order of the results
* @return {Promise|GraphModel[]} A promise resolving with an array of `GraphModel`s of the products.
*/ },
{
key: 'fetchQuery',
value: function fetchQuery() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$first = _ref.first,
first = _ref$first === undefined ? 20 : _ref$first,
_ref$sortKey = _ref.sortKey,
sortKey = _ref$sortKey === undefined ? 'ID' : _ref$sortKey,
query$$1 = _ref.query,
reverse = _ref.reverse;
return this.graphQLClient.send(query$2, {
first: first,
sortKey: sortKey,
query: query$$1,
reverse: reverse }).
then(defaultResolver('shop.products')).then(paginateProductConnectionsAndResolve(this.graphQLClient));
} },
{
key: 'helpers',
get: function get$$1() {
return productHelpers;
} }]);
return ProductResource;
}(Resource);
function query$4(client) {
var document = client.document();
var spreads = {};
var variables = {};
variables.__defaultOperation__ = {};
variables.__defaultOperation__.id = client.variable("id", "ID!");
spreads.CollectionFragment = document.defineFragment("CollectionFragment", "Collection", function (root) {
root.add("id");
root.add("handle");
root.add("description");
root.add("descriptionHtml");
root.add("updatedAt");
root.add("title");
root.add("image", function (image) {
image.add("id");
image.add("src");
image.add("altText");
});
});
document.addQuery([variables.__defaultOperation__.id], function (root) {
root.add("node", {
args: {
id: variables.__defaultOperation__.id } },
function (node) {
node.addFragment(spreads.CollectionFragment);
});
});
return document;
}
function query$5(client) {
var document = client.document();
var spreads = {};
var variables = {};
variables.__defaultOperation__ = {};
variables.__defaultOperation__.id = client.variable("id", "ID!");
spreads.VariantFragment = document.defineFragment("VariantFragment", "ProductVariant", function (root) {
root.add("id");
root.add("title");
root.add("price");
root.add("weight");
root.add("available");
root.add("sku");
root.add("compareAtPrice");
root.add("image", function (image) {
image.add("id");
image.add("src");
image.add("altText");
});
root.add("selectedOptions", function (selectedOptions) {
selectedOptions.add("name");
selectedOptions.add("value");
});
});
spreads.ProductFragment = document.defineFragment("ProductFragment", "Product", function (root) {
root.add("id");
root.add("createdAt");
root.add("updatedAt");
root.add("descriptionHtml");
root.add("description");
root.add("handle");
root.add("productType");
root.add("title");
root.add("vendor");
root.add("tags");
root.add("publishedAt");
root.add("onlineStoreUrl");
root.add("options", function (options) {
options.add("name");
options.add("values");
});
root.add("images", {
args: {
first: 250 } },
function (images) {
images.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
images.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.add("id");
node.add("src");
node.add("altText");
});
});
});
root.add("variants", {
args: {
first: 250 } },
function (variants) {
variants.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
variants.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.addFragment(spreads.VariantFragment);
});
});
});
});
spreads.CollectionFragment = document.defineFragment("CollectionFragment", "Collection", function (root) {
root.add("id");
root.add("handle");
root.add("description");
root.add("descriptionHtml");
root.add("updatedAt");
root.add("title");
root.add("image", function (image) {
image.add("id");
image.add("src");
image.add("altText");
});
});
spreads.CollectionsProductsFragment = document.defineFragment("CollectionsProductsFragment", "Collection", function (root) {
root.add("products", {
args: {
first: 20 } },
function (products) {
products.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
products.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.addFragment(spreads.ProductFragment);
});
});
});
});
document.addQuery([variables.__defaultOperation__.id], function (root) {
root.add("node", {
args: {
id: variables.__defaultOperation__.id } },
function (node) {
node.addFragment(spreads.CollectionFragment);
node.addFragment(spreads.CollectionsProductsFragment);
});
});
return document;
}
function query$6(client) {
var document = client.document();
var spreads = {};
var variables = {};
variables.__defaultOperation__ = {};
variables.__defaultOperation__.first = client.variable("first", "Int!");
variables.__defaultOperation__.query = client.variable("query", "String");
variables.__defaultOperation__.sortKey = client.variable("sortKey", "CollectionSortKeys");
variables.__defaultOperation__.reverse = client.variable("reverse", "Boolean");
spreads.CollectionFragment = document.defineFragment("CollectionFragment", "Collection", function (root) {
root.add("id");
root.add("handle");
root.add("description");
root.add("descriptionHtml");
root.add("updatedAt");
root.add("title");
root.add("image", function (image) {
image.add("id");
image.add("src");
image.add("altText");
});
});
document.addQuery([variables.__defaultOperation__.first, variables.__defaultOperation__.query, variables.__defaultOperation__.sortKey, variables.__defaultOperation__.reverse], function (root) {
root.add("shop", function (shop) {
shop.add("collections", {
args: {
first: variables.__defaultOperation__.first,
query: variables.__defaultOperation__.query,
sortKey: variables.__defaultOperation__.sortKey,
reverse: variables.__defaultOperation__.reverse } },
function (collections) {
collections.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
collections.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.addFragment(spreads.CollectionFragment);
});
});
});
});
});
return document;
}
function query$7(client) {
var document = client.document();
var spreads = {};
var variables = {};
variables.__defaultOperation__ = {};
variables.__defaultOperation__.first = client.variable("first", "Int!");
variables.__defaultOperation__.query = client.variable("query", "String");
variables.__defaultOperation__.sortKey = client.variable("sortKey", "CollectionSortKeys");
variables.__defaultOperation__.reverse = client.variable("reverse", "Boolean");
variables.__defaultOperation__.productsFirst = client.variable("productsFirst", "Int!");
spreads.VariantFragment = document.defineFragment("VariantFragment", "ProductVariant", function (root) {
root.add("id");
root.add("title");
root.add("price");
root.add("weight");
root.add("available");
root.add("sku");
root.add("compareAtPrice");
root.add("image", function (image) {
image.add("id");
image.add("src");
image.add("altText");
});
root.add("selectedOptions", function (selectedOptions) {
selectedOptions.add("name");
selectedOptions.add("value");
});
});
spreads.CollectionFragment = document.defineFragment("CollectionFragment", "Collection", function (root) {
root.add("id");
root.add("handle");
root.add("description");
root.add("descriptionHtml");
root.add("updatedAt");
root.add("title");
root.add("image", function (image) {
image.add("id");
image.add("src");
image.add("altText");
});
});
spreads.ProductFragment = document.defineFragment("ProductFragment", "Product", function (root) {
root.add("id");
root.add("createdAt");
root.add("updatedAt");
root.add("descriptionHtml");
root.add("description");
root.add("handle");
root.add("productType");
root.add("title");
root.add("vendor");
root.add("tags");
root.add("publishedAt");
root.add("onlineStoreUrl");
root.add("options", function (options) {
options.add("name");
options.add("values");
});
root.add("images", {
args: {
first: 250 } },
function (images) {
images.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
images.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.add("id");
node.add("src");
node.add("altText");
});
});
});
root.add("variants", {
args: {
first: 250 } },
function (variants) {
variants.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
variants.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.addFragment(spreads.VariantFragment);
});
});
});
});
document.addQuery([variables.__defaultOperation__.first, variables.__defaultOperation__.query, variables.__defaultOperation__.sortKey, variables.__defaultOperation__.reverse, variables.__defaultOperation__.productsFirst], function (root) {
root.add("shop", function (shop) {
shop.add("collections", {
args: {
first: variables.__defaultOperation__.first,
query: variables.__defaultOperation__.query,
sortKey: variables.__defaultOperation__.sortKey,
reverse: variables.__defaultOperation__.reverse } },
function (collections) {
collections.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
collections.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.addFragment(spreads.CollectionFragment);
node.add("products", {
args: {
first: variables.__defaultOperation__.productsFirst } },
function (products) {
products.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
products.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.addFragment(spreads.ProductFragment);
});
});
});
});
});
});
});
});
return document;
}
function query$8(client) {
var document = client.document();
var spreads = {};
var variables = {};
variables.__defaultOperation__ = {};
variables.__defaultOperation__.handle = client.variable("handle", "String!");
spreads.VariantFragment = document.defineFragment("VariantFragment", "ProductVariant", function (root) {
root.add("id");
root.add("title");
root.add("price");
root.add("weight");
root.add("available");
root.add("sku");
root.add("compareAtPrice");
root.add("image", function (image) {
image.add("id");
image.add("src");
image.add("altText");
});
root.add("selectedOptions", function (selectedOptions) {
selectedOptions.add("name");
selectedOptions.add("value");
});
});
spreads.ProductFragment = document.defineFragment("ProductFragment", "Product", function (root) {
root.add("id");
root.add("createdAt");
root.add("updatedAt");
root.add("descriptionHtml");
root.add("description");
root.add("handle");
root.add("productType");
root.add("title");
root.add("vendor");
root.add("tags");
root.add("publishedAt");
root.add("onlineStoreUrl");
root.add("options", function (options) {
options.add("name");
options.add("values");
});
root.add("images", {
args: {
first: 250 } },
function (images) {
images.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
images.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.add("id");
node.add("src");
node.add("altText");
});
});
});
root.add("variants", {
args: {
first: 250 } },
function (variants) {
variants.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
variants.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.addFragment(spreads.VariantFragment);
});
});
});
});
spreads.CollectionFragment = document.defineFragment("CollectionFragment", "Collection", function (root) {
root.add("id");
root.add("handle");
root.add("description");
root.add("descriptionHtml");
root.add("updatedAt");
root.add("title");
root.add("image", function (image) {
image.add("id");
image.add("src");
image.add("altText");
});
});
spreads.CollectionsProductsFragment = document.defineFragment("CollectionsProductsFragment", "Collection", function (root) {
root.add("products", {
args: {
first: 20 } },
function (products) {
products.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
products.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.addFragment(spreads.ProductFragment);
});
});
});
});
document.addQuery([variables.__defaultOperation__.handle], function (root) {
root.add("shop", function (shop) {
shop.add("collectionByHandle", {
args: {
handle: variables.__defaultOperation__.handle } },
function (collectionByHandle) {
collectionByHandle.addFragment(spreads.CollectionFragment);
collectionByHandle.addFragment(spreads.CollectionsProductsFragment);
});
});
});
return document;
}
// GraphQL
/**
* The JS Buy SDK collection resource
* @class
*/
var CollectionResource = function (_Resource) {
inherits$1(CollectionResource, _Resource);
function CollectionResource() {
classCallCheck$1(this, CollectionResource);
return possibleConstructorReturn$1(this, (CollectionResource.__proto__ || Object.getPrototypeOf(CollectionResource)).apply(this, arguments));
}
createClass$1(CollectionResource, [{
key: 'fetchAll',
/**
* Fetches all collections on the shop, not including products.
* To fetch collections with products use [fetchAllsWithProducts]{@link Client#fetchAllsWithProducts}.
*
* @example
* client.collection.fetchAll().then((collections) => {
* // Do something with the collections
* });
*
* @return {Promise|GraphModel[]} A promise resolving with an array of `GraphModel`s of the collections.
*/
value: function fetchAll() {
var first = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 20;
return this.graphQLClient.send(query$6, { first: first }).then(defaultResolver('shop.collections'));
}
/**
* Fetches all collections on the shop, including products.
*
* @example
* client.collection.fetchAllWithProducts().then((collections) => {
* // Do something with the collections
* });
*
* @return {Promise|GraphModel[]} A promise resolving with an array of `GraphModel`s of the collections.
*/ },
{
key: 'fetchAllWithProducts',
value: function fetchAllWithProducts() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$first = _ref.first,
first = _ref$first === undefined ? 20 : _ref$first,
_ref$productsFirst = _ref.productsFirst,
productsFirst = _ref$productsFirst === undefined ? 20 : _ref$productsFirst;
return this.graphQLClient.send(query$7, { first: first, productsFirst: productsFirst }).then(defaultResolver('shop.collections')).then(paginateCollectionsProductConnectionsAndResolve(this.graphQLClient));
}
/**
* Fetches a single collection by ID on the shop, not including products.
* To fetch the collection with products use [fetchWithProducts]{@link Client#fetchWithProducts}.
*
* @example
* client.collection.fetch('Xk9lM2JkNzFmNzIQ4NTIY4ZDFiZTUyZTUwNTE2MDNhZjg==').then((collection) => {
* // Do something with the collection
* });
*
* @param {String} id The id of the collection to fetch.
* @return {Promise|GraphModel} A promise resolving with a `GraphModel` of the collection.
*/ },
{
key: 'fetch',
value: function fetch(id) {
return this.graphQLClient.send(query$4, { id: id }).then(defaultResolver('node'));
}
/**
* Fetches a single collection by ID on the shop, including products.
*
* @example
* client.collection.fetchWithProducts('Xk9lM2JkNzFmNzIQ4NTIY4ZDFiZTUyZTUwNTE2MDNhZjg==').then((collection) => {
* // Do something with the collection
* });
*
* @param {String} id The id of the collection to fetch.
* @return {Promise|GraphModel} A promise resolving with a `GraphModel` of the collection.
*/ },
{
key: 'fetchWithProducts',
value: function fetchWithProducts(id) {
return this.graphQLClient.send(query$5, { id: id }).then(defaultResolver('node')).then(paginateCollectionsProductConnectionsAndResolve(this.graphQLClient));
}
/**
* Fetches a collection by handle on the shop.
*
* @example
* client.collection.fetchByHandle('my-collection').then((collection) => {
* // Do something with the collection
* });
*
* @param {String} handle The handle of the collection to fetch.
* @return {Promise|GraphModel} A promise resolving with a `GraphModel` of the collection.
*/ },
{
key: 'fetchByHandle',
value: function fetchByHandle(handle) {
return this.graphQLClient.send(query$8, { handle: handle }).then(defaultResolver('shop.collectionByHandle'));
}
/**
* Fetches all collections on the shop that match the query.
*
* @example
* client.collection.fetchQuery({first: 20, sortKey: 'CREATED_AT', reverse: true}).then((collections) => {
* // Do something with the first 10 collections sorted by title in ascending order
* });
*
* @param {Object} [args] An object specifying the query data containing zero or more of:
* @param {Int} [args.first=20] The relay `first` param. This specifies page size.
* @param {String} [args.sortKey=ID] The key to sort results by. Available values are
* documented as {@link https://help.shopify.com/api/storefront-api/reference/enum/collectionsortkeys|Collection Sort Keys}.
* @param {String} [args.query] A query string. See full documentation {@link https://help.shopify.com/api/storefront-api/reference/object/shop#collections|here}
* @param {Boolean} [args.reverse] Whether or not to reverse the sort order of the results
* @return {Promise|GraphModel[]} A promise resolving with an array of `GraphModel`s of the collections.
*/ },
{
key: 'fetchQuery',
value: function fetchQuery() {
var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref2$first = _ref2.first,
first = _ref2$first === undefined ? 20 : _ref2$first,
_ref2$sortKey = _ref2.sortKey,
sortKey = _ref2$sortKey === undefined ? 'ID' : _ref2$sortKey,
query = _ref2.query,
reverse = _ref2.reverse;
return this.graphQLClient.send(query$6, {
first: first,
sortKey: sortKey,
query: query,
reverse: reverse }).
then(defaultResolver('shop.collections'));
} }]);
return CollectionResource;
}(Resource);
function query$9(client) {
var document = client.document();
document.addQuery(function (root) {
root.add("shop", function (shop) {
shop.add("currencyCode");
shop.add("description");
shop.add("moneyFormat");
shop.add("name");
shop.add("primaryDomain", function (primaryDomain) {
primaryDomain.add("host");
primaryDomain.add("sslEnabled");
primaryDomain.add("url");
});
});
});
return document;
}
function query$10(client) {
var document = client.document();
var spreads = {};
spreads.PolicyFragment = document.defineFragment("PolicyFragment", "ShopPolicy", function (root) {
root.add("id");
root.add("title");
root.add("url");
root.add("body");
});
document.addQuery(function (root) {
root.add("shop", function (shop) {
shop.add("privacyPolicy", function (privacyPolicy) {
privacyPolicy.addFragment(spreads.PolicyFragment);
});
shop.add("termsOfService", function (termsOfService) {
termsOfService.addFragment(spreads.PolicyFragment);
});
shop.add("refundPolicy", function (refundPolicy) {
refundPolicy.addFragment(spreads.PolicyFragment);
});
});
});
return document;
}
// GraphQL
/**
* The JS Buy SDK shop resource
* @class
*/
var ShopResource = function (_Resource) {
inherits$1(ShopResource, _Resource);
function ShopResource() {
classCallCheck$1(this, ShopResource);
return possibleConstructorReturn$1(this, (ShopResource.__proto__ || Object.getPrototypeOf(ShopResource)).apply(this, arguments));
}
createClass$1(ShopResource, [{
key: 'fetchInfo',
/**
* Fetches shop information (`currencyCode`, `description`, `moneyFormat`, `name`, and `primaryDomain`).
* See the {@link https://help.shopify.com/api/storefront-api/reference/object/shop|Storefront API reference} for more information.
*
* @example
* client.shop.fetchInfo().then((shop) => {
* // Do something with the shop
* });
*
* @return {Promise|GraphModel} A promise resolving with a `GraphModel` of the shop.
*/
value: function fetchInfo() {
return this.graphQLClient.send(query$9).then(defaultResolver('shop'));
}
/**
* Fetches shop policies (privacy policy, terms of service and refund policy).
*
* @example
* client.shop.fetchPolicies().then((shop) => {
* // Do something with the shop
* });
*
* @return {Promise|GraphModel} A promise resolving with a `GraphModel` of the shop.
*/ },
{
key: 'fetchPolicies',
value: function fetchPolicies() {
return this.graphQLClient.send(query$10).then(defaultResolver('shop'));
} }]);
return ShopResource;
}(Resource);
function handleCheckoutMutation(mutationRootKey, client) {
return function (_ref) {
var data = _ref.data,
errors = _ref.errors,
model = _ref.model;
var rootData = data[mutationRootKey];
var rootModel = model[mutationRootKey];
if (rootData && rootData.checkout) {
return client.fetchAllPages(rootModel.checkout.lineItems, { pageSize: 250 }).then(function (lineItems) {
rootModel.checkout.attrs.lineItems = lineItems;
rootModel.checkout.errors = errors;
rootModel.checkout.userErrors = rootModel.userErrors;
return rootModel.checkout;
});
}
if (errors && errors.length) {
return Promise.reject(new Error(JSON.stringify(errors)));
}
if (rootData && rootData.userErrors && rootData.userErrors.length) {
return Promise.reject(new Error(JSON.stringify(rootData.userErrors)));
}
return Promise.reject(new Error("The " + mutationRootKey + " mutation failed due to an unknown error."));
};
}
function query$11(client) {
var document = client.document();
var spreads = {};
var variables = {};
variables.__defaultOperation__ = {};
variables.__defaultOperation__.id = client.variable("id", "ID!");
spreads.VariantFragment = document.defineFragment("VariantFragment", "ProductVariant", function (root) {
root.add("id");
root.add("title");
root.add("price");
root.add("weight");
root.add("available");
root.add("sku");
root.add("compareAtPrice");
root.add("image", function (image) {
image.add("id");
image.add("src");
image.add("altText");
});
root.add("selectedOptions", function (selectedOptions) {
selectedOptions.add("name");
selectedOptions.add("value");
});
});
spreads.VariantWithProductFragment = document.defineFragment("VariantWithProductFragment", "ProductVariant", function (root) {
root.addFragment(spreads.VariantFragment);
root.add("product", function (product) {
product.add("id");
});
});
spreads.MailingAddressFragment = document.defineFragment("MailingAddressFragment", "MailingAddress", function (root) {
root.add("id");
root.add("address1");
root.add("address2");
root.add("city");
root.add("company");
root.add("country");
root.add("firstName");
root.add("formatted");
root.add("lastName");
root.add("latitude");
root.add("longitude");
root.add("phone");
root.add("province");
root.add("zip");
root.add("name");
root.add("countryCode");
root.add("provinceCode");
});
spreads.CheckoutFragment = document.defineFragment("CheckoutFragment", "Checkout", function (root) {
root.add("id");
root.add("ready");
root.add("requiresShipping");
root.add("note");
root.add("paymentDue");
root.add("webUrl");
root.add("orderStatusUrl");
root.add("taxExempt");
root.add("taxesIncluded");
root.add("currencyCode");
root.add("totalTax");
root.add("subtotalPrice");
root.add("totalPrice");
root.add("completedAt");
root.add("createdAt");
root.add("updatedAt");
root.add("shippingAddress", function (shippingAddress) {
shippingAddress.addFragment(spreads.MailingAddressFragment);
});
root.add("shippingLine", function (shippingLine) {
shippingLine.add("handle");
shippingLine.add("price");
shippingLine.add("title");
});
root.add("customAttributes", function (customAttributes) {
customAttributes.add("key");
customAttributes.add("value");
});
root.add("order", function (order) {
order.add("id");
order.add("processedAt");
order.add("orderNumber");
order.add("subtotalPrice");
order.add("totalShippingPrice");
order.add("totalTax");
order.add("totalPrice");
order.add("currencyCode");
order.add("totalRefunded");
order.add("customerUrl");
order.add("shippingAddress", function (shippingAddress) {
shippingAddress.addFragment(spreads.MailingAddressFragment);
});
order.add("lineItems", {
args: {
first: 250 } },
function (lineItems) {
lineItems.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
lineItems.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.add("title");
node.add("variant", function (variant) {
variant.addFragment(spreads.VariantWithProductFragment);
});
node.add("quantity");
node.add("customAttributes", function (customAttributes) {
customAttributes.add("key");
customAttributes.add("value");
});
});
});
});
});
root.add("lineItems", {
args: {
first: 250 } },
function (lineItems) {
lineItems.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
lineItems.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.add("id");
node.add("title");
node.add("variant", function (variant) {
variant.addFragment(spreads.VariantWithProductFragment);
});
node.add("quantity");
node.add("customAttributes", function (customAttributes) {
customAttributes.add("key");
customAttributes.add("value");
});
});
});
});
});
document.addQuery([variables.__defaultOperation__.id], function (root) {
root.add("node", {
args: {
id: variables.__defaultOperation__.id } },
function (node) {
node.addFragment(spreads.CheckoutFragment);
});
});
return document;
}
function query$12(client) {
var document = client.document();
var spreads = {};
var variables = {};
variables.__defaultOperation__ = {};
variables.__defaultOperation__.input = client.variable("input", "CheckoutCreateInput!");
spreads.VariantFragment = document.defineFragment("VariantFragment", "ProductVariant", function (root) {
root.add("id");
root.add("title");
root.add("price");
root.add("weight");
root.add("available");
root.add("sku");
root.add("compareAtPrice");
root.add("image", function (image) {
image.add("id");
image.add("src");
image.add("altText");
});
root.add("selectedOptions", function (selectedOptions) {
selectedOptions.add("name");
selectedOptions.add("value");
});
});
spreads.VariantWithProductFragment = document.defineFragment("VariantWithProductFragment", "ProductVariant", function (root) {
root.addFragment(spreads.VariantFragment);
root.add("product", function (product) {
product.add("id");
});
});
spreads.UserErrorFragment = document.defineFragment("UserErrorFragment", "UserError", function (root) {
root.add("field");
root.add("message");
});
spreads.MailingAddressFragment = document.defineFragment("MailingAddressFragment", "MailingAddress", function (root) {
root.add("id");
root.add("address1");
root.add("address2");
root.add("city");
root.add("company");
root.add("country");
root.add("firstName");
root.add("formatted");
root.add("lastName");
root.add("latitude");
root.add("longitude");
root.add("phone");
root.add("province");
root.add("zip");
root.add("name");
root.add("countryCode");
root.add("provinceCode");
});
spreads.CheckoutFragment = document.defineFragment("CheckoutFragment", "Checkout", function (root) {
root.add("id");
root.add("ready");
root.add("requiresShipping");
root.add("note");
root.add("paymentDue");
root.add("webUrl");
root.add("orderStatusUrl");
root.add("taxExempt");
root.add("taxesIncluded");
root.add("currencyCode");
root.add("totalTax");
root.add("subtotalPrice");
root.add("totalPrice");
root.add("completedAt");
root.add("createdAt");
root.add("updatedAt");
root.add("shippingAddress", function (shippingAddress) {
shippingAddress.addFragment(spreads.MailingAddressFragment);
});
root.add("shippingLine", function (shippingLine) {
shippingLine.add("handle");
shippingLine.add("price");
shippingLine.add("title");
});
root.add("customAttributes", function (customAttributes) {
customAttributes.add("key");
customAttributes.add("value");
});
root.add("order", function (order) {
order.add("id");
order.add("processedAt");
order.add("orderNumber");
order.add("subtotalPrice");
order.add("totalShippingPrice");
order.add("totalTax");
order.add("totalPrice");
order.add("currencyCode");
order.add("totalRefunded");
order.add("customerUrl");
order.add("shippingAddress", function (shippingAddress) {
shippingAddress.addFragment(spreads.MailingAddressFragment);
});
order.add("lineItems", {
args: {
first: 250 } },
function (lineItems) {
lineItems.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
lineItems.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.add("title");
node.add("variant", function (variant) {
variant.addFragment(spreads.VariantWithProductFragment);
});
node.add("quantity");
node.add("customAttributes", function (customAttributes) {
customAttributes.add("key");
customAttributes.add("value");
});
});
});
});
});
root.add("lineItems", {
args: {
first: 250 } },
function (lineItems) {
lineItems.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
lineItems.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.add("id");
node.add("title");
node.add("variant", function (variant) {
variant.addFragment(spreads.VariantWithProductFragment);
});
node.add("quantity");
node.add("customAttributes", function (customAttributes) {
customAttributes.add("key");
customAttributes.add("value");
});
});
});
});
});
document.addMutation([variables.__defaultOperation__.input], function (root) {
root.add("checkoutCreate", {
args: {
input: variables.__defaultOperation__.input } },
function (checkoutCreate) {
checkoutCreate.add("userErrors", function (userErrors) {
userErrors.addFragment(spreads.UserErrorFragment);
});
checkoutCreate.add("checkout", function (checkout) {
checkout.addFragment(spreads.CheckoutFragment);
});
});
});
return document;
}
function query$13(client) {
var document = client.document();
var spreads = {};
var variables = {};
variables.__defaultOperation__ = {};
variables.__defaultOperation__.checkoutId = client.variable("checkoutId", "ID!");
variables.__defaultOperation__.lineItems = client.variable("lineItems", "[CheckoutLineItemInput!]!");
spreads.VariantFragment = document.defineFragment("VariantFragment", "ProductVariant", function (root) {
root.add("id");
root.add("title");
root.add("price");
root.add("weight");
root.add("available");
root.add("sku");
root.add("compareAtPrice");
root.add("image", function (image) {
image.add("id");
image.add("src");
image.add("altText");
});
root.add("selectedOptions", function (selectedOptions) {
selectedOptions.add("name");
selectedOptions.add("value");
});
});
spreads.VariantWithProductFragment = document.defineFragment("VariantWithProductFragment", "ProductVariant", function (root) {
root.addFragment(spreads.VariantFragment);
root.add("product", function (product) {
product.add("id");
});
});
spreads.UserErrorFragment = document.defineFragment("UserErrorFragment", "UserError", function (root) {
root.add("field");
root.add("message");
});
spreads.MailingAddressFragment = document.defineFragment("MailingAddressFragment", "MailingAddress", function (root) {
root.add("id");
root.add("address1");
root.add("address2");
root.add("city");
root.add("company");
root.add("country");
root.add("firstName");
root.add("formatted");
root.add("lastName");
root.add("latitude");
root.add("longitude");
root.add("phone");
root.add("province");
root.add("zip");
root.add("name");
root.add("countryCode");
root.add("provinceCode");
});
spreads.CheckoutFragment = document.defineFragment("CheckoutFragment", "Checkout", function (root) {
root.add("id");
root.add("ready");
root.add("requiresShipping");
root.add("note");
root.add("paymentDue");
root.add("webUrl");
root.add("orderStatusUrl");
root.add("taxExempt");
root.add("taxesIncluded");
root.add("currencyCode");
root.add("totalTax");
root.add("subtotalPrice");
root.add("totalPrice");
root.add("completedAt");
root.add("createdAt");
root.add("updatedAt");
root.add("shippingAddress", function (shippingAddress) {
shippingAddress.addFragment(spreads.MailingAddressFragment);
});
root.add("shippingLine", function (shippingLine) {
shippingLine.add("handle");
shippingLine.add("price");
shippingLine.add("title");
});
root.add("customAttributes", function (customAttributes) {
customAttributes.add("key");
customAttributes.add("value");
});
root.add("order", function (order) {
order.add("id");
order.add("processedAt");
order.add("orderNumber");
order.add("subtotalPrice");
order.add("totalShippingPrice");
order.add("totalTax");
order.add("totalPrice");
order.add("currencyCode");
order.add("totalRefunded");
order.add("customerUrl");
order.add("shippingAddress", function (shippingAddress) {
shippingAddress.addFragment(spreads.MailingAddressFragment);
});
order.add("lineItems", {
args: {
first: 250 } },
function (lineItems) {
lineItems.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
lineItems.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.add("title");
node.add("variant", function (variant) {
variant.addFragment(spreads.VariantWithProductFragment);
});
node.add("quantity");
node.add("customAttributes", function (customAttributes) {
customAttributes.add("key");
customAttributes.add("value");
});
});
});
});
});
root.add("lineItems", {
args: {
first: 250 } },
function (lineItems) {
lineItems.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
lineItems.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.add("id");
node.add("title");
node.add("variant", function (variant) {
variant.addFragment(spreads.VariantWithProductFragment);
});
node.add("quantity");
node.add("customAttributes", function (customAttributes) {
customAttributes.add("key");
customAttributes.add("value");
});
});
});
});
});
document.addMutation([variables.__defaultOperation__.checkoutId, variables.__defaultOperation__.lineItems], function (root) {
root.add("checkoutLineItemsAdd", {
args: {
checkoutId: variables.__defaultOperation__.checkoutId,
lineItems: variables.__defaultOperation__.lineItems } },
function (checkoutLineItemsAdd) {
checkoutLineItemsAdd.add("userErrors", function (userErrors) {
userErrors.addFragment(spreads.UserErrorFragment);
});
checkoutLineItemsAdd.add("checkout", function (checkout) {
checkout.addFragment(spreads.CheckoutFragment);
});
});
});
return document;
}
function query$14(client) {
var document = client.document();
var spreads = {};
var variables = {};
variables.__defaultOperation__ = {};
variables.__defaultOperation__.checkoutId = client.variable("checkoutId", "ID!");
variables.__defaultOperation__.lineItemIds = client.variable("lineItemIds", "[ID!]!");
spreads.VariantFragment = document.defineFragment("VariantFragment", "ProductVariant", function (root) {
root.add("id");
root.add("title");
root.add("price");
root.add("weight");
root.add("available");
root.add("sku");
root.add("compareAtPrice");
root.add("image", function (image) {
image.add("id");
image.add("src");
image.add("altText");
});
root.add("selectedOptions", function (selectedOptions) {
selectedOptions.add("name");
selectedOptions.add("value");
});
});
spreads.VariantWithProductFragment = document.defineFragment("VariantWithProductFragment", "ProductVariant", function (root) {
root.addFragment(spreads.VariantFragment);
root.add("product", function (product) {
product.add("id");
});
});
spreads.UserErrorFragment = document.defineFragment("UserErrorFragment", "UserError", function (root) {
root.add("field");
root.add("message");
});
spreads.MailingAddressFragment = document.defineFragment("MailingAddressFragment", "MailingAddress", function (root) {
root.add("id");
root.add("address1");
root.add("address2");
root.add("city");
root.add("company");
root.add("country");
root.add("firstName");
root.add("formatted");
root.add("lastName");
root.add("latitude");
root.add("longitude");
root.add("phone");
root.add("province");
root.add("zip");
root.add("name");
root.add("countryCode");
root.add("provinceCode");
});
spreads.CheckoutFragment = document.defineFragment("CheckoutFragment", "Checkout", function (root) {
root.add("id");
root.add("ready");
root.add("requiresShipping");
root.add("note");
root.add("paymentDue");
root.add("webUrl");
root.add("orderStatusUrl");
root.add("taxExempt");
root.add("taxesIncluded");
root.add("currencyCode");
root.add("totalTax");
root.add("subtotalPrice");
root.add("totalPrice");
root.add("completedAt");
root.add("createdAt");
root.add("updatedAt");
root.add("shippingAddress", function (shippingAddress) {
shippingAddress.addFragment(spreads.MailingAddressFragment);
});
root.add("shippingLine", function (shippingLine) {
shippingLine.add("handle");
shippingLine.add("price");
shippingLine.add("title");
});
root.add("customAttributes", function (customAttributes) {
customAttributes.add("key");
customAttributes.add("value");
});
root.add("order", function (order) {
order.add("id");
order.add("processedAt");
order.add("orderNumber");
order.add("subtotalPrice");
order.add("totalShippingPrice");
order.add("totalTax");
order.add("totalPrice");
order.add("currencyCode");
order.add("totalRefunded");
order.add("customerUrl");
order.add("shippingAddress", function (shippingAddress) {
shippingAddress.addFragment(spreads.MailingAddressFragment);
});
order.add("lineItems", {
args: {
first: 250 } },
function (lineItems) {
lineItems.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
lineItems.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.add("title");
node.add("variant", function (variant) {
variant.addFragment(spreads.VariantWithProductFragment);
});
node.add("quantity");
node.add("customAttributes", function (customAttributes) {
customAttributes.add("key");
customAttributes.add("value");
});
});
});
});
});
root.add("lineItems", {
args: {
first: 250 } },
function (lineItems) {
lineItems.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
lineItems.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.add("id");
node.add("title");
node.add("variant", function (variant) {
variant.addFragment(spreads.VariantWithProductFragment);
});
node.add("quantity");
node.add("customAttributes", function (customAttributes) {
customAttributes.add("key");
customAttributes.add("value");
});
});
});
});
});
document.addMutation([variables.__defaultOperation__.checkoutId, variables.__defaultOperation__.lineItemIds], function (root) {
root.add("checkoutLineItemsRemove", {
args: {
checkoutId: variables.__defaultOperation__.checkoutId,
lineItemIds: variables.__defaultOperation__.lineItemIds } },
function (checkoutLineItemsRemove) {
checkoutLineItemsRemove.add("userErrors", function (userErrors) {
userErrors.addFragment(spreads.UserErrorFragment);
});
checkoutLineItemsRemove.add("checkout", function (checkout) {
checkout.addFragment(spreads.CheckoutFragment);
});
});
});
return document;
}
function query$15(client) {
var document = client.document();
var spreads = {};
var variables = {};
variables.__defaultOperation__ = {};
variables.__defaultOperation__.checkoutId = client.variable("checkoutId", "ID!");
variables.__defaultOperation__.lineItems = client.variable("lineItems", "[CheckoutLineItemUpdateInput!]!");
spreads.VariantFragment = document.defineFragment("VariantFragment", "ProductVariant", function (root) {
root.add("id");
root.add("title");
root.add("price");
root.add("weight");
root.add("available");
root.add("sku");
root.add("compareAtPrice");
root.add("image", function (image) {
image.add("id");
image.add("src");
image.add("altText");
});
root.add("selectedOptions", function (selectedOptions) {
selectedOptions.add("name");
selectedOptions.add("value");
});
});
spreads.VariantWithProductFragment = document.defineFragment("VariantWithProductFragment", "ProductVariant", function (root) {
root.addFragment(spreads.VariantFragment);
root.add("product", function (product) {
product.add("id");
});
});
spreads.UserErrorFragment = document.defineFragment("UserErrorFragment", "UserError", function (root) {
root.add("field");
root.add("message");
});
spreads.MailingAddressFragment = document.defineFragment("MailingAddressFragment", "MailingAddress", function (root) {
root.add("id");
root.add("address1");
root.add("address2");
root.add("city");
root.add("company");
root.add("country");
root.add("firstName");
root.add("formatted");
root.add("lastName");
root.add("latitude");
root.add("longitude");
root.add("phone");
root.add("province");
root.add("zip");
root.add("name");
root.add("countryCode");
root.add("provinceCode");
});
spreads.CheckoutFragment = document.defineFragment("CheckoutFragment", "Checkout", function (root) {
root.add("id");
root.add("ready");
root.add("requiresShipping");
root.add("note");
root.add("paymentDue");
root.add("webUrl");
root.add("orderStatusUrl");
root.add("taxExempt");
root.add("taxesIncluded");
root.add("currencyCode");
root.add("totalTax");
root.add("subtotalPrice");
root.add("totalPrice");
root.add("completedAt");
root.add("createdAt");
root.add("updatedAt");
root.add("shippingAddress", function (shippingAddress) {
shippingAddress.addFragment(spreads.MailingAddressFragment);
});
root.add("shippingLine", function (shippingLine) {
shippingLine.add("handle");
shippingLine.add("price");
shippingLine.add("title");
});
root.add("customAttributes", function (customAttributes) {
customAttributes.add("key");
customAttributes.add("value");
});
root.add("order", function (order) {
order.add("id");
order.add("processedAt");
order.add("orderNumber");
order.add("subtotalPrice");
order.add("totalShippingPrice");
order.add("totalTax");
order.add("totalPrice");
order.add("currencyCode");
order.add("totalRefunded");
order.add("customerUrl");
order.add("shippingAddress", function (shippingAddress) {
shippingAddress.addFragment(spreads.MailingAddressFragment);
});
order.add("lineItems", {
args: {
first: 250 } },
function (lineItems) {
lineItems.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
lineItems.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.add("title");
node.add("variant", function (variant) {
variant.addFragment(spreads.VariantWithProductFragment);
});
node.add("quantity");
node.add("customAttributes", function (customAttributes) {
customAttributes.add("key");
customAttributes.add("value");
});
});
});
});
});
root.add("lineItems", {
args: {
first: 250 } },
function (lineItems) {
lineItems.add("pageInfo", function (pageInfo) {
pageInfo.add("hasNextPage");
pageInfo.add("hasPreviousPage");
});
lineItems.add("edges", function (edges) {
edges.add("cursor");
edges.add("node", function (node) {
node.add("id");
node.add("title");
node.add("variant", function (variant) {
variant.addFragment(spreads.VariantWithProductFragment);
});
node.add("quantity");
node.add("customAttributes", function (customAttributes) {
customAttributes.add("key");
customAttributes.add("value");
});
});
});
});
});
document.addMutation([variables.__defaultOperation__.checkoutId, variables.__defaultOperation__.lineItems], function (root) {
root.add("checkoutLineItemsUpdate", {
args: {
checkoutId: variables.__defaultOperation__.checkoutId,
lineItems: variables.__defaultOperation__.lineItems } },
function (checkoutLineItemsUpdate) {
checkoutLineItemsUpdate.add("userErrors", function (userErrors) {
userErrors.addFragment(spreads.UserErrorFragment);
});
checkoutLineItemsUpdate.add("checkout", function (checkout) {
checkout.addFragment(spreads.CheckoutFragment);
});
});
});
return document;
}
// GraphQL
/**
* The JS Buy SDK checkout resource
* @class
*/
var CheckoutResource = function (_Resource) {
inherits$1(CheckoutResource, _Resource);
function CheckoutResource() {
classCallCheck$1(this, CheckoutResource);
return possibleConstructorReturn$1(this, (CheckoutResource.__proto__ || Object.getPrototypeOf(CheckoutResource)).apply(this, arguments));
}
createClass$1(CheckoutResource, [{
key: 'fetch',
/**
* Fetches a checkout by ID.
*
* @example
* client.checkout.fetch('FlZj9rZXlN5MDY4ZDFiZTUyZTUwNTE2MDNhZjg=').then((checkout) => {
* // Do something with the checkout
* });
*
* @param {String} id The id of the checkout to fetch.
* @return {Promise|GraphModel} A promise resolving with a `GraphModel` of the checkout.
*/
value: function fetch(id) {
var _this2 = this;
return this.graphQLClient.send(query$11, { id: id }).then(defaultResolver('node')).then(function (checkout) {
return _this2.graphQLClient.fetchAllPages(checkout.lineItems, { pageSize: 250 }).then(function (lineItems) {
checkout.attrs.lineItems = lineItems;
return checkout;
});
});
}
/**
* Creates a checkout.
*
* @example
* const input = {
* lineItems: [
* {variantId: 'Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0VmFyaWFudC8yOTEwNjAyMjc5Mg==', quantity: 5}
* ]
* };
*
* client.checkout.create(input).then((checkout) => {
* // Do something with the newly created checkout
* });
*
* @param {Object} [input] An input object containing zero or more of:
* @param {String} [input.email] An email connected to the checkout.
* @param {Object[]} [input.lineItems] A list of line items in the checkout. See the {@link https://help.shopify.com/api/storefront-api/reference/input_object/checkoutlineiteminput|Storefront API reference} for valid input fields for each line item.
* @param {Object} [input.shippingAddress] A shipping address. See the {@link https://help.shopify.com/api/storefront-api/reference/input_object/mailingaddressinput|Storefront API reference} for valid input fields.
* @param {String} [input.note] A note for the checkout.
* @param {Object[]} [input.customAttributes] A list of custom attributes for the checkout. See the {@link https://help.shopify.com/api/storefront-api/reference/input_object/attributeinput|Storefront API reference} for valid input fields.
* @return {Promise|GraphModel} A promise resolving with the created checkout.
*/ },
{
key: 'create',
value: function create() {
var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return this.graphQLClient.send(query$12, { input: input }).then(handleCheckoutMutation('checkoutCreate', this.graphQLClient));
}
/**
* Adds line items to an existing checkout.
*
* @example
* const checkoutId = 'Z2lkOi8vc2hvcGlmeS9DaGVja291dC9kMTZmM2EzMDM4Yjc4N=';
* const lineItems = [{variantId: 'Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0VmFyaWFudC8yOTEwNjAyMjc5Mg==', quantity: 5}];
*
* client.checkout.addLineItems(checkoutId, lineItems).then((checkout) => {
* // Do something with the updated checkout
* });
*
* @param {String} checkoutId The ID of the checkout to add line items to.
* @param {Object[]} lineItems A list of line items to add to the checkout. See the {@link https://help.shopify.com/api/storefront-api/reference/input_object/checkoutlineiteminput|Storefront API reference} for valid input fields for each line item.
* @return {Promise|GraphModel} A promise resolving with the updated checkout.
*/ },
{
key: 'addLineItems',
value: function addLineItems(checkoutId, lineItems) {
return this.graphQLClient.send(query$13, { checkoutId: checkoutId, lineItems: lineItems }).then(handleCheckoutMutation('checkoutLineItemsAdd', this.graphQLClient));
}
/**
* Removes line items from an existing checkout.
*
* @example
* const checkoutId = 'Z2lkOi8vc2hvcGlmeS9DaGVja291dC9kMTZmM2EzMDM4Yjc4N=';
* const lineItemIds = ['TViZGE5Y2U1ZDFhY2FiMmM2YT9rZXk9NTc2YjBhODcwNWIxYzg0YjE5ZjRmZGQ5NjczNGVkZGU='];
*
* client.checkout.removeLineItems(checkoutId, lineItemIds).then((checkout) => {
* // Do something with the updated checkout
* });
*
* @param {String} checkoutId The ID of the checkout to remove line items from.
* @param {String[]} lineItemIds A list of the ids of line items to remove from the checkout.
* @return {Promise|GraphModel} A promise resolving with the updated checkout.
*/ },
{
key: 'removeLineItems',
value: function removeLineItems(checkoutId, lineItemIds) {
return this.graphQLClient.send(query$14, { checkoutId: checkoutId, lineItemIds: lineItemIds }).then(handleCheckoutMutation('checkoutLineItemsRemove', this.graphQLClient));
}
/**
* Updates line items on an existing checkout.
*
* @example
* const checkoutId = 'Z2lkOi8vc2hvcGlmeS9DaGVja291dC9kMTZmM2EzMDM4Yjc4N=';
* const lineItems = [
* {
* id: 'TViZGE5Y2U1ZDFhY2FiMmM2YT9rZXk9NTc2YjBhODcwNWIxYzg0YjE5ZjRmZGQ5NjczNGVkZGU=',
* quantity: 5,
* variantId: 'Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0VmFyaWFudC8yOTEwNjAyMjc5Mg=='
* }
* ];
*
* client.checkout.updateLineItems(checkoutId, lineItems).then(checkout => {
* // Do something with the updated checkout
* });
*
* @param {String} checkoutId The ID of the checkout to update a line item on.
* @param {Object[]} lineItems A list of line item information to update. See the {@link https://help.shopify.com/api/storefront-api/reference/input_object/checkoutlineitemupdateinput|Storefront API reference} for valid input fields for each line item.
* @return {Promise|GraphModel} A promise resolving with the updated checkout.
*/ },
{
key: 'updateLineItems',
value: function updateLineItems(checkoutId, lineItems) {
return this.graphQLClient.send(query$15, { checkoutId: checkoutId, lineItems: lineItems }).then(handleCheckoutMutation('checkoutLineItemsUpdate', this.graphQLClient));
} }]);
return CheckoutResource;
}(Resource);
/**
* @namespace ImageHelpers
*/
var imageHelpers = {
/**
* Generates the image src for a resized image with maximum dimensions `maxWidth` and `maxHeight`.
* Images do not scale up.
*
* @example
* const url = client.image.imageForSize(product.variants[0].image, {maxWidth: 50, maxHeight: 50});
*
* @memberof ImageHelpers
* @method imageForSize
* @param {Object} image The original image model to generate the image src for.
* @param {Object} options An options object containing:
* @param {Integer} options.maxWidth The maximum width for the image.
* @param {Integer} options.maxHeight The maximum height for the image.
* @return {String} The image src for the resized image.
*/
imageForSize: function imageForSize(image, _ref) {
var maxWidth = _ref.maxWidth,
maxHeight = _ref.maxHeight;
var splitUrl = image.src.split('?');
var notQuery = splitUrl[0];
var query = splitUrl[1] ? '?' + splitUrl[1] : '';
// Use the section before the query
var imageTokens = notQuery.split('.');
// Take the token before the file extension and append the dimensions
var imagePathIndex = imageTokens.length - 2;
imageTokens[imagePathIndex] = imageTokens[imagePathIndex] + '_' + maxWidth + 'x' + maxHeight;
return '' + imageTokens.join('.') + query;
} };
/**
* The JS Buy SDK image resource
* @class
*/
var ImageResource = function (_Resource) {
inherits$1(ImageResource, _Resource);
function ImageResource() {
classCallCheck$1(this, ImageResource);
return possibleConstructorReturn$1(this, (ImageResource.__proto__ || Object.getPrototypeOf(ImageResource)).apply(this, arguments));
}
createClass$1(ImageResource, [{
key: 'helpers',
get: function get$$1() {
return imageHelpers;
} }]);
return ImageResource;
}(Resource);
var version = "1.4.0";
var QueryRoot = {
"name": "QueryRoot",
"kind": "OBJECT",
"fieldBaseTypes": {
"node": "Node",
"nodes": "Node",
"shop": "Shop" },
"implementsNode": false };
var Node = {
"name": "Node",
"kind": "INTERFACE",
"fieldBaseTypes": {},
"possibleTypes": ["AppliedGiftCard", "Article", "Blog", "Checkout", "CheckoutLineItem", "Collection", "Comment", "MailingAddress", "Order", "Payment", "Product", "ProductOption", "ProductVariant", "ShopPolicy"] };
var ID = {
"name": "ID",
"kind": "SCALAR" };
var String$1 = {
"name": "String",
"kind": "SCALAR" };
var Boolean$1 = {
"name": "Boolean",
"kind": "SCALAR" };
var DateTime = {
"name": "DateTime",
"kind": "SCALAR" };
var MailingAddress = {
"name": "MailingAddress",
"kind": "OBJECT",
"fieldBaseTypes": {
"address1": "String",
"address2": "String",
"city": "String",
"company": "String",
"country": "String",
"countryCode": "String",
"firstName": "String",
"formatted": "String",
"id": "ID",
"lastName": "String",
"latitude": "Float",
"longitude": "Float",
"name": "String",
"phone": "String",
"province": "String",
"provinceCode": "String",
"zip": "String" },
"implementsNode": true };
var Float = {
"name": "Float",
"kind": "SCALAR" };
var PageInfo = {
"name": "PageInfo",
"kind": "OBJECT",
"fieldBaseTypes": {
"hasNextPage": "Boolean",
"hasPreviousPage": "Boolean" },
"implementsNode": false };
var Int = {
"name": "Int",
"kind": "SCALAR" };
var Order = {
"name": "Order",
"kind": "OBJECT",
"fieldBaseTypes": {
"currencyCode": "CurrencyCode",
"customerUrl": "URL",
"id": "ID",
"lineItems": "OrderLineItemConnection",
"orderNumber": "Int",
"processedAt": "DateTime",
"shippingAddress": "MailingAddress",
"subtotalPrice": "Money",
"totalPrice": "Money",
"totalRefunded": "Money",
"totalShippingPrice": "Money",
"totalTax": "Money" },
"implementsNode": true };
var Money = {
"name": "Money",
"kind": "SCALAR" };
var CurrencyCode = {
"name": "CurrencyCode",
"kind": "ENUM" };
var URL = {
"name": "URL",
"kind": "SCALAR" };
var OrderLineItemConnection = {
"name": "OrderLineItemConnection",
"kind": "OBJECT",
"fieldBaseTypes": {
"edges": "OrderLineItemEdge",
"pageInfo": "PageInfo" },
"implementsNode": false };
var OrderLineItemEdge = {
"name": "OrderLineItemEdge",
"kind": "OBJECT",
"fieldBaseTypes": {
"cursor": "String",
"node": "OrderLineItem" },
"implementsNode": false };
var OrderLineItem = {
"name": "OrderLineItem",
"kind": "OBJECT",
"fieldBaseTypes": {
"customAttributes": "Attribute",
"quantity": "Int",
"title": "String",
"variant": "ProductVariant" },
"implementsNode": false };
var ProductVariant = {
"name": "ProductVariant",
"kind": "OBJECT",
"fieldBaseTypes": {
"available": "Boolean",
"compareAtPrice": "Money",
"id": "ID",
"image": "Image",
"price": "Money",
"product": "Product",
"selectedOptions": "SelectedOption",
"sku": "String",
"title": "String",
"weight": "Float" },
"implementsNode": true };
var Image = {
"name": "Image",
"kind": "OBJECT",
"fieldBaseTypes": {
"altText": "String",
"id": "ID",
"src": "URL" },
"implementsNode": false };
var SelectedOption = {
"name": "SelectedOption",
"kind": "OBJECT",
"fieldBaseTypes": {
"name": "String",
"value": "String" },
"implementsNode": false };
var Product = {
"name": "Product",
"kind": "OBJECT",
"fieldBaseTypes": {
"createdAt": "DateTime",
"description": "String",
"descriptionHtml": "HTML",
"handle": "String",
"id": "ID",
"images": "ImageConnection",
"onlineStoreUrl": "URL",
"options": "ProductOption",
"productType": "String",
"publishedAt": "DateTime",
"tags": "String",
"title": "String",
"updatedAt": "DateTime",
"variants": "ProductVariantConnection",
"vendor": "String" },
"implementsNode": true };
var CollectionConnection = {
"name": "CollectionConnection",
"kind": "OBJECT",
"fieldBaseTypes": {
"edges": "CollectionEdge",
"pageInfo": "PageInfo" },
"implementsNode": false };
var CollectionEdge = {
"name": "CollectionEdge",
"kind": "OBJECT",
"fieldBaseTypes": {
"cursor": "String",
"node": "Collection" },
"implementsNode": false };
var Collection = {
"name": "Collection",
"kind": "OBJECT",
"fieldBaseTypes": {
"description": "String",
"descriptionHtml": "HTML",
"handle": "String",
"id": "ID",
"image": "Image",
"products": "ProductConnection",
"title": "String",
"updatedAt": "DateTime" },
"implementsNode": true };
var HTML = {
"name": "HTML",
"kind": "SCALAR" };
var ProductConnection = {
"name": "ProductConnection",
"kind": "OBJECT",
"fieldBaseTypes": {
"edges": "ProductEdge",
"pageInfo": "PageInfo" },
"implementsNode": false };
var ProductEdge = {
"name": "ProductEdge",
"kind": "OBJECT",
"fieldBaseTypes": {
"cursor": "String",
"node": "Product" },
"implementsNode": false };
var ImageConnection = {
"name": "ImageConnection",
"kind": "OBJECT",
"fieldBaseTypes": {
"edges": "ImageEdge",
"pageInfo": "PageInfo" },
"implementsNode": false };
var ImageEdge = {
"name": "ImageEdge",
"kind": "OBJECT",
"fieldBaseTypes": {
"cursor": "String",
"node": "Image" },
"implementsNode": false };
var ProductOption = {
"name": "ProductOption",
"kind": "OBJECT",
"fieldBaseTypes": {
"name": "String",
"values": "String" },
"implementsNode": true };
var ProductVariantConnection = {
"name": "ProductVariantConnection",
"kind": "OBJECT",
"fieldBaseTypes": {
"edges": "ProductVariantEdge",
"pageInfo": "PageInfo" },
"implementsNode": false };
var ProductVariantEdge = {
"name": "ProductVariantEdge",
"kind": "OBJECT",
"fieldBaseTypes": {
"cursor": "String",
"node": "ProductVariant" },
"implementsNode": false };
var Attribute = {
"name": "Attribute",
"kind": "OBJECT",
"fieldBaseTypes": {
"key": "String",
"value": "String" },
"implementsNode": false };
var Shop = {
"name": "Shop",
"kind": "OBJECT",
"fieldBaseTypes": {
"collectionByHandle": "Collection",
"collections": "CollectionConnection",
"currencyCode": "CurrencyCode",
"description": "String",
"moneyFormat": "String",
"name": "String",
"primaryDomain": "Domain",
"privacyPolicy": "ShopPolicy",
"productByHandle": "Product",
"products": "ProductConnection",
"refundPolicy": "ShopPolicy",
"termsOfService": "ShopPolicy" },
"implementsNode": false };
var Domain = {
"name": "Domain",
"kind": "OBJECT",
"fieldBaseTypes": {
"host": "String",
"sslEnabled": "Boolean",
"url": "URL" },
"implementsNode": false };
var ShopPolicy = {
"name": "ShopPolicy",
"kind": "OBJECT",
"fieldBaseTypes": {
"body": "String",
"id": "ID",
"title": "String",
"url": "URL" },
"implementsNode": true };
var Mutation$1 = {
"name": "Mutation",
"kind": "OBJECT",
"fieldBaseTypes": {
"checkoutCreate": "CheckoutCreatePayload",
"checkoutLineItemsAdd": "CheckoutLineItemsAddPayload",
"checkoutLineItemsRemove": "CheckoutLineItemsRemovePayload",
"checkoutLineItemsUpdate": "CheckoutLineItemsUpdatePayload" },
"implementsNode": false,
"relayInputObjectBaseTypes": {
"checkoutAttributesUpdate": "CheckoutAttributesUpdateInput",
"checkoutCreate": "CheckoutCreateInput",
"customerAccessTokenCreate": "CustomerAccessTokenCreateInput",
"customerActivate": "CustomerActivateInput",
"customerCreate": "CustomerCreateInput",
"customerReset": "CustomerResetInput" } };
var UserError = {
"name": "UserError",
"kind": "OBJECT",
"fieldBaseTypes": {
"field": "String",
"message": "String" },
"implementsNode": false };
var Checkout = {
"name": "Checkout",
"kind": "OBJECT",
"fieldBaseTypes": {
"completedAt": "DateTime",
"createdAt": "DateTime",
"currencyCode": "CurrencyCode",
"customAttributes": "Attribute",
"id": "ID",
"lineItems": "CheckoutLineItemConnection",
"note": "String",
"order": "Order",
"orderStatusUrl": "URL",
"paymentDue": "Money",
"ready": "Boolean",
"requiresShipping": "Boolean",
"shippingAddress": "MailingAddress",
"shippingLine": "ShippingRate",
"subtotalPrice": "Money",
"taxExempt": "Boolean",
"taxesIncluded": "Boolean",
"totalPrice": "Money",
"totalTax": "Money",
"updatedAt": "DateTime",
"webUrl": "URL" },
"implementsNode": true };
var CheckoutLineItemConnection = {
"name": "CheckoutLineItemConnection",
"kind": "OBJECT",
"fieldBaseTypes": {
"edges": "CheckoutLineItemEdge",
"pageInfo": "PageInfo" },
"implementsNode": false };
var CheckoutLineItemEdge = {
"name": "CheckoutLineItemEdge",
"kind": "OBJECT",
"fieldBaseTypes": {
"cursor": "String",
"node": "CheckoutLineItem" },
"implementsNode": false };
var CheckoutLineItem = {
"name": "CheckoutLineItem",
"kind": "OBJECT",
"fieldBaseTypes": {
"customAttributes": "Attribute",
"id": "ID",
"quantity": "Int",
"title": "String",
"variant": "ProductVariant" },
"implementsNode": true };
var ShippingRate = {
"name": "ShippingRate",
"kind": "OBJECT",
"fieldBaseTypes": {
"handle": "String",
"price": "Money",
"title": "String" },
"implementsNode": false };
var CheckoutCreatePayload = {
"name": "CheckoutCreatePayload",
"kind": "OBJECT",
"fieldBaseTypes": {
"checkout": "Checkout",
"userErrors": "UserError" },
"implementsNode": false };
var CheckoutLineItemsAddPayload = {
"name": "CheckoutLineItemsAddPayload",
"kind": "OBJECT",
"fieldBaseTypes": {
"checkout": "Checkout",
"userErrors": "UserError" },
"implementsNode": false };
var CheckoutLineItemsRemovePayload = {
"name": "CheckoutLineItemsRemovePayload",
"kind": "OBJECT",
"fieldBaseTypes": {
"checkout": "Checkout",
"userErrors": "UserError" },
"implementsNode": false };
var CheckoutLineItemsUpdatePayload = {
"name": "CheckoutLineItemsUpdatePayload",
"kind": "OBJECT",
"fieldBaseTypes": {
"checkout": "Checkout",
"userErrors": "UserError" },
"implementsNode": false };
var Types = {
types: {} };
Types.types["QueryRoot"] = QueryRoot;
Types.types["Node"] = Node;
Types.types["ID"] = ID;
Types.types["String"] = String$1;
Types.types["Boolean"] = Boolean$1;
Types.types["DateTime"] = DateTime;
Types.types["MailingAddress"] = MailingAddress;
Types.types["Float"] = Float;
Types.types["PageInfo"] = PageInfo;
Types.types["Int"] = Int;
Types.types["Order"] = Order;
Types.types["Money"] = Money;
Types.types["CurrencyCode"] = CurrencyCode;
Types.types["URL"] = URL;
Types.types["OrderLineItemConnection"] = OrderLineItemConnection;
Types.types["OrderLineItemEdge"] = OrderLineItemEdge;
Types.types["OrderLineItem"] = OrderLineItem;
Types.types["ProductVariant"] = ProductVariant;
Types.types["Image"] = Image;
Types.types["SelectedOption"] = SelectedOption;
Types.types["Product"] = Product;
Types.types["CollectionConnection"] = CollectionConnection;
Types.types["CollectionEdge"] = CollectionEdge;
Types.types["Collection"] = Collection;
Types.types["HTML"] = HTML;
Types.types["ProductConnection"] = ProductConnection;
Types.types["ProductEdge"] = ProductEdge;
Types.types["ImageConnection"] = ImageConnection;
Types.types["ImageEdge"] = ImageEdge;
Types.types["ProductOption"] = ProductOption;
Types.types["ProductVariantConnection"] = ProductVariantConnection;
Types.types["ProductVariantEdge"] = ProductVariantEdge;
Types.types["Attribute"] = Attribute;
Types.types["Shop"] = Shop;
Types.types["Domain"] = Domain;
Types.types["ShopPolicy"] = ShopPolicy;
Types.types["Mutation"] = Mutation$1;
Types.types["UserError"] = UserError;
Types.types["Checkout"] = Checkout;
Types.types["CheckoutLineItemConnection"] = CheckoutLineItemConnection;
Types.types["CheckoutLineItemEdge"] = CheckoutLineItemEdge;
Types.types["CheckoutLineItem"] = CheckoutLineItem;
Types.types["ShippingRate"] = ShippingRate;
Types.types["CheckoutCreatePayload"] = CheckoutCreatePayload;
Types.types["CheckoutLineItemsAddPayload"] = CheckoutLineItemsAddPayload;
Types.types["CheckoutLineItemsRemovePayload"] = CheckoutLineItemsRemovePayload;
Types.types["CheckoutLineItemsUpdatePayload"] = CheckoutLineItemsUpdatePayload;
Types.queryType = "QueryRoot";
Types.mutationType = "Mutation";
Types.subscriptionType = null;
function recursivelyFreezeObject(structure) {
Object.getOwnPropertyNames(structure).forEach(function (key) {
var value = structure[key];
if (value && (typeof value === "undefined" ? "undefined" : _typeof(value)) === 'object') {
recursivelyFreezeObject(value);
}
});
Object.freeze(structure);
return structure;
}
var types = recursivelyFreezeObject(Types);
// GraphQL
/**
* The JS Buy SDK Client.
* @class
*
* @property {ProductResource} product The property under which product fetching methods live.
* @property {CollectionResource} collection The property under which collection fetching methods live.
* @property {ShopResource} shop The property under which shop fetching methods live.
* @property {CheckoutResource} checkout The property under which shop fetching and mutating methods live.
* @property {ImageResource} image The property under which image helper methods live.
*/
var Client = function () {
createClass$1(Client, null, [{
key: 'buildClient',
/**
* Primary entry point for building a new Client.
*/
value: function buildClient(config, fetchFunction) {
var newConfig = new Config(config);
var client = new Client(newConfig, Client$2, fetchFunction);
client.config = newConfig;
return client;
}
/**
* @constructs Client
* @param {Config} config An instance of {@link Config} used to configure the Client.
*/ }]);
function Client(config) {
var GraphQLClientClass = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Client$2;
var fetchFunction = arguments[2];
classCallCheck$1(this, Client);
var url = 'https://' + config.domain + '/api/graphql';
var headers = {
'X-SDK-Variant': 'javascript',
'X-SDK-Version': version,
'X-Shopify-Storefront-Access-Token': config.storefrontAccessToken };
if (fetchFunction) {
headers['Content-Type'] = 'application/json';
headers.Accept = 'application/json';
this.graphQLClient = new GraphQLClientClass(types, {
fetcher: function fetcher(graphQLParams) {
return fetchFunction(url, {
body: JSON.stringify(graphQLParams),
method: 'POST',
mode: 'cors',
headers: headers }).
then(function (response) {
return response.json();
});
} });
} else {
this.graphQLClient = new GraphQLClientClass(types, {
url: url,
fetcherOptions: { headers: headers } });
}
this.product = new ProductResource(this.graphQLClient);
this.collection = new CollectionResource(this.graphQLClient);
this.shop = new ShopResource(this.graphQLClient);
this.checkout = new CheckoutResource(this.graphQLClient);
this.image = new ImageResource(this.graphQLClient);
}
/**
* Fetches the next page of models
*
* @example
* client.fetchNextPage(products).then((nextProducts) => {
* // Do something with the products
* });
*
* @param {models} [Array] The paginated set to fetch the next page of
* @return {Promise|GraphModel[]} A promise resolving with an array of `GraphModel`s of the type provided.
*/
createClass$1(Client, [{
key: 'fetchNextPage',
value: function fetchNextPage(models) {
return this.graphQLClient.fetchNextPage(models);
} }]);
return Client;
}();
module.exports = Client;
//# sourceMappingURL=index.js.map
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_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;}; /*
_ _ _ _
___| (_) ___| | __ (_)___
/ __| | |/ __| |/ / | / __|
\__ \ | | (__| < _ | \__ \
|___/_|_|\___|_|\_(_)/ |___/
|__/
Version: 1.8.1
Author: Ken Wheeler
Website: http://kenwheeler.github.io
Docs: http://kenwheeler.github.io/slick
Repo: http://github.com/kenwheeler/slick
Issues: http://github.com/kenwheeler/slick/issues
*/
/* global window, document, define, jQuery, setInterval, clearInterval */
;(function (factory) {
'use strict';
if (true) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(10)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (typeof exports !== 'undefined') {
module.exports = factory(require('jquery'));
} else {
factory(jQuery);
}
})(function ($) {
'use strict';
var Slick = window.Slick || {};
Slick = function () {
var instanceUid = 0;
function Slick(element, settings) {
var _ = this,dataSettings;
_.defaults = {
accessibility: true,
adaptiveHeight: false,
appendArrows: $(element),
appendDots: $(element),
arrows: true,
asNavFor: null,
prevArrow: '<button class="slick-prev" aria-label="Previous" type="button">Previous</button>',
nextArrow: '<button class="slick-next" aria-label="Next" type="button">Next</button>',
autoplay: false,
autoplaySpeed: 3000,
centerMode: false,
centerPadding: '50px',
cssEase: 'ease',
customPaging: function customPaging(slider, i) {
return $('<button type="button" />').text(i + 1);
},
dots: false,
dotsClass: 'slick-dots',
draggable: true,
easing: 'linear',
edgeFriction: 0.35,
fade: false,
focusOnSelect: false,
focusOnChange: false,
infinite: true,
initialSlide: 0,
lazyLoad: 'ondemand',
mobileFirst: false,
pauseOnHover: true,
pauseOnFocus: true,
pauseOnDotsHover: false,
respondTo: 'window',
responsive: null,
rows: 1,
rtl: false,
slide: '',
slidesPerRow: 1,
slidesToShow: 1,
slidesToScroll: 1,
speed: 500,
swipe: true,
swipeToSlide: false,
touchMove: true,
touchThreshold: 5,
useCSS: true,
useTransform: true,
variableWidth: false,
vertical: false,
verticalSwiping: false,
waitForAnimate: true,
zIndex: 1000 };
_.initials = {
animating: false,
dragging: false,
autoPlayTimer: null,
currentDirection: 0,
currentLeft: null,
currentSlide: 0,
direction: 1,
$dots: null,
listWidth: null,
listHeight: null,
loadIndex: 0,
$nextArrow: null,
$prevArrow: null,
scrolling: false,
slideCount: null,
slideWidth: null,
$slideTrack: null,
$slides: null,
sliding: false,
slideOffset: 0,
swipeLeft: null,
swiping: false,
$list: null,
touchObject: {},
transformsEnabled: false,
unslicked: false };
$.extend(_, _.initials);
_.activeBreakpoint = null;
_.animType = null;
_.animProp = null;
_.breakpoints = [];
_.breakpointSettings = [];
_.cssTransitions = false;
_.focussed = false;
_.interrupted = false;
_.hidden = 'hidden';
_.paused = true;
_.positionProp = null;
_.respondTo = null;
_.rowCount = 1;
_.shouldClick = true;
_.$slider = $(element);
_.$slidesCache = null;
_.transformType = null;
_.transitionType = null;
_.visibilityChange = 'visibilitychange';
_.windowWidth = 0;
_.windowTimer = null;
dataSettings = $(element).data('slick') || {};
_.options = $.extend({}, _.defaults, settings, dataSettings);
_.currentSlide = _.options.initialSlide;
_.originalSettings = _.options;
if (typeof document.mozHidden !== 'undefined') {
_.hidden = 'mozHidden';
_.visibilityChange = 'mozvisibilitychange';
} else if (typeof document.webkitHidden !== 'undefined') {
_.hidden = 'webkitHidden';
_.visibilityChange = 'webkitvisibilitychange';
}
_.autoPlay = $.proxy(_.autoPlay, _);
_.autoPlayClear = $.proxy(_.autoPlayClear, _);
_.autoPlayIterator = $.proxy(_.autoPlayIterator, _);
_.changeSlide = $.proxy(_.changeSlide, _);
_.clickHandler = $.proxy(_.clickHandler, _);
_.selectHandler = $.proxy(_.selectHandler, _);
_.setPosition = $.proxy(_.setPosition, _);
_.swipeHandler = $.proxy(_.swipeHandler, _);
_.dragHandler = $.proxy(_.dragHandler, _);
_.keyHandler = $.proxy(_.keyHandler, _);
_.instanceUid = instanceUid++;
// A simple way to check for HTML strings
// Strict HTML recognition (must start with <)
// Extracted from jQuery v1.11 source
_.htmlExpr = /^(?:\s*(<[\w\W]+>)[^>]*)$/;
_.registerBreakpoints();
_.init(true);
}
return Slick;
}();
Slick.prototype.activateADA = function () {
var _ = this;
_.$slideTrack.find('.slick-active').attr({
'aria-hidden': 'false' }).
find('a, input, button, select').attr({
'tabindex': '0' });
};
Slick.prototype.addSlide = Slick.prototype.slickAdd = function (markup, index, addBefore) {
var _ = this;
if (typeof index === 'boolean') {
addBefore = index;
index = null;
} else if (index < 0 || index >= _.slideCount) {
return false;
}
_.unload();
if (typeof index === 'number') {
if (index === 0 && _.$slides.length === 0) {
$(markup).appendTo(_.$slideTrack);
} else if (addBefore) {
$(markup).insertBefore(_.$slides.eq(index));
} else {
$(markup).insertAfter(_.$slides.eq(index));
}
} else {
if (addBefore === true) {
$(markup).prependTo(_.$slideTrack);
} else {
$(markup).appendTo(_.$slideTrack);
}
}
_.$slides = _.$slideTrack.children(this.options.slide);
_.$slideTrack.children(this.options.slide).detach();
_.$slideTrack.append(_.$slides);
_.$slides.each(function (index, element) {
$(element).attr('data-slick-index', index);
});
_.$slidesCache = _.$slides;
_.reinit();
};
Slick.prototype.animateHeight = function () {
var _ = this;
if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
_.$list.animate({
height: targetHeight },
_.options.speed);
}
};
Slick.prototype.animateSlide = function (targetLeft, callback) {
var animProps = {},
_ = this;
_.animateHeight();
if (_.options.rtl === true && _.options.vertical === false) {
targetLeft = -targetLeft;
}
if (_.transformsEnabled === false) {
if (_.options.vertical === false) {
_.$slideTrack.animate({
left: targetLeft },
_.options.speed, _.options.easing, callback);
} else {
_.$slideTrack.animate({
top: targetLeft },
_.options.speed, _.options.easing, callback);
}
} else {
if (_.cssTransitions === false) {
if (_.options.rtl === true) {
_.currentLeft = -_.currentLeft;
}
$({
animStart: _.currentLeft }).
animate({
animStart: targetLeft },
{
duration: _.options.speed,
easing: _.options.easing,
step: function step(now) {
now = Math.ceil(now);
if (_.options.vertical === false) {
animProps[_.animType] = 'translate(' +
now + 'px, 0px)';
_.$slideTrack.css(animProps);
} else {
animProps[_.animType] = 'translate(0px,' +
now + 'px)';
_.$slideTrack.css(animProps);
}
},
complete: function complete() {
if (callback) {
callback.call();
}
} });
} else {
_.applyTransition();
targetLeft = Math.ceil(targetLeft);
if (_.options.vertical === false) {
animProps[_.animType] = 'translate3d(' + targetLeft + 'px, 0px, 0px)';
} else {
animProps[_.animType] = 'translate3d(0px,' + targetLeft + 'px, 0px)';
}
_.$slideTrack.css(animProps);
if (callback) {
setTimeout(function () {
_.disableTransition();
callback.call();
}, _.options.speed);
}
}
}
};
Slick.prototype.getNavTarget = function () {
var _ = this,
asNavFor = _.options.asNavFor;
if (asNavFor && asNavFor !== null) {
asNavFor = $(asNavFor).not(_.$slider);
}
return asNavFor;
};
Slick.prototype.asNavFor = function (index) {
var _ = this,
asNavFor = _.getNavTarget();
if (asNavFor !== null && (typeof asNavFor === 'undefined' ? 'undefined' : _typeof(asNavFor)) === 'object') {
asNavFor.each(function () {
var target = $(this).slick('getSlick');
if (!target.unslicked) {
target.slideHandler(index, true);
}
});
}
};
Slick.prototype.applyTransition = function (slide) {
var _ = this,
transition = {};
if (_.options.fade === false) {
transition[_.transitionType] = _.transformType + ' ' + _.options.speed + 'ms ' + _.options.cssEase;
} else {
transition[_.transitionType] = 'opacity ' + _.options.speed + 'ms ' + _.options.cssEase;
}
if (_.options.fade === false) {
_.$slideTrack.css(transition);
} else {
_.$slides.eq(slide).css(transition);
}
};
Slick.prototype.autoPlay = function () {
var _ = this;
_.autoPlayClear();
if (_.slideCount > _.options.slidesToShow) {
_.autoPlayTimer = setInterval(_.autoPlayIterator, _.options.autoplaySpeed);
}
};
Slick.prototype.autoPlayClear = function () {
var _ = this;
if (_.autoPlayTimer) {
clearInterval(_.autoPlayTimer);
}
};
Slick.prototype.autoPlayIterator = function () {
var _ = this,
slideTo = _.currentSlide + _.options.slidesToScroll;
if (!_.paused && !_.interrupted && !_.focussed) {
if (_.options.infinite === false) {
if (_.direction === 1 && _.currentSlide + 1 === _.slideCount - 1) {
_.direction = 0;
} else
if (_.direction === 0) {
slideTo = _.currentSlide - _.options.slidesToScroll;
if (_.currentSlide - 1 === 0) {
_.direction = 1;
}
}
}
_.slideHandler(slideTo);
}
};
Slick.prototype.buildArrows = function () {
var _ = this;
if (_.options.arrows === true) {
_.$prevArrow = $(_.options.prevArrow).addClass('slick-arrow');
_.$nextArrow = $(_.options.nextArrow).addClass('slick-arrow');
if (_.slideCount > _.options.slidesToShow) {
_.$prevArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');
_.$nextArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');
if (_.htmlExpr.test(_.options.prevArrow)) {
_.$prevArrow.prependTo(_.options.appendArrows);
}
if (_.htmlExpr.test(_.options.nextArrow)) {
_.$nextArrow.appendTo(_.options.appendArrows);
}
if (_.options.infinite !== true) {
_.$prevArrow.
addClass('slick-disabled').
attr('aria-disabled', 'true');
}
} else {
_.$prevArrow.add(_.$nextArrow).
addClass('slick-hidden').
attr({
'aria-disabled': 'true',
'tabindex': '-1' });
}
}
};
Slick.prototype.buildDots = function () {
var _ = this,
i,dot;
if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
_.$slider.addClass('slick-dotted');
dot = $('<ul />').addClass(_.options.dotsClass);
for (i = 0; i <= _.getDotCount(); i += 1) {
dot.append($('<li />').append(_.options.customPaging.call(this, _, i)));
}
_.$dots = dot.appendTo(_.options.appendDots);
_.$dots.find('li').first().addClass('slick-active');
}
};
Slick.prototype.buildOut = function () {
var _ = this;
_.$slides =
_.$slider.
children(_.options.slide + ':not(.slick-cloned)').
addClass('slick-slide');
_.slideCount = _.$slides.length;
_.$slides.each(function (index, element) {
$(element).
attr('data-slick-index', index).
data('originalStyling', $(element).attr('style') || '');
});
_.$slider.addClass('slick-slider');
_.$slideTrack = _.slideCount === 0 ?
$('<div class="slick-track"/>').appendTo(_.$slider) :
_.$slides.wrapAll('<div class="slick-track"/>').parent();
_.$list = _.$slideTrack.wrap(
'<div class="slick-list"/>').parent();
_.$slideTrack.css('opacity', 0);
if (_.options.centerMode === true || _.options.swipeToSlide === true) {
_.options.slidesToScroll = 1;
}
$('img[data-lazy]', _.$slider).not('[src]').addClass('slick-loading');
_.setupInfinite();
_.buildArrows();
_.buildDots();
_.updateDots();
_.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);
if (_.options.draggable === true) {
_.$list.addClass('draggable');
}
};
Slick.prototype.buildRows = function () {
var _ = this,a,b,c,newSlides,numOfSlides,originalSlides,slidesPerSection;
newSlides = document.createDocumentFragment();
originalSlides = _.$slider.children();
if (_.options.rows > 0) {
slidesPerSection = _.options.slidesPerRow * _.options.rows;
numOfSlides = Math.ceil(
originalSlides.length / slidesPerSection);
for (a = 0; a < numOfSlides; a++) {
var slide = document.createElement('div');
for (b = 0; b < _.options.rows; b++) {
var row = document.createElement('div');
for (c = 0; c < _.options.slidesPerRow; c++) {
var target = a * slidesPerSection + (b * _.options.slidesPerRow + c);
if (originalSlides.get(target)) {
row.appendChild(originalSlides.get(target));
}
}
slide.appendChild(row);
}
newSlides.appendChild(slide);
}
_.$slider.empty().append(newSlides);
_.$slider.children().children().children().
css({
'width': 100 / _.options.slidesPerRow + '%',
'display': 'inline-block' });
}
};
Slick.prototype.checkResponsive = function (initial, forceUpdate) {
var _ = this,
breakpoint,targetBreakpoint,respondToWidth,triggerBreakpoint = false;
var sliderWidth = _.$slider.width();
var windowWidth = window.innerWidth || $(window).width();
if (_.respondTo === 'window') {
respondToWidth = windowWidth;
} else if (_.respondTo === 'slider') {
respondToWidth = sliderWidth;
} else if (_.respondTo === 'min') {
respondToWidth = Math.min(windowWidth, sliderWidth);
}
if (_.options.responsive &&
_.options.responsive.length &&
_.options.responsive !== null) {
targetBreakpoint = null;
for (breakpoint in _.breakpoints) {
if (_.breakpoints.hasOwnProperty(breakpoint)) {
if (_.originalSettings.mobileFirst === false) {
if (respondToWidth < _.breakpoints[breakpoint]) {
targetBreakpoint = _.breakpoints[breakpoint];
}
} else {
if (respondToWidth > _.breakpoints[breakpoint]) {
targetBreakpoint = _.breakpoints[breakpoint];
}
}
}
}
if (targetBreakpoint !== null) {
if (_.activeBreakpoint !== null) {
if (targetBreakpoint !== _.activeBreakpoint || forceUpdate) {
_.activeBreakpoint =
targetBreakpoint;
if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
_.unslick(targetBreakpoint);
} else {
_.options = $.extend({}, _.originalSettings,
_.breakpointSettings[
targetBreakpoint]);
if (initial === true) {
_.currentSlide = _.options.initialSlide;
}
_.refresh(initial);
}
triggerBreakpoint = targetBreakpoint;
}
} else {
_.activeBreakpoint = targetBreakpoint;
if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
_.unslick(targetBreakpoint);
} else {
_.options = $.extend({}, _.originalSettings,
_.breakpointSettings[
targetBreakpoint]);
if (initial === true) {
_.currentSlide = _.options.initialSlide;
}
_.refresh(initial);
}
triggerBreakpoint = targetBreakpoint;
}
} else {
if (_.activeBreakpoint !== null) {
_.activeBreakpoint = null;
_.options = _.originalSettings;
if (initial === true) {
_.currentSlide = _.options.initialSlide;
}
_.refresh(initial);
triggerBreakpoint = targetBreakpoint;
}
}
// only trigger breakpoints during an actual break. not on initialize.
if (!initial && triggerBreakpoint !== false) {
_.$slider.trigger('breakpoint', [_, triggerBreakpoint]);
}
}
};
Slick.prototype.changeSlide = function (event, dontAnimate) {
var _ = this,
$target = $(event.currentTarget),
indexOffset,slideOffset,unevenOffset;
// If target is a link, prevent default action.
if ($target.is('a')) {
event.preventDefault();
}
// If target is not the <li> element (ie: a child), find the <li>.
if (!$target.is('li')) {
$target = $target.closest('li');
}
unevenOffset = _.slideCount % _.options.slidesToScroll !== 0;
indexOffset = unevenOffset ? 0 : (_.slideCount - _.currentSlide) % _.options.slidesToScroll;
switch (event.data.message) {
case 'previous':
slideOffset = indexOffset === 0 ? _.options.slidesToScroll : _.options.slidesToShow - indexOffset;
if (_.slideCount > _.options.slidesToShow) {
_.slideHandler(_.currentSlide - slideOffset, false, dontAnimate);
}
break;
case 'next':
slideOffset = indexOffset === 0 ? _.options.slidesToScroll : indexOffset;
if (_.slideCount > _.options.slidesToShow) {
_.slideHandler(_.currentSlide + slideOffset, false, dontAnimate);
}
break;
case 'index':
var index = event.data.index === 0 ? 0 :
event.data.index || $target.index() * _.options.slidesToScroll;
_.slideHandler(_.checkNavigable(index), false, dontAnimate);
$target.children().trigger('focus');
break;
default:
return;}
};
Slick.prototype.checkNavigable = function (index) {
var _ = this,
navigables,prevNavigable;
navigables = _.getNavigableIndexes();
prevNavigable = 0;
if (index > navigables[navigables.length - 1]) {
index = navigables[navigables.length - 1];
} else {
for (var n in navigables) {
if (index < navigables[n]) {
index = prevNavigable;
break;
}
prevNavigable = navigables[n];
}
}
return index;
};
Slick.prototype.cleanUpEvents = function () {
var _ = this;
if (_.options.dots && _.$dots !== null) {
$('li', _.$dots).
off('click.slick', _.changeSlide).
off('mouseenter.slick', $.proxy(_.interrupt, _, true)).
off('mouseleave.slick', $.proxy(_.interrupt, _, false));
if (_.options.accessibility === true) {
_.$dots.off('keydown.slick', _.keyHandler);
}
}
_.$slider.off('focus.slick blur.slick');
if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
_.$prevArrow && _.$prevArrow.off('click.slick', _.changeSlide);
_.$nextArrow && _.$nextArrow.off('click.slick', _.changeSlide);
if (_.options.accessibility === true) {
_.$prevArrow && _.$prevArrow.off('keydown.slick', _.keyHandler);
_.$nextArrow && _.$nextArrow.off('keydown.slick', _.keyHandler);
}
}
_.$list.off('touchstart.slick mousedown.slick', _.swipeHandler);
_.$list.off('touchmove.slick mousemove.slick', _.swipeHandler);
_.$list.off('touchend.slick mouseup.slick', _.swipeHandler);
_.$list.off('touchcancel.slick mouseleave.slick', _.swipeHandler);
_.$list.off('click.slick', _.clickHandler);
$(document).off(_.visibilityChange, _.visibility);
_.cleanUpSlideEvents();
if (_.options.accessibility === true) {
_.$list.off('keydown.slick', _.keyHandler);
}
if (_.options.focusOnSelect === true) {
$(_.$slideTrack).children().off('click.slick', _.selectHandler);
}
$(window).off('orientationchange.slick.slick-' + _.instanceUid, _.orientationChange);
$(window).off('resize.slick.slick-' + _.instanceUid, _.resize);
$('[draggable!=true]', _.$slideTrack).off('dragstart', _.preventDefault);
$(window).off('load.slick.slick-' + _.instanceUid, _.setPosition);
};
Slick.prototype.cleanUpSlideEvents = function () {
var _ = this;
_.$list.off('mouseenter.slick', $.proxy(_.interrupt, _, true));
_.$list.off('mouseleave.slick', $.proxy(_.interrupt, _, false));
};
Slick.prototype.cleanUpRows = function () {
var _ = this,originalSlides;
if (_.options.rows > 0) {
originalSlides = _.$slides.children().children();
originalSlides.removeAttr('style');
_.$slider.empty().append(originalSlides);
}
};
Slick.prototype.clickHandler = function (event) {
var _ = this;
if (_.shouldClick === false) {
event.stopImmediatePropagation();
event.stopPropagation();
event.preventDefault();
}
};
Slick.prototype.destroy = function (refresh) {
var _ = this;
_.autoPlayClear();
_.touchObject = {};
_.cleanUpEvents();
$('.slick-cloned', _.$slider).detach();
if (_.$dots) {
_.$dots.remove();
}
if (_.$prevArrow && _.$prevArrow.length) {
_.$prevArrow.
removeClass('slick-disabled slick-arrow slick-hidden').
removeAttr('aria-hidden aria-disabled tabindex').
css('display', '');
if (_.htmlExpr.test(_.options.prevArrow)) {
_.$prevArrow.remove();
}
}
if (_.$nextArrow && _.$nextArrow.length) {
_.$nextArrow.
removeClass('slick-disabled slick-arrow slick-hidden').
removeAttr('aria-hidden aria-disabled tabindex').
css('display', '');
if (_.htmlExpr.test(_.options.nextArrow)) {
_.$nextArrow.remove();
}
}
if (_.$slides) {
_.$slides.
removeClass('slick-slide slick-active slick-center slick-visible slick-current').
removeAttr('aria-hidden').
removeAttr('data-slick-index').
each(function () {
$(this).attr('style', $(this).data('originalStyling'));
});
_.$slideTrack.children(this.options.slide).detach();
_.$slideTrack.detach();
_.$list.detach();
_.$slider.append(_.$slides);
}
_.cleanUpRows();
_.$slider.removeClass('slick-slider');
_.$slider.removeClass('slick-initialized');
_.$slider.removeClass('slick-dotted');
_.unslicked = true;
if (!refresh) {
_.$slider.trigger('destroy', [_]);
}
};
Slick.prototype.disableTransition = function (slide) {
var _ = this,
transition = {};
transition[_.transitionType] = '';
if (_.options.fade === false) {
_.$slideTrack.css(transition);
} else {
_.$slides.eq(slide).css(transition);
}
};
Slick.prototype.fadeSlide = function (slideIndex, callback) {
var _ = this;
if (_.cssTransitions === false) {
_.$slides.eq(slideIndex).css({
zIndex: _.options.zIndex });
_.$slides.eq(slideIndex).animate({
opacity: 1 },
_.options.speed, _.options.easing, callback);
} else {
_.applyTransition(slideIndex);
_.$slides.eq(slideIndex).css({
opacity: 1,
zIndex: _.options.zIndex });
if (callback) {
setTimeout(function () {
_.disableTransition(slideIndex);
callback.call();
}, _.options.speed);
}
}
};
Slick.prototype.fadeSlideOut = function (slideIndex) {
var _ = this;
if (_.cssTransitions === false) {
_.$slides.eq(slideIndex).animate({
opacity: 0,
zIndex: _.options.zIndex - 2 },
_.options.speed, _.options.easing);
} else {
_.applyTransition(slideIndex);
_.$slides.eq(slideIndex).css({
opacity: 0,
zIndex: _.options.zIndex - 2 });
}
};
Slick.prototype.filterSlides = Slick.prototype.slickFilter = function (filter) {
var _ = this;
if (filter !== null) {
_.$slidesCache = _.$slides;
_.unload();
_.$slideTrack.children(this.options.slide).detach();
_.$slidesCache.filter(filter).appendTo(_.$slideTrack);
_.reinit();
}
};
Slick.prototype.focusHandler = function () {
var _ = this;
_.$slider.
off('focus.slick blur.slick').
on('focus.slick blur.slick', '*', function (event) {
event.stopImmediatePropagation();
var $sf = $(this);
setTimeout(function () {
if (_.options.pauseOnFocus) {
_.focussed = $sf.is(':focus');
_.autoPlay();
}
}, 0);
});
};
Slick.prototype.getCurrent = Slick.prototype.slickCurrentSlide = function () {
var _ = this;
return _.currentSlide;
};
Slick.prototype.getDotCount = function () {
var _ = this;
var breakPoint = 0;
var counter = 0;
var pagerQty = 0;
if (_.options.infinite === true) {
if (_.slideCount <= _.options.slidesToShow) {
++pagerQty;
} else {
while (breakPoint < _.slideCount) {
++pagerQty;
breakPoint = counter + _.options.slidesToScroll;
counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
}
}
} else if (_.options.centerMode === true) {
pagerQty = _.slideCount;
} else if (!_.options.asNavFor) {
pagerQty = 1 + Math.ceil((_.slideCount - _.options.slidesToShow) / _.options.slidesToScroll);
} else {
while (breakPoint < _.slideCount) {
++pagerQty;
breakPoint = counter + _.options.slidesToScroll;
counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
}
}
return pagerQty - 1;
};
Slick.prototype.getLeft = function (slideIndex) {
var _ = this,
targetLeft,
verticalHeight,
verticalOffset = 0,
targetSlide,
coef;
_.slideOffset = 0;
verticalHeight = _.$slides.first().outerHeight(true);
if (_.options.infinite === true) {
if (_.slideCount > _.options.slidesToShow) {
_.slideOffset = _.slideWidth * _.options.slidesToShow * -1;
coef = -1;
if (_.options.vertical === true && _.options.centerMode === true) {
if (_.options.slidesToShow === 2) {
coef = -1.5;
} else if (_.options.slidesToShow === 1) {
coef = -2;
}
}
verticalOffset = verticalHeight * _.options.slidesToShow * coef;
}
if (_.slideCount % _.options.slidesToScroll !== 0) {
if (slideIndex + _.options.slidesToScroll > _.slideCount && _.slideCount > _.options.slidesToShow) {
if (slideIndex > _.slideCount) {
_.slideOffset = (_.options.slidesToShow - (slideIndex - _.slideCount)) * _.slideWidth * -1;
verticalOffset = (_.options.slidesToShow - (slideIndex - _.slideCount)) * verticalHeight * -1;
} else {
_.slideOffset = _.slideCount % _.options.slidesToScroll * _.slideWidth * -1;
verticalOffset = _.slideCount % _.options.slidesToScroll * verticalHeight * -1;
}
}
}
} else {
if (slideIndex + _.options.slidesToShow > _.slideCount) {
_.slideOffset = (slideIndex + _.options.slidesToShow - _.slideCount) * _.slideWidth;
verticalOffset = (slideIndex + _.options.slidesToShow - _.slideCount) * verticalHeight;
}
}
if (_.slideCount <= _.options.slidesToShow) {
_.slideOffset = 0;
verticalOffset = 0;
}
if (_.options.centerMode === true && _.slideCount <= _.options.slidesToShow) {
_.slideOffset = _.slideWidth * Math.floor(_.options.slidesToShow) / 2 - _.slideWidth * _.slideCount / 2;
} else if (_.options.centerMode === true && _.options.infinite === true) {
_.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2) - _.slideWidth;
} else if (_.options.centerMode === true) {
_.slideOffset = 0;
_.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2);
}
if (_.options.vertical === false) {
targetLeft = slideIndex * _.slideWidth * -1 + _.slideOffset;
} else {
targetLeft = slideIndex * verticalHeight * -1 + verticalOffset;
}
if (_.options.variableWidth === true) {
if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
} else {
targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow);
}
if (_.options.rtl === true) {
if (targetSlide[0]) {
targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
} else {
targetLeft = 0;
}
} else {
targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
}
if (_.options.centerMode === true) {
if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
} else {
targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow + 1);
}
if (_.options.rtl === true) {
if (targetSlide[0]) {
targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
} else {
targetLeft = 0;
}
} else {
targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
}
targetLeft += (_.$list.width() - targetSlide.outerWidth()) / 2;
}
}
return targetLeft;
};
Slick.prototype.getOption = Slick.prototype.slickGetOption = function (option) {
var _ = this;
return _.options[option];
};
Slick.prototype.getNavigableIndexes = function () {
var _ = this,
breakPoint = 0,
counter = 0,
indexes = [],
max;
if (_.options.infinite === false) {
max = _.slideCount;
} else {
breakPoint = _.options.slidesToScroll * -1;
counter = _.options.slidesToScroll * -1;
max = _.slideCount * 2;
}
while (breakPoint < max) {
indexes.push(breakPoint);
breakPoint = counter + _.options.slidesToScroll;
counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
}
return indexes;
};
Slick.prototype.getSlick = function () {
return this;
};
Slick.prototype.getSlideCount = function () {
var _ = this,
slidesTraversed,swipedSlide,centerOffset;
centerOffset = _.options.centerMode === true ? _.slideWidth * Math.floor(_.options.slidesToShow / 2) : 0;
if (_.options.swipeToSlide === true) {
_.$slideTrack.find('.slick-slide').each(function (index, slide) {
if (slide.offsetLeft - centerOffset + $(slide).outerWidth() / 2 > _.swipeLeft * -1) {
swipedSlide = slide;
return false;
}
});
slidesTraversed = Math.abs($(swipedSlide).attr('data-slick-index') - _.currentSlide) || 1;
return slidesTraversed;
} else {
return _.options.slidesToScroll;
}
};
Slick.prototype.goTo = Slick.prototype.slickGoTo = function (slide, dontAnimate) {
var _ = this;
_.changeSlide({
data: {
message: 'index',
index: parseInt(slide) } },
dontAnimate);
};
Slick.prototype.init = function (creation) {
var _ = this;
if (!$(_.$slider).hasClass('slick-initialized')) {
$(_.$slider).addClass('slick-initialized');
_.buildRows();
_.buildOut();
_.setProps();
_.startLoad();
_.loadSlider();
_.initializeEvents();
_.updateArrows();
_.updateDots();
_.checkResponsive(true);
_.focusHandler();
}
if (creation) {
_.$slider.trigger('init', [_]);
}
if (_.options.accessibility === true) {
_.initADA();
}
if (_.options.autoplay) {
_.paused = false;
_.autoPlay();
}
};
Slick.prototype.initADA = function () {
var _ = this,
numDotGroups = Math.ceil(_.slideCount / _.options.slidesToShow),
tabControlIndexes = _.getNavigableIndexes().filter(function (val) {
return val >= 0 && val < _.slideCount;
});
_.$slides.add(_.$slideTrack.find('.slick-cloned')).attr({
'aria-hidden': 'true',
'tabindex': '-1' }).
find('a, input, button, select').attr({
'tabindex': '-1' });
if (_.$dots !== null) {
_.$slides.not(_.$slideTrack.find('.slick-cloned')).each(function (i) {
var slideControlIndex = tabControlIndexes.indexOf(i);
$(this).attr({
'role': 'tabpanel',
'id': 'slick-slide' + _.instanceUid + i,
'tabindex': -1 });
if (slideControlIndex !== -1) {
var ariaButtonControl = 'slick-slide-control' + _.instanceUid + slideControlIndex;
if ($('#' + ariaButtonControl).length) {
$(this).attr({
'aria-describedby': ariaButtonControl });
}
}
});
_.$dots.attr('role', 'tablist').find('li').each(function (i) {
var mappedSlideIndex = tabControlIndexes[i];
$(this).attr({
'role': 'presentation' });
$(this).find('button').first().attr({
'role': 'tab',
'id': 'slick-slide-control' + _.instanceUid + i,
'aria-controls': 'slick-slide' + _.instanceUid + mappedSlideIndex,
'aria-label': i + 1 + ' of ' + numDotGroups,
'aria-selected': null,
'tabindex': '-1' });
}).eq(_.currentSlide).find('button').attr({
'aria-selected': 'true',
'tabindex': '0' }).
end();
}
for (var i = _.currentSlide, max = i + _.options.slidesToShow; i < max; i++) {
if (_.options.focusOnChange) {
_.$slides.eq(i).attr({ 'tabindex': '0' });
} else {
_.$slides.eq(i).removeAttr('tabindex');
}
}
_.activateADA();
};
Slick.prototype.initArrowEvents = function () {
var _ = this;
if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
_.$prevArrow.
off('click.slick').
on('click.slick', {
message: 'previous' },
_.changeSlide);
_.$nextArrow.
off('click.slick').
on('click.slick', {
message: 'next' },
_.changeSlide);
if (_.options.accessibility === true) {
_.$prevArrow.on('keydown.slick', _.keyHandler);
_.$nextArrow.on('keydown.slick', _.keyHandler);
}
}
};
Slick.prototype.initDotEvents = function () {
var _ = this;
if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
$('li', _.$dots).on('click.slick', {
message: 'index' },
_.changeSlide);
if (_.options.accessibility === true) {
_.$dots.on('keydown.slick', _.keyHandler);
}
}
if (_.options.dots === true && _.options.pauseOnDotsHover === true && _.slideCount > _.options.slidesToShow) {
$('li', _.$dots).
on('mouseenter.slick', $.proxy(_.interrupt, _, true)).
on('mouseleave.slick', $.proxy(_.interrupt, _, false));
}
};
Slick.prototype.initSlideEvents = function () {
var _ = this;
if (_.options.pauseOnHover) {
_.$list.on('mouseenter.slick', $.proxy(_.interrupt, _, true));
_.$list.on('mouseleave.slick', $.proxy(_.interrupt, _, false));
}
};
Slick.prototype.initializeEvents = function () {
var _ = this;
_.initArrowEvents();
_.initDotEvents();
_.initSlideEvents();
_.$list.on('touchstart.slick mousedown.slick', {
action: 'start' },
_.swipeHandler);
_.$list.on('touchmove.slick mousemove.slick', {
action: 'move' },
_.swipeHandler);
_.$list.on('touchend.slick mouseup.slick', {
action: 'end' },
_.swipeHandler);
_.$list.on('touchcancel.slick mouseleave.slick', {
action: 'end' },
_.swipeHandler);
_.$list.on('click.slick', _.clickHandler);
$(document).on(_.visibilityChange, $.proxy(_.visibility, _));
if (_.options.accessibility === true) {
_.$list.on('keydown.slick', _.keyHandler);
}
if (_.options.focusOnSelect === true) {
$(_.$slideTrack).children().on('click.slick', _.selectHandler);
}
$(window).on('orientationchange.slick.slick-' + _.instanceUid, $.proxy(_.orientationChange, _));
$(window).on('resize.slick.slick-' + _.instanceUid, $.proxy(_.resize, _));
$('[draggable!=true]', _.$slideTrack).on('dragstart', _.preventDefault);
$(window).on('load.slick.slick-' + _.instanceUid, _.setPosition);
$(_.setPosition);
};
Slick.prototype.initUI = function () {
var _ = this;
if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
_.$prevArrow.show();
_.$nextArrow.show();
}
if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
_.$dots.show();
}
};
Slick.prototype.keyHandler = function (event) {
var _ = this;
//Dont slide if the cursor is inside the form fields and arrow keys are pressed
if (!event.target.tagName.match('TEXTAREA|INPUT|SELECT')) {
if (event.keyCode === 37 && _.options.accessibility === true) {
_.changeSlide({
data: {
message: _.options.rtl === true ? 'next' : 'previous' } });
} else if (event.keyCode === 39 && _.options.accessibility === true) {
_.changeSlide({
data: {
message: _.options.rtl === true ? 'previous' : 'next' } });
}
}
};
Slick.prototype.lazyLoad = function () {
var _ = this,
loadRange,cloneRange,rangeStart,rangeEnd;
function loadImages(imagesScope) {
$('img[data-lazy]', imagesScope).each(function () {
var image = $(this),
imageSource = $(this).attr('data-lazy'),
imageSrcSet = $(this).attr('data-srcset'),
imageSizes = $(this).attr('data-sizes') || _.$slider.attr('data-sizes'),
imageToLoad = document.createElement('img');
imageToLoad.onload = function () {
image.
animate({ opacity: 0 }, 100, function () {
if (imageSrcSet) {
image.
attr('srcset', imageSrcSet);
if (imageSizes) {
image.
attr('sizes', imageSizes);
}
}
image.
attr('src', imageSource).
animate({ opacity: 1 }, 200, function () {
image.
removeAttr('data-lazy data-srcset data-sizes').
removeClass('slick-loading');
});
_.$slider.trigger('lazyLoaded', [_, image, imageSource]);
});
};
imageToLoad.onerror = function () {
image.
removeAttr('data-lazy').
removeClass('slick-loading').
addClass('slick-lazyload-error');
_.$slider.trigger('lazyLoadError', [_, image, imageSource]);
};
imageToLoad.src = imageSource;
});
}
if (_.options.centerMode === true) {
if (_.options.infinite === true) {
rangeStart = _.currentSlide + (_.options.slidesToShow / 2 + 1);
rangeEnd = rangeStart + _.options.slidesToShow + 2;
} else {
rangeStart = Math.max(0, _.currentSlide - (_.options.slidesToShow / 2 + 1));
rangeEnd = 2 + (_.options.slidesToShow / 2 + 1) + _.currentSlide;
}
} else {
rangeStart = _.options.infinite ? _.options.slidesToShow + _.currentSlide : _.currentSlide;
rangeEnd = Math.ceil(rangeStart + _.options.slidesToShow);
if (_.options.fade === true) {
if (rangeStart > 0) rangeStart--;
if (rangeEnd <= _.slideCount) rangeEnd++;
}
}
loadRange = _.$slider.find('.slick-slide').slice(rangeStart, rangeEnd);
if (_.options.lazyLoad === 'anticipated') {
var prevSlide = rangeStart - 1,
nextSlide = rangeEnd,
$slides = _.$slider.find('.slick-slide');
for (var i = 0; i < _.options.slidesToScroll; i++) {
if (prevSlide < 0) prevSlide = _.slideCount - 1;
loadRange = loadRange.add($slides.eq(prevSlide));
loadRange = loadRange.add($slides.eq(nextSlide));
prevSlide--;
nextSlide++;
}
}
loadImages(loadRange);
if (_.slideCount <= _.options.slidesToShow) {
cloneRange = _.$slider.find('.slick-slide');
loadImages(cloneRange);
} else
if (_.currentSlide >= _.slideCount - _.options.slidesToShow) {
cloneRange = _.$slider.find('.slick-cloned').slice(0, _.options.slidesToShow);
loadImages(cloneRange);
} else if (_.currentSlide === 0) {
cloneRange = _.$slider.find('.slick-cloned').slice(_.options.slidesToShow * -1);
loadImages(cloneRange);
}
};
Slick.prototype.loadSlider = function () {
var _ = this;
_.setPosition();
_.$slideTrack.css({
opacity: 1 });
_.$slider.removeClass('slick-loading');
_.initUI();
if (_.options.lazyLoad === 'progressive') {
_.progressiveLazyLoad();
}
};
Slick.prototype.next = Slick.prototype.slickNext = function () {
var _ = this;
_.changeSlide({
data: {
message: 'next' } });
};
Slick.prototype.orientationChange = function () {
var _ = this;
_.checkResponsive();
_.setPosition();
};
Slick.prototype.pause = Slick.prototype.slickPause = function () {
var _ = this;
_.autoPlayClear();
_.paused = true;
};
Slick.prototype.play = Slick.prototype.slickPlay = function () {
var _ = this;
_.autoPlay();
_.options.autoplay = true;
_.paused = false;
_.focussed = false;
_.interrupted = false;
};
Slick.prototype.postSlide = function (index) {
var _ = this;
if (!_.unslicked) {
_.$slider.trigger('afterChange', [_, index]);
_.animating = false;
if (_.slideCount > _.options.slidesToShow) {
_.setPosition();
}
_.swipeLeft = null;
if (_.options.autoplay) {
_.autoPlay();
}
if (_.options.accessibility === true) {
_.initADA();
if (_.options.focusOnChange) {
var $currentSlide = $(_.$slides.get(_.currentSlide));
$currentSlide.attr('tabindex', 0).focus();
}
}
}
};
Slick.prototype.prev = Slick.prototype.slickPrev = function () {
var _ = this;
_.changeSlide({
data: {
message: 'previous' } });
};
Slick.prototype.preventDefault = function (event) {
event.preventDefault();
};
Slick.prototype.progressiveLazyLoad = function (tryCount) {
tryCount = tryCount || 1;
var _ = this,
$imgsToLoad = $('img[data-lazy]', _.$slider),
image,
imageSource,
imageSrcSet,
imageSizes,
imageToLoad;
if ($imgsToLoad.length) {
image = $imgsToLoad.first();
imageSource = image.attr('data-lazy');
imageSrcSet = image.attr('data-srcset');
imageSizes = image.attr('data-sizes') || _.$slider.attr('data-sizes');
imageToLoad = document.createElement('img');
imageToLoad.onload = function () {
if (imageSrcSet) {
image.
attr('srcset', imageSrcSet);
if (imageSizes) {
image.
attr('sizes', imageSizes);
}
}
image.
attr('src', imageSource).
removeAttr('data-lazy data-srcset data-sizes').
removeClass('slick-loading');
if (_.options.adaptiveHeight === true) {
_.setPosition();
}
_.$slider.trigger('lazyLoaded', [_, image, imageSource]);
_.progressiveLazyLoad();
};
imageToLoad.onerror = function () {
if (tryCount < 3) {
/**
* try to load the image 3 times,
* leave a slight delay so we don't get
* servers blocking the request.
*/
setTimeout(function () {
_.progressiveLazyLoad(tryCount + 1);
}, 500);
} else {
image.
removeAttr('data-lazy').
removeClass('slick-loading').
addClass('slick-lazyload-error');
_.$slider.trigger('lazyLoadError', [_, image, imageSource]);
_.progressiveLazyLoad();
}
};
imageToLoad.src = imageSource;
} else {
_.$slider.trigger('allImagesLoaded', [_]);
}
};
Slick.prototype.refresh = function (initializing) {
var _ = this,currentSlide,lastVisibleIndex;
lastVisibleIndex = _.slideCount - _.options.slidesToShow;
// in non-infinite sliders, we don't want to go past the
// last visible index.
if (!_.options.infinite && _.currentSlide > lastVisibleIndex) {
_.currentSlide = lastVisibleIndex;
}
// if less slides than to show, go to start.
if (_.slideCount <= _.options.slidesToShow) {
_.currentSlide = 0;
}
currentSlide = _.currentSlide;
_.destroy(true);
$.extend(_, _.initials, { currentSlide: currentSlide });
_.init();
if (!initializing) {
_.changeSlide({
data: {
message: 'index',
index: currentSlide } },
false);
}
};
Slick.prototype.registerBreakpoints = function () {
var _ = this,breakpoint,currentBreakpoint,l,
responsiveSettings = _.options.responsive || null;
if ($.type(responsiveSettings) === 'array' && responsiveSettings.length) {
_.respondTo = _.options.respondTo || 'window';
for (breakpoint in responsiveSettings) {
l = _.breakpoints.length - 1;
if (responsiveSettings.hasOwnProperty(breakpoint)) {
currentBreakpoint = responsiveSettings[breakpoint].breakpoint;
// loop through the breakpoints and cut out any existing
// ones with the same breakpoint number, we don't want dupes.
while (l >= 0) {
if (_.breakpoints[l] && _.breakpoints[l] === currentBreakpoint) {
_.breakpoints.splice(l, 1);
}
l--;
}
_.breakpoints.push(currentBreakpoint);
_.breakpointSettings[currentBreakpoint] = responsiveSettings[breakpoint].settings;
}
}
_.breakpoints.sort(function (a, b) {
return _.options.mobileFirst ? a - b : b - a;
});
}
};
Slick.prototype.reinit = function () {
var _ = this;
_.$slides =
_.$slideTrack.
children(_.options.slide).
addClass('slick-slide');
_.slideCount = _.$slides.length;
if (_.currentSlide >= _.slideCount && _.currentSlide !== 0) {
_.currentSlide = _.currentSlide - _.options.slidesToScroll;
}
if (_.slideCount <= _.options.slidesToShow) {
_.currentSlide = 0;
}
_.registerBreakpoints();
_.setProps();
_.setupInfinite();
_.buildArrows();
_.updateArrows();
_.initArrowEvents();
_.buildDots();
_.updateDots();
_.initDotEvents();
_.cleanUpSlideEvents();
_.initSlideEvents();
_.checkResponsive(false, true);
if (_.options.focusOnSelect === true) {
$(_.$slideTrack).children().on('click.slick', _.selectHandler);
}
_.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);
_.setPosition();
_.focusHandler();
_.paused = !_.options.autoplay;
_.autoPlay();
_.$slider.trigger('reInit', [_]);
};
Slick.prototype.resize = function () {
var _ = this;
if ($(window).width() !== _.windowWidth) {
clearTimeout(_.windowDelay);
_.windowDelay = window.setTimeout(function () {
_.windowWidth = $(window).width();
_.checkResponsive();
if (!_.unslicked) {_.setPosition();}
}, 50);
}
};
Slick.prototype.removeSlide = Slick.prototype.slickRemove = function (index, removeBefore, removeAll) {
var _ = this;
if (typeof index === 'boolean') {
removeBefore = index;
index = removeBefore === true ? 0 : _.slideCount - 1;
} else {
index = removeBefore === true ? --index : index;
}
if (_.slideCount < 1 || index < 0 || index > _.slideCount - 1) {
return false;
}
_.unload();
if (removeAll === true) {
_.$slideTrack.children().remove();
} else {
_.$slideTrack.children(this.options.slide).eq(index).remove();
}
_.$slides = _.$slideTrack.children(this.options.slide);
_.$slideTrack.children(this.options.slide).detach();
_.$slideTrack.append(_.$slides);
_.$slidesCache = _.$slides;
_.reinit();
};
Slick.prototype.setCSS = function (position) {
var _ = this,
positionProps = {},
x,y;
if (_.options.rtl === true) {
position = -position;
}
x = _.positionProp == 'left' ? Math.ceil(position) + 'px' : '0px';
y = _.positionProp == 'top' ? Math.ceil(position) + 'px' : '0px';
positionProps[_.positionProp] = position;
if (_.transformsEnabled === false) {
_.$slideTrack.css(positionProps);
} else {
positionProps = {};
if (_.cssTransitions === false) {
positionProps[_.animType] = 'translate(' + x + ', ' + y + ')';
_.$slideTrack.css(positionProps);
} else {
positionProps[_.animType] = 'translate3d(' + x + ', ' + y + ', 0px)';
_.$slideTrack.css(positionProps);
}
}
};
Slick.prototype.setDimensions = function () {
var _ = this;
if (_.options.vertical === false) {
if (_.options.centerMode === true) {
_.$list.css({
padding: '0px ' + _.options.centerPadding });
}
} else {
_.$list.height(_.$slides.first().outerHeight(true) * _.options.slidesToShow);
if (_.options.centerMode === true) {
_.$list.css({
padding: _.options.centerPadding + ' 0px' });
}
}
_.listWidth = _.$list.width();
_.listHeight = _.$list.height();
if (_.options.vertical === false && _.options.variableWidth === false) {
_.slideWidth = Math.ceil(_.listWidth / _.options.slidesToShow);
_.$slideTrack.width(Math.ceil(_.slideWidth * _.$slideTrack.children('.slick-slide').length));
} else if (_.options.variableWidth === true) {
_.$slideTrack.width(5000 * _.slideCount);
} else {
_.slideWidth = Math.ceil(_.listWidth);
_.$slideTrack.height(Math.ceil(_.$slides.first().outerHeight(true) * _.$slideTrack.children('.slick-slide').length));
}
var offset = _.$slides.first().outerWidth(true) - _.$slides.first().width();
if (_.options.variableWidth === false) _.$slideTrack.children('.slick-slide').width(_.slideWidth - offset);
};
Slick.prototype.setFade = function () {
var _ = this,
targetLeft;
_.$slides.each(function (index, element) {
targetLeft = _.slideWidth * index * -1;
if (_.options.rtl === true) {
$(element).css({
position: 'relative',
right: targetLeft,
top: 0,
zIndex: _.options.zIndex - 2,
opacity: 0 });
} else {
$(element).css({
position: 'relative',
left: targetLeft,
top: 0,
zIndex: _.options.zIndex - 2,
opacity: 0 });
}
});
_.$slides.eq(_.currentSlide).css({
zIndex: _.options.zIndex - 1,
opacity: 1 });
};
Slick.prototype.setHeight = function () {
var _ = this;
if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
_.$list.css('height', targetHeight);
}
};
Slick.prototype.setOption =
Slick.prototype.slickSetOption = function () {
/**
* accepts arguments in format of:
*
* - for changing a single option's value:
* .slick("setOption", option, value, refresh )
*
* - for changing a set of responsive options:
* .slick("setOption", 'responsive', [{}, ...], refresh )
*
* - for updating multiple values at once (not responsive)
* .slick("setOption", { 'option': value, ... }, refresh )
*/
var _ = this,l,item,option,value,refresh = false,type;
if ($.type(arguments[0]) === 'object') {
option = arguments[0];
refresh = arguments[1];
type = 'multiple';
} else if ($.type(arguments[0]) === 'string') {
option = arguments[0];
value = arguments[1];
refresh = arguments[2];
if (arguments[0] === 'responsive' && $.type(arguments[1]) === 'array') {
type = 'responsive';
} else if (typeof arguments[1] !== 'undefined') {
type = 'single';
}
}
if (type === 'single') {
_.options[option] = value;
} else if (type === 'multiple') {
$.each(option, function (opt, val) {
_.options[opt] = val;
});
} else if (type === 'responsive') {
for (item in value) {
if ($.type(_.options.responsive) !== 'array') {
_.options.responsive = [value[item]];
} else {
l = _.options.responsive.length - 1;
// loop through the responsive object and splice out duplicates.
while (l >= 0) {
if (_.options.responsive[l].breakpoint === value[item].breakpoint) {
_.options.responsive.splice(l, 1);
}
l--;
}
_.options.responsive.push(value[item]);
}
}
}
if (refresh) {
_.unload();
_.reinit();
}
};
Slick.prototype.setPosition = function () {
var _ = this;
_.setDimensions();
_.setHeight();
if (_.options.fade === false) {
_.setCSS(_.getLeft(_.currentSlide));
} else {
_.setFade();
}
_.$slider.trigger('setPosition', [_]);
};
Slick.prototype.setProps = function () {
var _ = this,
bodyStyle = document.body.style;
_.positionProp = _.options.vertical === true ? 'top' : 'left';
if (_.positionProp === 'top') {
_.$slider.addClass('slick-vertical');
} else {
_.$slider.removeClass('slick-vertical');
}
if (bodyStyle.WebkitTransition !== undefined ||
bodyStyle.MozTransition !== undefined ||
bodyStyle.msTransition !== undefined) {
if (_.options.useCSS === true) {
_.cssTransitions = true;
}
}
if (_.options.fade) {
if (typeof _.options.zIndex === 'number') {
if (_.options.zIndex < 3) {
_.options.zIndex = 3;
}
} else {
_.options.zIndex = _.defaults.zIndex;
}
}
if (bodyStyle.OTransform !== undefined) {
_.animType = 'OTransform';
_.transformType = '-o-transform';
_.transitionType = 'OTransition';
if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
}
if (bodyStyle.MozTransform !== undefined) {
_.animType = 'MozTransform';
_.transformType = '-moz-transform';
_.transitionType = 'MozTransition';
if (bodyStyle.perspectiveProperty === undefined && bodyStyle.MozPerspective === undefined) _.animType = false;
}
if (bodyStyle.webkitTransform !== undefined) {
_.animType = 'webkitTransform';
_.transformType = '-webkit-transform';
_.transitionType = 'webkitTransition';
if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
}
if (bodyStyle.msTransform !== undefined) {
_.animType = 'msTransform';
_.transformType = '-ms-transform';
_.transitionType = 'msTransition';
if (bodyStyle.msTransform === undefined) _.animType = false;
}
if (bodyStyle.transform !== undefined && _.animType !== false) {
_.animType = 'transform';
_.transformType = 'transform';
_.transitionType = 'transition';
}
_.transformsEnabled = _.options.useTransform && _.animType !== null && _.animType !== false;
};
Slick.prototype.setSlideClasses = function (index) {
var _ = this,
centerOffset,allSlides,indexOffset,remainder;
allSlides = _.$slider.
find('.slick-slide').
removeClass('slick-active slick-center slick-current').
attr('aria-hidden', 'true');
_.$slides.
eq(index).
addClass('slick-current');
if (_.options.centerMode === true) {
var evenCoef = _.options.slidesToShow % 2 === 0 ? 1 : 0;
centerOffset = Math.floor(_.options.slidesToShow / 2);
if (_.options.infinite === true) {
if (index >= centerOffset && index <= _.slideCount - 1 - centerOffset) {
_.$slides.
slice(index - centerOffset + evenCoef, index + centerOffset + 1).
addClass('slick-active').
attr('aria-hidden', 'false');
} else {
indexOffset = _.options.slidesToShow + index;
allSlides.
slice(indexOffset - centerOffset + 1 + evenCoef, indexOffset + centerOffset + 2).
addClass('slick-active').
attr('aria-hidden', 'false');
}
if (index === 0) {
allSlides.
eq(allSlides.length - 1 - _.options.slidesToShow).
addClass('slick-center');
} else if (index === _.slideCount - 1) {
allSlides.
eq(_.options.slidesToShow).
addClass('slick-center');
}
}
_.$slides.
eq(index).
addClass('slick-center');
} else {
if (index >= 0 && index <= _.slideCount - _.options.slidesToShow) {
_.$slides.
slice(index, index + _.options.slidesToShow).
addClass('slick-active').
attr('aria-hidden', 'false');
} else if (allSlides.length <= _.options.slidesToShow) {
allSlides.
addClass('slick-active').
attr('aria-hidden', 'false');
} else {
remainder = _.slideCount % _.options.slidesToShow;
indexOffset = _.options.infinite === true ? _.options.slidesToShow + index : index;
if (_.options.slidesToShow == _.options.slidesToScroll && _.slideCount - index < _.options.slidesToShow) {
allSlides.
slice(indexOffset - (_.options.slidesToShow - remainder), indexOffset + remainder).
addClass('slick-active').
attr('aria-hidden', 'false');
} else {
allSlides.
slice(indexOffset, indexOffset + _.options.slidesToShow).
addClass('slick-active').
attr('aria-hidden', 'false');
}
}
}
if (_.options.lazyLoad === 'ondemand' || _.options.lazyLoad === 'anticipated') {
_.lazyLoad();
}
};
Slick.prototype.setupInfinite = function () {
var _ = this,
i,slideIndex,infiniteCount;
if (_.options.fade === true) {
_.options.centerMode = false;
}
if (_.options.infinite === true && _.options.fade === false) {
slideIndex = null;
if (_.slideCount > _.options.slidesToShow) {
if (_.options.centerMode === true) {
infiniteCount = _.options.slidesToShow + 1;
} else {
infiniteCount = _.options.slidesToShow;
}
for (i = _.slideCount; i > _.slideCount -
infiniteCount; i -= 1) {
slideIndex = i - 1;
$(_.$slides[slideIndex]).clone(true).attr('id', '').
attr('data-slick-index', slideIndex - _.slideCount).
prependTo(_.$slideTrack).addClass('slick-cloned');
}
for (i = 0; i < infiniteCount + _.slideCount; i += 1) {
slideIndex = i;
$(_.$slides[slideIndex]).clone(true).attr('id', '').
attr('data-slick-index', slideIndex + _.slideCount).
appendTo(_.$slideTrack).addClass('slick-cloned');
}
_.$slideTrack.find('.slick-cloned').find('[id]').each(function () {
$(this).attr('id', '');
});
}
}
};
Slick.prototype.interrupt = function (toggle) {
var _ = this;
if (!toggle) {
_.autoPlay();
}
_.interrupted = toggle;
};
Slick.prototype.selectHandler = function (event) {
var _ = this;
var targetElement =
$(event.target).is('.slick-slide') ?
$(event.target) :
$(event.target).parents('.slick-slide');
var index = parseInt(targetElement.attr('data-slick-index'));
if (!index) index = 0;
if (_.slideCount <= _.options.slidesToShow) {
_.slideHandler(index, false, true);
return;
}
_.slideHandler(index);
};
Slick.prototype.slideHandler = function (index, sync, dontAnimate) {
var targetSlide,animSlide,oldSlide,slideLeft,targetLeft = null,
_ = this,navTarget;
sync = sync || false;
if (_.animating === true && _.options.waitForAnimate === true) {
return;
}
if (_.options.fade === true && _.currentSlide === index) {
return;
}
if (sync === false) {
_.asNavFor(index);
}
targetSlide = index;
targetLeft = _.getLeft(targetSlide);
slideLeft = _.getLeft(_.currentSlide);
_.currentLeft = _.swipeLeft === null ? slideLeft : _.swipeLeft;
if (_.options.infinite === false && _.options.centerMode === false && (index < 0 || index > _.getDotCount() * _.options.slidesToScroll)) {
if (_.options.fade === false) {
targetSlide = _.currentSlide;
if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
_.animateSlide(slideLeft, function () {
_.postSlide(targetSlide);
});
} else {
_.postSlide(targetSlide);
}
}
return;
} else if (_.options.infinite === false && _.options.centerMode === true && (index < 0 || index > _.slideCount - _.options.slidesToScroll)) {
if (_.options.fade === false) {
targetSlide = _.currentSlide;
if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
_.animateSlide(slideLeft, function () {
_.postSlide(targetSlide);
});
} else {
_.postSlide(targetSlide);
}
}
return;
}
if (_.options.autoplay) {
clearInterval(_.autoPlayTimer);
}
if (targetSlide < 0) {
if (_.slideCount % _.options.slidesToScroll !== 0) {
animSlide = _.slideCount - _.slideCount % _.options.slidesToScroll;
} else {
animSlide = _.slideCount + targetSlide;
}
} else if (targetSlide >= _.slideCount) {
if (_.slideCount % _.options.slidesToScroll !== 0) {
animSlide = 0;
} else {
animSlide = targetSlide - _.slideCount;
}
} else {
animSlide = targetSlide;
}
_.animating = true;
_.$slider.trigger('beforeChange', [_, _.currentSlide, animSlide]);
oldSlide = _.currentSlide;
_.currentSlide = animSlide;
_.setSlideClasses(_.currentSlide);
if (_.options.asNavFor) {
navTarget = _.getNavTarget();
navTarget = navTarget.slick('getSlick');
if (navTarget.slideCount <= navTarget.options.slidesToShow) {
navTarget.setSlideClasses(_.currentSlide);
}
}
_.updateDots();
_.updateArrows();
if (_.options.fade === true) {
if (dontAnimate !== true) {
_.fadeSlideOut(oldSlide);
_.fadeSlide(animSlide, function () {
_.postSlide(animSlide);
});
} else {
_.postSlide(animSlide);
}
_.animateHeight();
return;
}
if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
_.animateSlide(targetLeft, function () {
_.postSlide(animSlide);
});
} else {
_.postSlide(animSlide);
}
};
Slick.prototype.startLoad = function () {
var _ = this;
if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
_.$prevArrow.hide();
_.$nextArrow.hide();
}
if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
_.$dots.hide();
}
_.$slider.addClass('slick-loading');
};
Slick.prototype.swipeDirection = function () {
var xDist,yDist,r,swipeAngle,_ = this;
xDist = _.touchObject.startX - _.touchObject.curX;
yDist = _.touchObject.startY - _.touchObject.curY;
r = Math.atan2(yDist, xDist);
swipeAngle = Math.round(r * 180 / Math.PI);
if (swipeAngle < 0) {
swipeAngle = 360 - Math.abs(swipeAngle);
}
if (swipeAngle <= 45 && swipeAngle >= 0) {
return _.options.rtl === false ? 'left' : 'right';
}
if (swipeAngle <= 360 && swipeAngle >= 315) {
return _.options.rtl === false ? 'left' : 'right';
}
if (swipeAngle >= 135 && swipeAngle <= 225) {
return _.options.rtl === false ? 'right' : 'left';
}
if (_.options.verticalSwiping === true) {
if (swipeAngle >= 35 && swipeAngle <= 135) {
return 'down';
} else {
return 'up';
}
}
return 'vertical';
};
Slick.prototype.swipeEnd = function (event) {
var _ = this,
slideCount,
direction;
_.dragging = false;
_.swiping = false;
if (_.scrolling) {
_.scrolling = false;
return false;
}
_.interrupted = false;
_.shouldClick = _.touchObject.swipeLength > 10 ? false : true;
if (_.touchObject.curX === undefined) {
return false;
}
if (_.touchObject.edgeHit === true) {
_.$slider.trigger('edge', [_, _.swipeDirection()]);
}
if (_.touchObject.swipeLength >= _.touchObject.minSwipe) {
direction = _.swipeDirection();
switch (direction) {
case 'left':
case 'down':
slideCount =
_.options.swipeToSlide ?
_.checkNavigable(_.currentSlide + _.getSlideCount()) :
_.currentSlide + _.getSlideCount();
_.currentDirection = 0;
break;
case 'right':
case 'up':
slideCount =
_.options.swipeToSlide ?
_.checkNavigable(_.currentSlide - _.getSlideCount()) :
_.currentSlide - _.getSlideCount();
_.currentDirection = 1;
break;
default:}
if (direction != 'vertical') {
_.slideHandler(slideCount);
_.touchObject = {};
_.$slider.trigger('swipe', [_, direction]);
}
} else {
if (_.touchObject.startX !== _.touchObject.curX) {
_.slideHandler(_.currentSlide);
_.touchObject = {};
}
}
};
Slick.prototype.swipeHandler = function (event) {
var _ = this;
if (_.options.swipe === false || 'ontouchend' in document && _.options.swipe === false) {
return;
} else if (_.options.draggable === false && event.type.indexOf('mouse') !== -1) {
return;
}
_.touchObject.fingerCount = event.originalEvent && event.originalEvent.touches !== undefined ?
event.originalEvent.touches.length : 1;
_.touchObject.minSwipe = _.listWidth / _.options.
touchThreshold;
if (_.options.verticalSwiping === true) {
_.touchObject.minSwipe = _.listHeight / _.options.
touchThreshold;
}
switch (event.data.action) {
case 'start':
_.swipeStart(event);
break;
case 'move':
_.swipeMove(event);
break;
case 'end':
_.swipeEnd(event);
break;}
};
Slick.prototype.swipeMove = function (event) {
var _ = this,
edgeWasHit = false,
curLeft,swipeDirection,swipeLength,positionOffset,touches,verticalSwipeLength;
touches = event.originalEvent !== undefined ? event.originalEvent.touches : null;
if (!_.dragging || _.scrolling || touches && touches.length !== 1) {
return false;
}
curLeft = _.getLeft(_.currentSlide);
_.touchObject.curX = touches !== undefined ? touches[0].pageX : event.clientX;
_.touchObject.curY = touches !== undefined ? touches[0].pageY : event.clientY;
_.touchObject.swipeLength = Math.round(Math.sqrt(
Math.pow(_.touchObject.curX - _.touchObject.startX, 2)));
verticalSwipeLength = Math.round(Math.sqrt(
Math.pow(_.touchObject.curY - _.touchObject.startY, 2)));
if (!_.options.verticalSwiping && !_.swiping && verticalSwipeLength > 4) {
_.scrolling = true;
return false;
}
if (_.options.verticalSwiping === true) {
_.touchObject.swipeLength = verticalSwipeLength;
}
swipeDirection = _.swipeDirection();
if (event.originalEvent !== undefined && _.touchObject.swipeLength > 4) {
_.swiping = true;
event.preventDefault();
}
positionOffset = (_.options.rtl === false ? 1 : -1) * (_.touchObject.curX > _.touchObject.startX ? 1 : -1);
if (_.options.verticalSwiping === true) {
positionOffset = _.touchObject.curY > _.touchObject.startY ? 1 : -1;
}
swipeLength = _.touchObject.swipeLength;
_.touchObject.edgeHit = false;
if (_.options.infinite === false) {
if (_.currentSlide === 0 && swipeDirection === 'right' || _.currentSlide >= _.getDotCount() && swipeDirection === 'left') {
swipeLength = _.touchObject.swipeLength * _.options.edgeFriction;
_.touchObject.edgeHit = true;
}
}
if (_.options.vertical === false) {
_.swipeLeft = curLeft + swipeLength * positionOffset;
} else {
_.swipeLeft = curLeft + swipeLength * (_.$list.height() / _.listWidth) * positionOffset;
}
if (_.options.verticalSwiping === true) {
_.swipeLeft = curLeft + swipeLength * positionOffset;
}
if (_.options.fade === true || _.options.touchMove === false) {
return false;
}
if (_.animating === true) {
_.swipeLeft = null;
return false;
}
_.setCSS(_.swipeLeft);
};
Slick.prototype.swipeStart = function (event) {
var _ = this,
touches;
_.interrupted = true;
if (_.touchObject.fingerCount !== 1 || _.slideCount <= _.options.slidesToShow) {
_.touchObject = {};
return false;
}
if (event.originalEvent !== undefined && event.originalEvent.touches !== undefined) {
touches = event.originalEvent.touches[0];
}
_.touchObject.startX = _.touchObject.curX = touches !== undefined ? touches.pageX : event.clientX;
_.touchObject.startY = _.touchObject.curY = touches !== undefined ? touches.pageY : event.clientY;
_.dragging = true;
};
Slick.prototype.unfilterSlides = Slick.prototype.slickUnfilter = function () {
var _ = this;
if (_.$slidesCache !== null) {
_.unload();
_.$slideTrack.children(this.options.slide).detach();
_.$slidesCache.appendTo(_.$slideTrack);
_.reinit();
}
};
Slick.prototype.unload = function () {
var _ = this;
$('.slick-cloned', _.$slider).remove();
if (_.$dots) {
_.$dots.remove();
}
if (_.$prevArrow && _.htmlExpr.test(_.options.prevArrow)) {
_.$prevArrow.remove();
}
if (_.$nextArrow && _.htmlExpr.test(_.options.nextArrow)) {
_.$nextArrow.remove();
}
_.$slides.
removeClass('slick-slide slick-active slick-visible slick-current').
attr('aria-hidden', 'true').
css('width', '');
};
Slick.prototype.unslick = function (fromBreakpoint) {
var _ = this;
_.$slider.trigger('unslick', [_, fromBreakpoint]);
_.destroy();
};
Slick.prototype.updateArrows = function () {
var _ = this,
centerOffset;
centerOffset = Math.floor(_.options.slidesToShow / 2);
if (_.options.arrows === true &&
_.slideCount > _.options.slidesToShow &&
!_.options.infinite) {
_.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
_.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
if (_.currentSlide === 0) {
_.$prevArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
_.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
} else if (_.currentSlide >= _.slideCount - _.options.slidesToShow && _.options.centerMode === false) {
_.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
_.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
} else if (_.currentSlide >= _.slideCount - 1 && _.options.centerMode === true) {
_.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
_.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
}
}
};
Slick.prototype.updateDots = function () {
var _ = this;
if (_.$dots !== null) {
_.$dots.
find('li').
removeClass('slick-active').
end();
_.$dots.
find('li').
eq(Math.floor(_.currentSlide / _.options.slidesToScroll)).
addClass('slick-active');
}
};
Slick.prototype.visibility = function () {
var _ = this;
if (_.options.autoplay) {
if (document[_.hidden]) {
_.interrupted = true;
} else {
_.interrupted = false;
}
}
};
$.fn.slick = function () {
var _ = this,
opt = arguments[0],
args = Array.prototype.slice.call(arguments, 1),
l = _.length,
i,
ret;
for (i = 0; i < l; i++) {
if ((typeof opt === 'undefined' ? 'undefined' : _typeof(opt)) == 'object' || typeof opt == 'undefined')
_[i].slick = new Slick(_[i], opt);else
ret = _[i].slick[opt].apply(_[i].slick, args);
if (typeof ret != 'undefined') return ret;
}
return _;
};
});
/***/ }),
/* 10 */
/***/ (function(module, exports) {
module.exports = jQuery;
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });var _createClass = function () {function defineProperties(target, props) {for (var i = 0; i < props.length; i++) {var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);}}return function (Constructor, protoProps, staticProps) {if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;};}();function _classCallCheck(instance, Constructor) {if (!(instance instanceof Constructor)) {throw new TypeError("Cannot call a class as a function");}} /* jshint esversion: 6, browser: true, devel: true, indent: 2, curly: true, eqeqeq: true, futurehostile: true, latedef: true, undef: true, unused: true */
/* global $, document, window, WP */var
Ajaxy = function () {
function Ajaxy() {_classCallCheck(this, Ajaxy);
// firstLoad is checked below. It helps prevent Safari's popstate on load to
// reload (ajax) the site.
this.firstLoad = true;
// Bind function
this.ajaxBefore = this.ajaxBefore.bind(this);
this.ajaxSuccess = this.ajaxSuccess.bind(this);
this.ajaxAfter = this.ajaxAfter.bind(this);
this.ajaxErrorHandler = this.ajaxErrorHandler.bind(this);
this.handlePopState = this.handlePopState.bind(this);
// Bind links
this.bindLinks();
// Ajax events
this.ajaxSuccessEvent = new Event('ajaxySuccess');
this.ajaxEndTransition = new Event('ajaxyEndTransition');
$(window).bind('popstate', this.handlePopState);
}_createClass(Ajaxy, [{ key: 'handlePopState', value: function handlePopState()
{
if (!this.firstLoad) {
this.load(document.location.origin + document.location.pathname, false);
}
} }, { key: 'bindLinks', value: function bindLinks()
{
var siteURL = "http://" + top.location.host.toString();
this.$ajaxyLinks = $("a[href^='" + siteURL + "'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']").not('#wpadminbar a, .not-ajax');
// Find all ajaxy links and bind ajax event
this.$ajaxyLinks.click(this.handleLinkClick.bind(this));
} }, { key: 'handleLinkClick', value: function handleLinkClick(
event) {
// Detect if is cmd+click or ctrl+click or has been defaultPrevented somewhere else
if (!event.isDefaultPrevented() && !event.metaKey && !event.ctrlKey) {
event.preventDefault();
var url = event.currentTarget.href;
this.load(url);
}
return;
} }, { key: 'reset', value: function reset()
{
// Unbind click from all ajax links
this.$ajaxyLinks.unbind('click');
// Re initiate
this.bindLinks();
}
/*
* Load a new URL thru ajax
* @url {String}: URL to load
* @pushState {Bool}: Make false if a new state doens't need to be pushed (Default: true). Ex, going back
*/ }, { key: 'load', value: function load(
url) {var pushState = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
this.firstLoad = false;
if (pushState) {
// Push new history state
history.pushState(null, null, url);
}
$.ajax(url, {
dataType: 'html',
beforeSend: this.ajaxBefore,
error: this.ajaxErrorHandler,
success: this.ajaxSuccess,
complete: this.ajaxAfter });
} }, { key: 'ajaxBefore', value: function ajaxBefore(
xhr, settings) {
var $activeContent = $('#transition-cube .active .main-content');
var contentTop = $(document).scrollTop();
$activeContent.addClass('transition-content-absolute').css({
top: '-' + contentTop + 'px' });
$('body').addClass('loading');
$('#transition-cube').css('transform', 'scale(0.6)');
} }, { key: 'ajaxAfter', value: function ajaxAfter()
{
this.startTransition();
this.reset();
} }, { key: 'startTransition', value: function startTransition()
{var _this = this;
var $active = $('#transition-cube .active');
var $next = $('#transition-cube .next');
$active.removeClass('active');
$next.addClass('active');
setTimeout(function () {
$('#transition-cube .transition-cube-side').not('.active').css('opacity', '0');
$('#transition-cube').css('transform', 'scale(1)');
//$next.removeClass('next');
//$active.addClass('next');
_this.endTransition();
}, 500);
} }, { key: 'endTransition', value: function endTransition()
{var _this2 = this;
$('#transition-cube .next.active').removeClass('next');
$('#transition-cube .transition-cube-side').not('.active').addClass('next');
setTimeout(function () {
$('#transition-cube .next').css('opacity', '1');
$('body').removeClass('loading');
window.dispatchEvent(_this2.ajaxEndTransition);
}, 500);
} }, { key: 'ajaxErrorHandler', value: function ajaxErrorHandler(
jqXHR, textStatus) {
console.log(textStatus);
console.log(jqXHR);
} }, { key: 'ajaxSuccess', value: function ajaxSuccess(
data, textStatus, jqXHR) {
// Convert data into proper html to be able to fully parse thru jQuery
var respHtml = document.createElement('html');
respHtml.innerHTML = data;
// Get changes: body classes, page title, main content, header
var $bodyClasses = $('body', respHtml).attr('class');
var $content = $('.main-content', respHtml);
var $title = $('title', respHtml).text();
// Update with new title, content and classes
document.title = $title;
$('#transition-cube .next').html('').append($content);
$('body').removeAttr('class').addClass($bodyClasses + ' loading');
// Update Admin Bar
if (WP.isAdmin) {
$('#wpadminbar').html($('#wpadminbar', respHtml));
}
// Trigger event on window
window.dispatchEvent(this.ajaxSuccessEvent);
} }]);return Ajaxy;}();exports.default =
Ajaxy;
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });var _createClass = function () {function defineProperties(target, props) {for (var i = 0; i < props.length; i++) {var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);}}return function (Constructor, protoProps, staticProps) {if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;};}();function _classCallCheck(instance, Constructor) {if (!(instance instanceof Constructor)) {throw new TypeError("Cannot call a class as a function");}} /* jshint esversion: 6, browser: true, devel: true, indent: 2, curly: true, eqeqeq: true, futurehostile: true, latedef: true, undef: true, unused: true */
/* global $, document, window, WP */var
Stockists = function () {
function Stockists() {_classCallCheck(this, Stockists);
// Bind global Events
$(document).ready(this.onReady.bind(this));
$(window).on('ajaxySuccess', this.onReady.bind(this)); // Bind ajaxSuccess (custom event, comes from Ajaxy)
// Bind functions
this.handleSubmit = this.handleSubmit.bind(this);
this.requestGeolocation = this.requestGeolocation.bind(this);
this.geoSuccess = this.geoSuccess.bind(this);
this.geoError = this.geoError.bind(this);
this.handleSuccess = this.handleSuccess.bind(this);
this.handleError = this.handleError.bind(this);
this.outputMessage = this.outputMessage.bind(this);
}_createClass(Stockists, [{ key: 'onReady', value: function onReady()
{
// Get the stockists container (our main element and check)
this.$stockistsContainer = $('#find-stockists-container');
if (this.$stockistsContainer.length) {
// Get the rest of DOM elements
this.$zipCodeInput = $('#find-zip-code');
this.$submitButton = $('#find-submit');
this.$useGeolocationButton = $('#find-use-location');
// Bind to events
this.$submitButton.click(this.handleSubmit);
this.$useGeolocationButton.click(this.requestGeolocation);
}
} }, { key: 'handleSubmit', value: function handleSubmit(
event) {
event.preventDefault();
// Get input value (parsed as int)
var zipcode = parseInt(this.$zipCodeInput.val());
// Check our zipcode is exactly 5 digits
if (zipcode.toString().length !== 5) {
this.outputError('Please provide a valid zipcode');
} else {
this.findStockists({ zipcode: zipcode });
}
} }, { key: 'requestGeolocation', value: function requestGeolocation()
{
// Set loading message
this.outputMessage('Requesting your geolocation...');
// Request browser geolocation
navigator.geolocation.getCurrentPosition(this.geoSuccess, this.geoError);
} }, { key: 'geoSuccess', value: function geoSuccess(
position) {
// Get lat/lng
var _position$coords = position.coords,latitude = _position$coords.latitude,longitude = _position$coords.longitude;
this.findStockists({ latitude: latitude, longitude: longitude });
} }, { key: 'geoError', value: function geoError(
error) {
this.outputMessage('We cound\'t retrive your geolocation :(');
} }, { key: 'findStockists', value: function findStockists(
data) {
// Set loading message
this.outputMessage('Finding Stockists...');
// Make a request to find the nearest stockists
$.ajax(WP.siteUrl + '/wp-json/igv/find-stockists', {
dataType: 'json',
error: this.handleError,
success: this.handleSuccess,
data: data });
}
// Handle successful requests
}, { key: 'handleSuccess', value: function handleSuccess(data) {
// If success is false, it means no other zipcodes where found
// or an error happened in the server
if (!data.success) {
debugger;var _ref =
data.data || {},error = _ref.error;
this.outputError(error);
} else {
if (data.stockists.length) {
this.outputStockists(data.stockists);
} else {
this.outputError('We couldn\'t find stockists near you :(');
}
}
} }, { key: 'handleError', value: function handleError()
{
this.outputError();
}
/**
* Output a message in the stockists container
* @param {string} msg - The message to output
*/ }, { key: 'outputMessage', value: function outputMessage(
msg) {
this.$stockistsContainer.html('<p>' + msg + '</p>');
}
/**
* Output an error message in the stockists container
* @param {string} error - The error message to output
*/ }, { key: 'outputError', value: function outputError()
{var error = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'An error ocurred';
this.$stockistsContainer.html('<p class="error-message">' + error + '</p>');
}
/**
* Output a list of stockists
* @param {array} stockists - The list of stockists to output
*/ }, { key: 'outputStockists', value: function outputStockists(
stockists) {var _this = this;
// Clear list
this.$stockistsContainer.html('');
// Append each element
stockists.forEach(function (element) {
// Start our info string with the basics: title and address
var info = '\n <h3 class="font-size-mid">' +
element.post_title + '</h3>\n <div><a href="https://www.google.com/maps/search/' +
element._igv_stockist_address + '" target="_blank" rel="noopener noreferrer">' + element._igv_stockist_address + '</a></div>\n ';
// Phone
if (element._igv_stockist_phone !== undefined && element._igv_stockist_phone !== '') {
info += '\n <div><a href="tel:' +
element._igv_stockist_phone + '" target="_blank" rel="noopener noreferrer" class="link-underline">' + element._igv_stockist_phone + '</a></div>\n ';
}
// Links: website, facebok, instagram
if (element._igv_stockist_website !== undefined || element._igv_stockist_facebook !== undefined || element._igv_stockist_twitter !== undefined) {
// Open links paragraph
var links = '<div class="font-size-small">';
// Website
if (element._igv_stockist_website !== undefined) {
links += '<a class="font-uppercase link-underline" href="' + element._igv_stockist_website + '" target="_blank" rel="noopener noreferrer">Website</a>';
}
// Facebook
if (element._igv_stockist_facebook !== undefined) {
links += ' <a class="font-uppercase link-underline" href="' + element._igv_stockist_facebook + '" target="_blank" rel="noopener noreferrer">Facebook</a>';
}
// Instagram
if (element._igv_stockist_instagram !== undefined) {
links += ' <a class="font-uppercase link-underline" href="https://www.instagram.com/' + element._igv_stockist_instagram + '/" target="_blank" rel="noopener noreferrer">Instagram</a>';
}
// Close links paragraph
links += '</div>';
// Append to info
info += links;
}
// Append a list element with our info in it to the stockists list
_this.$stockistsContainer.append('<li>' + info + '</li>');
});
} }]);return Stockists;}();exports.default =
Stockists;
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });var _createClass = function () {function defineProperties(target, props) {for (var i = 0; i < props.length; i++) {var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);}}return function (Constructor, protoProps, staticProps) {if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;};}();function _classCallCheck(instance, Constructor) {if (!(instance instanceof Constructor)) {throw new TypeError("Cannot call a class as a function");}} /* jshint esversion: 6, browser: true, devel: true, indent: 2, curly: true, eqeqeq: true, futurehostile: true, latedef: true, undef: true, unused: true */
/* global $, document, WP */var
Cube = function () {
function Cube() {_classCallCheck(this, Cube);
this.mobileThreshold = 601;
$(window).
resize(this.onResize.bind(this)) // Bind resize
.on('ajaxyEndTransition', this.onReady.bind(this)); // Bind ajaxySuccess (custom event, comes from Ajaxy)
$(document).ready(this.onReady.bind(this));
}_createClass(Cube, [{ key: 'onResize', value: function onResize()
{
this.updateCubeStyle('recipe', '#transition-cube .active .main-content .recipe-item');
this.updateCubeStyle('product', '#transition-cube .active .main-content .archive-product-item');
} }, { key: 'onReady', value: function onReady()
{
this.bindRecipeCube();
this.bindProductCube();
} }, { key: 'bindRecipeCube', value: function bindRecipeCube()
{
if ($('.recipe-item').length) {
$('.recipe-item').on({
'click': function click() {
$('.cube-holder').removeClass('cube-active');
$(this).addClass('cube-active').find('.cube-right').addClass('cube-front');
$(this).addClass('cube-active').find('.cube-left').removeClass('cube-front');
},
'mouseleave': function mouseleave() {
$('.cube-holder').removeClass('cube-active');
$(this).find('.cube-right').removeClass('cube-front');
$(this).find('.cube-left').addClass('cube-front');
} });
this.updateCubeStyle('recipe', '#transition-cube .active .main-content .recipe-item');
}
} }, { key: 'bindProductCube', value: function bindProductCube()
{
if ($('.archive-product-item').length) {
$('.archive-product-item').on({
'mouseenter': function mouseenter() {
$('.cube-holder').removeClass('cube-active');
$(this).addClass('cube-active').find('.cube-right').addClass('cube-front');
$(this).addClass('cube-active').find('.cube-left').removeClass('cube-front');
},
'mouseleave': function mouseleave() {
$('.cube-holder').removeClass('cube-active');
$(this).find('.cube-right').removeClass('cube-front');
$(this).find('.cube-left').addClass('cube-front');
} });
this.updateCubeStyle('product', '#transition-cube .active .main-content .archive-product-item');
}
} }, { key: 'updateCubeStyle', value: function updateCubeStyle(
styleId, selector) {
if ($(selector).length) {
var width = $(selector).width() / 2;
var styleContent = '\n ' +
selector + ' .cube-left {\n transform: rotateY(-90deg) translateZ(' +
width + 'px)\n }\n ' +
selector + ' .cube-left.cube-front {\n transform: rotateY(0deg) translateZ(' +
width + 'px)\n }\n ' +
selector + ' .cube-right {\n transform: rotateY(90deg) translateZ(' +
width + 'px)\n }\n ' +
selector + ' .cube-right.cube-front {\n transform: rotateY(0deg) translateZ(' +
width + 'px)\n }';
if ($('style#cube-style-' + styleId).length) {
$('style#cube-style-' + styleId).html(styleContent);
$(selector).addClass('ready');
this.setTransition(selector);
} else {
var styleElement = '\n <style type="text/css" id="cube-style-' +
styleId + '">\n ' +
styleContent + '\n </style>';
$('head').append(styleElement);
$(selector).addClass('ready');
this.setTransition(selector);
}
}
} }, { key: 'setTransition', value: function setTransition(
selector) {
var cubeTransition = 0.6;
window.setTimeout(function () {
$(selector).find('.cube-left, .cube-right').css({
transition: 'transform ' + cubeTransition + 's ease-in-out' });
}, 100);
} }]);return Cube;}();exports.default =
Cube;
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });var _createClass = function () {function defineProperties(target, props) {for (var i = 0; i < props.length; i++) {var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);}}return function (Constructor, protoProps, staticProps) {if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;};}();function _classCallCheck(instance, Constructor) {if (!(instance instanceof Constructor)) {throw new TypeError("Cannot call a class as a function");}} /* jshint esversion: 6, browser: true, devel: true, indent: 2, curly: true, eqeqeq: true, futurehostile: true, latedef: true, undef: true, unused: true */
/* global $, document, WP */var
Mailchimp = function () {
function Mailchimp() {_classCallCheck(this, Mailchimp);
this.mobileThreshold = 601;
$(window).on('ajaxSuccess', this.onReady.bind(this)); // Bind ajaxSuccess (custom event, comes from Ajaxy)
$(document).ready(this.onReady.bind(this));
// Bind functions
this.submitForm = this.submitForm.bind(this);
this.successMessage = this.successMessage.bind(this);
}_createClass(Mailchimp, [{ key: 'onReady', value: function onReady()
{
this.$form = $('#mailchimp-form');
if (this.$form.length && WP.mailchimp !== null) {
this.$email = $('#mailchimp-email');
this.$reply = $('#mailchimp-response');
// Bind form submit event
this.$form.submit(this.submitForm);
}
} }, { key: 'submitForm', value: function submitForm()
{
var data = {};
// Get form data
var dataArray = this.$form.serializeArray();
// Create data object from form data
$.each(dataArray, function (index, item) {
data[item.name] = item.value;
});
this.handleMailchimpAjax(data, this.successMessage);
// Prevent default submit functionality
return false;
} }, { key: 'handleMailchimpAjax', value: function handleMailchimpAjax(
data, successCallback) {
// Rewrite action URL for JSONP
var url = WP.mailchimp.replace('/post?', '/post-json?').concat('&c=?');
// Ajax post to Mailchimp API
$.ajax({
url: url,
data: data,
success: successCallback,
dataType: 'jsonp',
error: function error(resp, text) {
console.log('mailchimp ajax submit error: ' + text);
} });
}
/**
* Handle response message
*/ }, { key: 'successMessage', value: function successMessage(
response) {
var msg = '';
if (response.result === 'success') {
// Success message
msg = 'You\'ve been successfully subscribed';
// Set class .valid on form elements
this.$reply.removeClass('error').addClass('valid');
this.$email.removeClass('error').addClass('valid');
} else {
// Set class .error on form elements
this.$email.removeClass('valid').addClass('error');
this.$reply.removeClass('valid').addClass('error');
// Make error message from API response
var index = -1;
try {
var parts = response.msg.split(' - ', 2);
if (parts[1] === undefined) {
msg = response.msg;
} else {
var i = parseInt(parts[0], 10);
if (i.toString() === parts[0]) {
index = parts[0];
msg = parts[1];
} else {
index = -1;
msg = response.msg;
}
}
}
catch (e) {
index = -1;
msg = response.msg;
}
}
// Show message
this.$reply.html(msg);
} }]);return Mailchimp;}();exports.default =
Mailchimp;
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });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;};}(); /* jshint esversion: 6, browser: true, devel: true, indent: 2, curly: true, eqeqeq: true, futurehostile: true, latedef: true, undef: true, unused: true */
/* global $, document, WP */
var _dayjs = __webpack_require__(16);var _dayjs2 = _interopRequireDefault(_dayjs);
var _jsCookie = __webpack_require__(1);var _jsCookie2 = _interopRequireDefault(_jsCookie);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function _classCallCheck(instance, Constructor) {if (!(instance instanceof Constructor)) {throw new TypeError("Cannot call a class as a function");}}var
AgeCheck = function () {
function AgeCheck(handleMailchimpAjax) {_classCallCheck(this, AgeCheck);
this.mobileThreshold = 601;
$(document).ready(this.onReady.bind(this));
this.handleMailchimpAjax = handleMailchimpAjax;
// Bind
this.handleAgeFormSubmit = this.handleAgeFormSubmit.bind(this);
}_createClass(AgeCheck, [{ key: 'onResize', value: function onResize()
{
} }, { key: 'onReady', value: function onReady()
{
this.checkForCookie();
this.bindAgeForm();
} }, { key: 'bindAgeForm', value: function bindAgeForm()
{
$('#submit-age').on('click', this.handleAgeFormSubmit);
} }, { key: 'handleAgeFormSubmit', value: function handleAgeFormSubmit(
event) {
event.preventDefault();
var month = $('#birthday-month').val();
var day = $('#birthday-day').val();
var year = $('#birthday-year').val();
var email = $('#mailchimp-email').val();
var validation = this.validateAgeForm(month, day, year);
if (validation.isValid === false) {
$('#age-form-response').html(validation.errorMessage).addClass('age-form-error');
} else {
_jsCookie2.default.set('legalAge', true, { expires: 1 }); // Expires in 1 day
$('body').removeClass('age-check');
if (email !== null && email !== '' && this.handleMailchimpAjax !== undefined) {
var data = { 'EMAIL': email };
this.handleMailchimpAjax(data);
}
}
} }, { key: 'validateAgeForm', value: function validateAgeForm(
month, day, year) {
//returns true or false based on validation state
var isValid = true;
var errorMessage = '';
if (month === null || month === '' || day === null || day === '' || year === null || year === '') {
isValid = false;
errorMessage = 'Please fill out all fields';
} else if (isNaN(month) || isNaN(day) || isNaN(year)) {
isValid = false;
errorMessage = 'Enter a valid number';
} else if (month > 12 || month < 1) {
isValid = false;
errorMessage = 'Enter a valid month';
} else if (day > 31 || day < 1) {
isValid = false;
errorMessage = 'Enter a valid day';
} else if (year > 2050 || year < 1900) {
isValid = false;
errorMessage = 'Enter a valid year';
} else {
var birthday = (0, _dayjs2.default)(new Date(year, month, day));
var age = (0, _dayjs2.default)().diff(birthday, 'years');
if (age < 21) {
isValid = false;
errorMessage = 'You must be of legal age to enter';
}
}
return { isValid: isValid, errorMessage: errorMessage };
} }, { key: 'checkForCookie', value: function checkForCookie()
{
var cookie = _jsCookie2.default.get('legalAge');
if (!cookie) {
$('body').addClass('age-check');
}
$('#main-container').removeClass('hide');
} }]);return AgeCheck;}();exports.default =
AgeCheck;
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_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;};!function (t, e) {"object" == ( false ? "undefined" : _typeof(exports)) && "undefined" != typeof module ? module.exports = e() : true ? !(__WEBPACK_AMD_DEFINE_FACTORY__ = (e),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
__WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : t.dayjs = e();}(undefined, function () {"use strict";var t = "second",e = "minute",n = "hour",s = "day",r = "week",i = "month",a = "year",u = "Sunday.Monday.Tuesday.Wednesday.Thursday.Friday.Saturday".split("."),c = "January.February.March.April.May.June.July.August.September.October.November.December".split("."),h = /^(\d{4})-?(\d{1,2})-?(\d{1,2})(.*?(\d{1,2}):(\d{1,2}):(\d{1,2}))?.?(\d{1,3})?$/,o = /\[.*?\]|Y{2,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,d = function d(t, e, n) {var s = String(t);return !s || s.length >= e ? t : "" + Array(e + 1 - s.length).join(n) + t;},$ = function $(t) {return t && String(t).toLowerCase().replace(/s$/, "");},f = function f(t) {return void 0 === t;},l = function l(t) {var e;return null === t ? new Date(NaN) : f(t) ? new Date() : t instanceof Date ? t : "string" == typeof t && (e = t.match(h)) ? new Date(e[1], e[2] - 1, e[3], e[5] || 0, e[6] || 0, e[7] || 0, e[8] || 0) : new Date(t);},m = function () {function h(t) {this.$d = l(t), this.init();}var m = h.prototype;return m.init = function () {this.$y = this.$d.getFullYear(), this.$M = this.$d.getMonth(), this.$D = this.$d.getDate(), this.$W = this.$d.getDay(), this.$H = this.$d.getHours(), this.$m = this.$d.getMinutes(), this.$s = this.$d.getSeconds(), this.$ms = this.$d.getMilliseconds();}, m.isValid = function () {return !("Invalid Date" === this.$d.toString());}, m.isLeapYear = function () {return this.$y % 4 == 0 && this.$y % 100 != 0 || this.$y % 400 == 0;}, m.isSame = function (t) {return this.valueOf() === t.valueOf();}, m.isBefore = function (t) {return this.valueOf() < t.valueOf();}, m.isAfter = function (t) {return this.valueOf() > t.valueOf();}, m.year = function () {return this.$y;}, m.month = function () {return this.$M;}, m.day = function () {return this.$W;}, m.date = function () {return this.$D;}, m.hour = function () {return this.$H;}, m.minute = function () {return this.$m;}, m.second = function () {return this.$s;}, m.millisecond = function () {return this.$ms;}, m.unix = function () {return Math.floor(this.valueOf() / 1e3);}, m.valueOf = function () {return this.$d.getTime();}, m.startOf = function (u, c) {var o = this,d = !!f(c) || c,l = function l(t, e, n) {void 0 === n && (n = o.$y);var r = new h(new Date(n, e, t));return d ? r : r.endOf(s);},m = function m(t, e) {return new h(o.toDate()[t].apply(o.toDate(), d ? [0, 0, 0, 0].slice(e) : [23, 59, 59, 999].slice(e)));};switch ($(u)) {case a:return d ? l(1, 0) : l(31, 11, this.$y);case i:return d ? l(1, this.$M) : l(0, this.$M + 1, this.$y);case r:return d ? l(this.$D - this.$W, this.$M) : l(this.$D + (6 - this.$W), this.$M, this.$y);case s:case "date":return m("setHours", 0);case n:return m("setMinutes", 1);case e:return m("setSeconds", 2);case t:return m("setMilliseconds", 3);default:return this.clone();}}, m.endOf = function (t) {return this.startOf(t, !1);}, m.$set = function (s, r) {switch ($(s)) {case "date":this.$d.setDate(r);break;case i:this.$d.setMonth(r);break;case a:this.$d.setFullYear(r);break;case n:this.$d.setHours(r);break;case e:this.$d.setMinutes(r);break;case t:this.$d.setSeconds(r);break;case "millisecond":this.$d.setMilliseconds(r);}return this.init(), this;}, m.set = function (t, e) {return this.clone().$set(t, e);}, m.add = function (t, u) {t = Number(t);var c,o = u && 1 === u.length ? u : $(u);if (["M", i].indexOf(o) > -1) {var d = this.set("date", 1).set(i, this.$M + t);return d = d.set("date", Math.min(this.$D, d.daysInMonth()));}if (["y", a].indexOf(o) > -1) return this.set(a, this.$y + t);switch (o) {case "m":case e:c = 6e4;break;case "h":case n:c = 36e5;break;case "d":case s:c = 864e5;break;case "w":case r:c = 6048e5;break;default:c = 1e3;}return new h(this.valueOf() + t * c);}, m.subtract = function (t, e) {return this.add(-1 * t, e);}, m.format = function (t) {var e,n,s,r,i = this,a = t || "YYYY-MM-DDTHH:mm:ssZ",h = (e = this.$d.getTimezoneOffset(), n = Math.abs(e), s = Math.floor(n / 60), r = n % 60, (e <= 0 ? "+" : "-") + d(s, 2, "0") + ":" + d(r, 2, "0"));return a.replace(o, function (t) {if (t.indexOf("[") > -1) return t.replace(/\[|\]/g, "");switch (t) {case "YY":return String(i.$y).slice(-2);case "YYYY":return String(i.$y);case "M":return String(i.$M + 1);case "MM":return d(i.$M + 1, 2, "0");case "MMM":return c[i.$M].slice(0, 3);case "MMMM":return c[i.$M];case "D":return String(i.$D);case "DD":return d(i.$D, 2, "0");case "d":return String(i.$W);case "dddd":return u[i.$W];case "H":return String(i.$H);case "HH":return d(i.$H, 2, "0");case "h":case "hh":return 0 === i.$H ? 12 : d(i.$H < 13 ? i.$H : i.$H - 12, "hh" === t ? 2 : 1, "0");case "a":return i.$H < 12 ? "am" : "pm";case "A":return i.$H < 12 ? "AM" : "PM";case "m":return String(i.$m);case "mm":return d(i.$m, 2, "0");case "s":return String(i.$s);case "ss":return d(i.$s, 2, "0");case "SSS":return d(i.$ms, 3, "0");case "Z":return h;default:return h.replace(":", "");}});}, m.diff = function (u, c, o) {var d,f,l,m,M,y,g = $(c),S = u instanceof h ? u : new h(u),D = this - S,b = (d = this, m = 12 * ((f = S).year() - d.year()) + (f.month() - d.month()), M = d.clone().add(m, "months"), l = f - M < 0 ? (f - M) / (M - d.clone().add(m - 1, "months")) : (f - M) / (d.clone().add(m + 1, "months") - M), Number(-(m + l)));switch (g) {case a:b /= 12;break;case i:break;case "quarter":b /= 3;break;case r:b = D / 6048e5;break;case s:b = D / 864e5;break;case n:b = D / 36e5;break;case e:b = D / 6e4;break;case t:b = D / 1e3;break;default:b = D;}return o ? b : (y = b) < 0 ? Math.ceil(y) || 0 : Math.floor(y);}, m.daysInMonth = function () {return this.endOf(i).$D;}, m.clone = function () {return new h(this);}, m.toDate = function () {return new Date(this.$d);}, m.toArray = function () {return [this.$y, this.$M, this.$D, this.$H, this.$m, this.$s, this.$ms];}, m.toJSON = function () {return this.toISOString();}, m.toISOString = function () {return this.toDate().toISOString();}, m.toObject = function () {return { years: this.$y, months: this.$M, date: this.$D, hours: this.$H, minutes: this.$m, seconds: this.$s, milliseconds: this.$ms };}, m.toString = function () {return this.$d.toUTCString();}, h;}();return function (t) {return new m(t);};});
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(module) {var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {return typeof obj;} : function (obj) {return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;};(function (window, factory) {
var lazySizes = factory(window, window.document);
window.lazySizes = lazySizes;
if (( false ? 'undefined' : _typeof(module)) == 'object' && module.exports) {
module.exports = lazySizes;
}
})(window, function l(window, document) {
'use strict';
/*jshint eqnull:true */
if (!document.getElementsByClassName) {return;}
var lazysizes, lazySizesConfig;
var docElem = document.documentElement;
var Date = window.Date;
var supportPicture = window.HTMLPictureElement;
var _addEventListener = 'addEventListener';
var _getAttribute = 'getAttribute';
var addEventListener = window[_addEventListener];
var setTimeout = window.setTimeout;
var requestAnimationFrame = window.requestAnimationFrame || setTimeout;
var requestIdleCallback = window.requestIdleCallback;
var regPicture = /^picture$/i;
var loadEvents = ['load', 'error', 'lazyincluded', '_lazyloaded'];
var regClassCache = {};
var forEach = Array.prototype.forEach;
var hasClass = function hasClass(ele, cls) {
if (!regClassCache[cls]) {
regClassCache[cls] = new RegExp('(\\s|^)' + cls + '(\\s|$)');
}
return regClassCache[cls].test(ele[_getAttribute]('class') || '') && regClassCache[cls];
};
var addClass = function addClass(ele, cls) {
if (!hasClass(ele, cls)) {
ele.setAttribute('class', (ele[_getAttribute]('class') || '').trim() + ' ' + cls);
}
};
var removeClass = function removeClass(ele, cls) {
var reg;
if (reg = hasClass(ele, cls)) {
ele.setAttribute('class', (ele[_getAttribute]('class') || '').replace(reg, ' '));
}
};
var addRemoveLoadEvents = function addRemoveLoadEvents(dom, fn, add) {
var action = add ? _addEventListener : 'removeEventListener';
if (add) {
addRemoveLoadEvents(dom, fn);
}
loadEvents.forEach(function (evt) {
dom[action](evt, fn);
});
};
var triggerEvent = function triggerEvent(elem, name, detail, noBubbles, noCancelable) {
var event = document.createEvent('CustomEvent');
if (!detail) {
detail = {};
}
detail.instance = lazysizes;
event.initCustomEvent(name, !noBubbles, !noCancelable, detail);
elem.dispatchEvent(event);
return event;
};
var updatePolyfill = function updatePolyfill(el, full) {
var polyfill;
if (!supportPicture && (polyfill = window.picturefill || lazySizesConfig.pf)) {
polyfill({ reevaluate: true, elements: [el] });
} else if (full && full.src) {
el.src = full.src;
}
};
var getCSS = function getCSS(elem, style) {
return (getComputedStyle(elem, null) || {})[style];
};
var getWidth = function getWidth(elem, parent, width) {
width = width || elem.offsetWidth;
while (width < lazySizesConfig.minSize && parent && !elem._lazysizesWidth) {
width = parent.offsetWidth;
parent = parent.parentNode;
}
return width;
};
var rAF = function () {
var running, waiting;
var firstFns = [];
var secondFns = [];
var fns = firstFns;
var run = function run() {
var runFns = fns;
fns = firstFns.length ? secondFns : firstFns;
running = true;
waiting = false;
while (runFns.length) {
runFns.shift()();
}
running = false;
};
var rafBatch = function rafBatch(fn, queue) {
if (running && !queue) {
fn.apply(this, arguments);
} else {
fns.push(fn);
if (!waiting) {
waiting = true;
(document.hidden ? setTimeout : requestAnimationFrame)(run);
}
}
};
rafBatch._lsFlush = run;
return rafBatch;
}();
var rAFIt = function rAFIt(fn, simple) {
return simple ?
function () {
rAF(fn);
} :
function () {
var that = this;
var args = arguments;
rAF(function () {
fn.apply(that, args);
});
};
};
var throttle = function throttle(fn) {
var running;
var lastTime = 0;
var gDelay = 125;
var rICTimeout = lazySizesConfig.ricTimeout;
var run = function run() {
running = false;
lastTime = Date.now();
fn();
};
var idleCallback = requestIdleCallback && lazySizesConfig.ricTimeout ?
function () {
requestIdleCallback(run, { timeout: rICTimeout });
if (rICTimeout !== lazySizesConfig.ricTimeout) {
rICTimeout = lazySizesConfig.ricTimeout;
}
} :
rAFIt(function () {
setTimeout(run);
}, true);
return function (isPriority) {
var delay;
if (isPriority = isPriority === true) {
rICTimeout = 33;
}
if (running) {
return;
}
running = true;
delay = gDelay - (Date.now() - lastTime);
if (delay < 0) {
delay = 0;
}
if (isPriority || delay < 9 && requestIdleCallback) {
idleCallback();
} else {
setTimeout(idleCallback, delay);
}
};
};
//based on http://modernjavascript.blogspot.de/2013/08/building-better-debounce.html
var debounce = function debounce(func) {
var timeout, timestamp;
var wait = 99;
var run = function run() {
timeout = null;
func();
};
var later = function later() {
var last = Date.now() - timestamp;
if (last < wait) {
setTimeout(later, wait - last);
} else {
(requestIdleCallback || run)(run);
}
};
return function () {
timestamp = Date.now();
if (!timeout) {
timeout = setTimeout(later, wait);
}
};
};
(function () {
var prop;
var lazySizesDefaults = {
lazyClass: 'lazyload',
loadedClass: 'lazyloaded',
loadingClass: 'lazyloading',
preloadClass: 'lazypreload',
errorClass: 'lazyerror',
//strictClass: 'lazystrict',
autosizesClass: 'lazyautosizes',
srcAttr: 'data-src',
srcsetAttr: 'data-srcset',
sizesAttr: 'data-sizes',
//preloadAfterLoad: false,
minSize: 40,
customMedia: {},
init: true,
expFactor: 1.5,
hFac: 0.8,
loadMode: 2,
loadHidden: true,
ricTimeout: 300 };
lazySizesConfig = window.lazySizesConfig || window.lazysizesConfig || {};
for (prop in lazySizesDefaults) {
if (!(prop in lazySizesConfig)) {
lazySizesConfig[prop] = lazySizesDefaults[prop];
}
}
window.lazySizesConfig = lazySizesConfig;
setTimeout(function () {
if (lazySizesConfig.init) {
init();
}
});
})();
var loader = function () {
var preloadElems, isCompleted, resetPreloadingTimer, loadMode, started;
var eLvW, elvH, eLtop, eLleft, eLright, eLbottom;
var defaultExpand, preloadExpand, hFac;
var regImg = /^img$/i;
var regIframe = /^iframe$/i;
var supportScroll = 'onscroll' in window && !/glebot/.test(navigator.userAgent);
var shrinkExpand = 0;
var currentExpand = 0;
var isLoading = 0;
var lowRuns = -1;
var resetPreloading = function resetPreloading(e) {
isLoading--;
if (e && e.target) {
addRemoveLoadEvents(e.target, resetPreloading);
}
if (!e || isLoading < 0 || !e.target) {
isLoading = 0;
}
};
var isNestedVisible = function isNestedVisible(elem, elemExpand) {
var outerRect;
var parent = elem;
var visible = getCSS(document.body, 'visibility') == 'hidden' || getCSS(elem, 'visibility') != 'hidden';
eLtop -= elemExpand;
eLbottom += elemExpand;
eLleft -= elemExpand;
eLright += elemExpand;
while (visible && (parent = parent.offsetParent) && parent != document.body && parent != docElem) {
visible = (getCSS(parent, 'opacity') || 1) > 0;
if (visible && getCSS(parent, 'overflow') != 'visible') {
outerRect = parent.getBoundingClientRect();
visible = eLright > outerRect.left &&
eLleft < outerRect.right &&
eLbottom > outerRect.top - 1 &&
eLtop < outerRect.bottom + 1;
}
}
return visible;
};
var checkElements = function checkElements() {
var eLlen, i, rect, autoLoadElem, loadedSomething, elemExpand, elemNegativeExpand, elemExpandVal, beforeExpandVal;
var lazyloadElems = lazysizes.elements;
if ((loadMode = lazySizesConfig.loadMode) && isLoading < 8 && (eLlen = lazyloadElems.length)) {
i = 0;
lowRuns++;
if (preloadExpand == null) {
if (!('expand' in lazySizesConfig)) {
lazySizesConfig.expand = docElem.clientHeight > 500 && docElem.clientWidth > 500 ? 500 : 370;
}
defaultExpand = lazySizesConfig.expand;
preloadExpand = defaultExpand * lazySizesConfig.expFactor;
}
if (currentExpand < preloadExpand && isLoading < 1 && lowRuns > 2 && loadMode > 2 && !document.hidden) {
currentExpand = preloadExpand;
lowRuns = 0;
} else if (loadMode > 1 && lowRuns > 1 && isLoading < 6) {
currentExpand = defaultExpand;
} else {
currentExpand = shrinkExpand;
}
for (; i < eLlen; i++) {
if (!lazyloadElems[i] || lazyloadElems[i]._lazyRace) {continue;}
if (!supportScroll) {unveilElement(lazyloadElems[i]);continue;}
if (!(elemExpandVal = lazyloadElems[i][_getAttribute]('data-expand')) || !(elemExpand = elemExpandVal * 1)) {
elemExpand = currentExpand;
}
if (beforeExpandVal !== elemExpand) {
eLvW = innerWidth + elemExpand * hFac;
elvH = innerHeight + elemExpand;
elemNegativeExpand = elemExpand * -1;
beforeExpandVal = elemExpand;
}
rect = lazyloadElems[i].getBoundingClientRect();
if ((eLbottom = rect.bottom) >= elemNegativeExpand &&
(eLtop = rect.top) <= elvH &&
(eLright = rect.right) >= elemNegativeExpand * hFac &&
(eLleft = rect.left) <= eLvW && (
eLbottom || eLright || eLleft || eLtop) && (
lazySizesConfig.loadHidden || getCSS(lazyloadElems[i], 'visibility') != 'hidden') && (
isCompleted && isLoading < 3 && !elemExpandVal && (loadMode < 3 || lowRuns < 4) || isNestedVisible(lazyloadElems[i], elemExpand))) {
unveilElement(lazyloadElems[i]);
loadedSomething = true;
if (isLoading > 9) {break;}
} else if (!loadedSomething && isCompleted && !autoLoadElem &&
isLoading < 4 && lowRuns < 4 && loadMode > 2 && (
preloadElems[0] || lazySizesConfig.preloadAfterLoad) && (
preloadElems[0] || !elemExpandVal && (eLbottom || eLright || eLleft || eLtop || lazyloadElems[i][_getAttribute](lazySizesConfig.sizesAttr) != 'auto'))) {
autoLoadElem = preloadElems[0] || lazyloadElems[i];
}
}
if (autoLoadElem && !loadedSomething) {
unveilElement(autoLoadElem);
}
}
};
var throttledCheckElements = throttle(checkElements);
var switchLoadingClass = function switchLoadingClass(e) {
addClass(e.target, lazySizesConfig.loadedClass);
removeClass(e.target, lazySizesConfig.loadingClass);
addRemoveLoadEvents(e.target, rafSwitchLoadingClass);
triggerEvent(e.target, 'lazyloaded');
};
var rafedSwitchLoadingClass = rAFIt(switchLoadingClass);
var rafSwitchLoadingClass = function rafSwitchLoadingClass(e) {
rafedSwitchLoadingClass({ target: e.target });
};
var changeIframeSrc = function changeIframeSrc(elem, src) {
try {
elem.contentWindow.location.replace(src);
} catch (e) {
elem.src = src;
}
};
var handleSources = function handleSources(source) {
var customMedia;
var sourceSrcset = source[_getAttribute](lazySizesConfig.srcsetAttr);
if (customMedia = lazySizesConfig.customMedia[source[_getAttribute]('data-media') || source[_getAttribute]('media')]) {
source.setAttribute('media', customMedia);
}
if (sourceSrcset) {
source.setAttribute('srcset', sourceSrcset);
}
};
var lazyUnveil = rAFIt(function (elem, detail, isAuto, sizes, isImg) {
var src, srcset, parent, isPicture, event, firesLoad;
if (!(event = triggerEvent(elem, 'lazybeforeunveil', detail)).defaultPrevented) {
if (sizes) {
if (isAuto) {
addClass(elem, lazySizesConfig.autosizesClass);
} else {
elem.setAttribute('sizes', sizes);
}
}
srcset = elem[_getAttribute](lazySizesConfig.srcsetAttr);
src = elem[_getAttribute](lazySizesConfig.srcAttr);
if (isImg) {
parent = elem.parentNode;
isPicture = parent && regPicture.test(parent.nodeName || '');
}
firesLoad = detail.firesLoad || 'src' in elem && (srcset || src || isPicture);
event = { target: elem };
if (firesLoad) {
addRemoveLoadEvents(elem, resetPreloading, true);
clearTimeout(resetPreloadingTimer);
resetPreloadingTimer = setTimeout(resetPreloading, 2500);
addClass(elem, lazySizesConfig.loadingClass);
addRemoveLoadEvents(elem, rafSwitchLoadingClass, true);
}
if (isPicture) {
forEach.call(parent.getElementsByTagName('source'), handleSources);
}
if (srcset) {
elem.setAttribute('srcset', srcset);
} else if (src && !isPicture) {
if (regIframe.test(elem.nodeName)) {
changeIframeSrc(elem, src);
} else {
elem.src = src;
}
}
if (isImg && (srcset || isPicture)) {
updatePolyfill(elem, { src: src });
}
}
if (elem._lazyRace) {
delete elem._lazyRace;
}
removeClass(elem, lazySizesConfig.lazyClass);
rAF(function () {
if (!firesLoad || elem.complete && elem.naturalWidth > 1) {
if (firesLoad) {
resetPreloading(event);
} else {
isLoading--;
}
switchLoadingClass(event);
}
}, true);
});
var unveilElement = function unveilElement(elem) {
var detail;
var isImg = regImg.test(elem.nodeName);
//allow using sizes="auto", but don't use. it's invalid. Use data-sizes="auto" or a valid value for sizes instead (i.e.: sizes="80vw")
var sizes = isImg && (elem[_getAttribute](lazySizesConfig.sizesAttr) || elem[_getAttribute]('sizes'));
var isAuto = sizes == 'auto';
if ((isAuto || !isCompleted) && isImg && (elem[_getAttribute]('src') || elem.srcset) && !elem.complete && !hasClass(elem, lazySizesConfig.errorClass) && hasClass(elem, lazySizesConfig.lazyClass)) {return;}
detail = triggerEvent(elem, 'lazyunveilread').detail;
if (isAuto) {
autoSizer.updateElem(elem, true, elem.offsetWidth);
}
elem._lazyRace = true;
isLoading++;
lazyUnveil(elem, detail, isAuto, sizes, isImg);
};
var onload = function onload() {
if (isCompleted) {return;}
if (Date.now() - started < 999) {
setTimeout(onload, 999);
return;
}
var afterScroll = debounce(function () {
lazySizesConfig.loadMode = 3;
throttledCheckElements();
});
isCompleted = true;
lazySizesConfig.loadMode = 3;
throttledCheckElements();
addEventListener('scroll', function () {
if (lazySizesConfig.loadMode == 3) {
lazySizesConfig.loadMode = 2;
}
afterScroll();
}, true);
};
return {
_: function _() {
started = Date.now();
lazysizes.elements = document.getElementsByClassName(lazySizesConfig.lazyClass);
preloadElems = document.getElementsByClassName(lazySizesConfig.lazyClass + ' ' + lazySizesConfig.preloadClass);
hFac = lazySizesConfig.hFac;
addEventListener('scroll', throttledCheckElements, true);
addEventListener('resize', throttledCheckElements, true);
if (window.MutationObserver) {
new MutationObserver(throttledCheckElements).observe(docElem, { childList: true, subtree: true, attributes: true });
} else {
docElem[_addEventListener]('DOMNodeInserted', throttledCheckElements, true);
docElem[_addEventListener]('DOMAttrModified', throttledCheckElements, true);
setInterval(throttledCheckElements, 999);
}
addEventListener('hashchange', throttledCheckElements, true);
//, 'fullscreenchange'
['focus', 'mouseover', 'click', 'load', 'transitionend', 'animationend', 'webkitAnimationEnd'].forEach(function (name) {
document[_addEventListener](name, throttledCheckElements, true);
});
if (/d$|^c/.test(document.readyState)) {
onload();
} else {
addEventListener('load', onload);
document[_addEventListener]('DOMContentLoaded', throttledCheckElements);
setTimeout(onload, 20000);
}
if (lazysizes.elements.length) {
checkElements();
rAF._lsFlush();
} else {
throttledCheckElements();
}
},
checkElems: throttledCheckElements,
unveil: unveilElement };
}();
var autoSizer = function () {
var autosizesElems;
var sizeElement = rAFIt(function (elem, parent, event, width) {
var sources, i, len;
elem._lazysizesWidth = width;
width += 'px';
elem.setAttribute('sizes', width);
if (regPicture.test(parent.nodeName || '')) {
sources = parent.getElementsByTagName('source');
for (i = 0, len = sources.length; i < len; i++) {
sources[i].setAttribute('sizes', width);
}
}
if (!event.detail.dataAttr) {
updatePolyfill(elem, event.detail);
}
});
var getSizeElement = function getSizeElement(elem, dataAttr, width) {
var event;
var parent = elem.parentNode;
if (parent) {
width = getWidth(elem, parent, width);
event = triggerEvent(elem, 'lazybeforesizes', { width: width, dataAttr: !!dataAttr });
if (!event.defaultPrevented) {
width = event.detail.width;
if (width && width !== elem._lazysizesWidth) {
sizeElement(elem, parent, event, width);
}
}
}
};
var updateElementsSizes = function updateElementsSizes() {
var i;
var len = autosizesElems.length;
if (len) {
i = 0;
for (; i < len; i++) {
getSizeElement(autosizesElems[i]);
}
}
};
var debouncedUpdateElementsSizes = debounce(updateElementsSizes);
return {
_: function _() {
autosizesElems = document.getElementsByClassName(lazySizesConfig.autosizesClass);
addEventListener('resize', debouncedUpdateElementsSizes);
},
checkElems: debouncedUpdateElementsSizes,
updateElem: getSizeElement };
}();
var init = function init() {
if (!init.i) {
init.i = true;
autoSizer._();
loader._();
}
};
lazysizes = {
cfg: lazySizesConfig,
autoSizer: autoSizer,
loader: loader,
init: init,
uP: updatePolyfill,
aC: addClass,
rC: removeClass,
hC: hasClass,
fire: triggerEvent,
gW: getWidth,
rAF: rAF };
return lazysizes;
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18)(module)))
/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function (module) {
if (!module.webpackPolyfill) {
module.deprecate = function () {};
module.paths = [];
// module.parent = undefined by default
if (!module.children) module.children = [];
Object.defineProperty(module, "loaded", {
enumerable: true,
get: function get() {
return module.l;
} });
Object.defineProperty(module, "id", {
enumerable: true,
get: function get() {
return module.i;
} });
module.webpackPolyfill = 1;
}
return module;
};
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_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;}; /*!
* ScrollMagic v2.0.5 (2015-04-29)
* The javascript library for magical scroll interactions.
* (c) 2015 Jan Paepke (@janpaepke)
* Project Website: http://scrollmagic.io
*
* @version 2.0.5
* @license Dual licensed under MIT license and GPL.
* @author Jan Paepke - e-mail@janpaepke.de
*
* @file ScrollMagic GSAP Animation Plugin.
*
* requires: GSAP ~1.14
* Powered by the Greensock Animation Platform (GSAP): http://www.greensock.com/js
* Greensock License info at http://www.greensock.com/licensing/
*/
/**
* This plugin is meant to be used in conjunction with the Greensock Animation Plattform.
* It offers an easy API to trigger Tweens or synchronize them to the scrollbar movement.
*
* Both the `lite` and the `max` versions of the GSAP library are supported.
* The most basic requirement is `TweenLite`.
*
* To have access to this extension, please include `plugins/animation.gsap.js`.
* @requires {@link http://greensock.com/gsap|GSAP ~1.14.x}
* @mixin animation.GSAP
*/
(function (root, factory) {
if (true) {
// AMD. Register as an anonymous module.
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(2), __webpack_require__(3), __webpack_require__(20)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ((typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) === 'object') {
// CommonJS
// Loads whole gsap package onto global scope.
require('gsap');
factory(require('scrollmagic'), TweenMax, TimelineMax);
} else {
// Browser globals
factory(root.ScrollMagic || root.jQuery && root.jQuery.ScrollMagic, root.TweenMax || root.TweenLite, root.TimelineMax || root.TimelineLite);
}
})(undefined, function (ScrollMagic, Tween, Timeline) {
"use strict";
var NAMESPACE = "animation.gsap";
var
console = window.console || {},
err = Function.prototype.bind.call(console.error || console.log ||
function () {}, console);
if (!ScrollMagic) {
err("(" + NAMESPACE + ") -> ERROR: The ScrollMagic main module could not be found. Please make sure it's loaded before this plugin or use an asynchronous loader like requirejs.");
}
if (!Tween) {
err("(" + NAMESPACE + ") -> ERROR: TweenLite or TweenMax could not be found. Please make sure GSAP is loaded before ScrollMagic or use an asynchronous loader like requirejs.");
}
/*
* ----------------------------------------------------------------
* Extensions for Scene
* ----------------------------------------------------------------
*/
/**
* Every instance of ScrollMagic.Scene now accepts an additional option.
* See {@link ScrollMagic.Scene} for a complete list of the standard options.
* @memberof! animation.GSAP#
* @method new ScrollMagic.Scene(options)
* @example
* var scene = new ScrollMagic.Scene({tweenChanges: true});
*
* @param {object} [options] - Options for the Scene. The options can be updated at any time.
* @param {boolean} [options.tweenChanges=false] - Tweens Animation to the progress target instead of setting it.
Does not affect animations where duration is `0`.
*/
/**
* **Get** or **Set** the tweenChanges option value.
* This only affects scenes with a duration. If `tweenChanges` is `true`, the progress update when scrolling will not be immediate, but instead the animation will smoothly animate to the target state.
* For a better understanding, try enabling and disabling this option in the [Scene Manipulation Example](../examples/basic/scene_manipulation.html).
* @memberof! animation.GSAP#
* @method Scene.tweenChanges
*
* @example
* // get the current tweenChanges option
* var tweenChanges = scene.tweenChanges();
*
* // set new tweenChanges option
* scene.tweenChanges(true);
*
* @fires {@link Scene.change}, when used as setter
* @param {boolean} [newTweenChanges] - The new tweenChanges setting of the scene.
* @returns {boolean} `get` - Current tweenChanges option value.
* @returns {Scene} `set` - Parent object for chaining.
*/
// add option (TODO: DOC (private for dev))
ScrollMagic.Scene.addOption("tweenChanges", // name
false, // default
function (val) {// validation callback
return !!val;
});
// extend scene
ScrollMagic.Scene.extend(function () {
var Scene = this,
_tween;
var log = function log() {
if (Scene._log) {// not available, when main source minified
Array.prototype.splice.call(arguments, 1, 0, "(" + NAMESPACE + ")", "->");
Scene._log.apply(this, arguments);
}
};
// set listeners
Scene.on("progress.plugin_gsap", function () {
updateTweenProgress();
});
Scene.on("destroy.plugin_gsap", function (e) {
Scene.removeTween(e.reset);
});
/**
* Update the tween progress to current position.
* @private
*/
var updateTweenProgress = function updateTweenProgress() {
if (_tween) {
var
progress = Scene.progress(),
state = Scene.state();
if (_tween.repeat && _tween.repeat() === -1) {
// infinite loop, so not in relation to progress
if (state === 'DURING' && _tween.paused()) {
_tween.play();
} else if (state !== 'DURING' && !_tween.paused()) {
_tween.pause();
}
} else if (progress != _tween.progress()) {// do we even need to update the progress?
// no infinite loop - so should we just play or go to a specific point in time?
if (Scene.duration() === 0) {
// play the animation
if (progress > 0) {// play from 0 to 1
_tween.play();
} else {// play from 1 to 0
_tween.reverse();
}
} else {
// go to a specific point in time
if (Scene.tweenChanges() && _tween.tweenTo) {
// go smooth
_tween.tweenTo(progress * _tween.duration());
} else {
// just hard set it
_tween.progress(progress).pause();
}
}
}
}
};
/**
* Add a tween to the scene.
* If you want to add multiple tweens, add them into a GSAP Timeline object and supply it instead (see example below).
*
* If the scene has a duration, the tween's duration will be projected to the scroll distance of the scene, meaning its progress will be synced to scrollbar movement.
* For a scene with a duration of `0`, the tween will be triggered when scrolling forward past the scene's trigger position and reversed, when scrolling back.
* To gain better understanding, check out the [Simple Tweening example](../examples/basic/simple_tweening.html).
*
* Instead of supplying a tween this method can also be used as a shorthand for `TweenMax.to()` (see example below).
* @memberof! animation.GSAP#
*
* @example
* // add a single tween directly
* scene.setTween(TweenMax.to("obj"), 1, {x: 100});
*
* // add a single tween via variable
* var tween = TweenMax.to("obj"), 1, {x: 100};
* scene.setTween(tween);
*
* // add multiple tweens, wrapped in a timeline.
* var timeline = new TimelineMax();
* var tween1 = TweenMax.from("obj1", 1, {x: 100});
* var tween2 = TweenMax.to("obj2", 1, {y: 100});
* timeline
* .add(tween1)
* .add(tween2);
* scene.addTween(timeline);
*
* // short hand to add a TweenMax.to() tween
* scene.setTween("obj3", 0.5, {y: 100});
*
* // short hand to add a TweenMax.to() tween for 1 second
* // this is useful, when the scene has a duration and the tween duration isn't important anyway
* scene.setTween("obj3", {y: 100});
*
* @param {(object|string)} TweenObject - A TweenMax, TweenLite, TimelineMax or TimelineLite object that should be animated in the scene. Can also be a Dom Element or Selector, when using direct tween definition (see examples).
* @param {(number|object)} duration - A duration for the tween, or tween parameters. If an object containing parameters are supplied, a default duration of 1 will be used.
* @param {object} params - The parameters for the tween
* @returns {Scene} Parent object for chaining.
*/
Scene.setTween = function (TweenObject, duration, params) {
var newTween;
if (arguments.length > 1) {
if (arguments.length < 3) {
params = duration;
duration = 1;
}
TweenObject = Tween.to(TweenObject, duration, params);
}
try {
// wrap Tween into a Timeline Object if available to include delay and repeats in the duration and standardize methods.
if (Timeline) {
newTween = new Timeline({
smoothChildTiming: true }).
add(TweenObject);
} else {
newTween = TweenObject;
}
newTween.pause();
} catch (e) {
log(1, "ERROR calling method 'setTween()': Supplied argument is not a valid TweenObject");
return Scene;
}
if (_tween) {// kill old tween?
Scene.removeTween();
}
_tween = newTween;
// some properties need to be transferred it to the wrapper, otherwise they would get lost.
if (TweenObject.repeat && TweenObject.repeat() === -1) {// TweenMax or TimelineMax Object?
_tween.repeat(-1);
_tween.yoyo(TweenObject.yoyo());
}
// Some tween validations and debugging helpers
if (Scene.tweenChanges() && !_tween.tweenTo) {
log(2, "WARNING: tweenChanges will only work if the TimelineMax object is available for ScrollMagic.");
}
// check if there are position tweens defined for the trigger and warn about it :)
if (_tween && Scene.controller() && Scene.triggerElement() && Scene.loglevel() >= 2) {// controller is needed to know scroll direction.
var
triggerTweens = Tween.getTweensOf(Scene.triggerElement()),
vertical = Scene.controller().info("vertical");
triggerTweens.forEach(function (value, index) {
var
tweenvars = value.vars.css || value.vars,
condition = vertical ? tweenvars.top !== undefined || tweenvars.bottom !== undefined : tweenvars.left !== undefined || tweenvars.right !== undefined;
if (condition) {
log(2, "WARNING: Tweening the position of the trigger element affects the scene timing and should be avoided!");
return false;
}
});
}
// warn about tween overwrites, when an element is tweened multiple times
if (parseFloat(TweenLite.version) >= 1.14) {// onOverwrite only present since GSAP v1.14.0
var
list = _tween.getChildren ? _tween.getChildren(true, true, false) : [_tween],
// get all nested tween objects
newCallback = function newCallback() {
log(2, "WARNING: tween was overwritten by another. To learn how to avoid this issue see here: https://github.com/janpaepke/ScrollMagic/wiki/WARNING:-tween-was-overwritten-by-another");
};
for (var i = 0, thisTween, oldCallback; i < list.length; i++) {/*jshint loopfunc: true */
thisTween = list[i];
if (oldCallback !== newCallback) {// if tweens is added more than once
oldCallback = thisTween.vars.onOverwrite;
thisTween.vars.onOverwrite = function () {
if (oldCallback) {
oldCallback.apply(this, arguments);
}
newCallback.apply(this, arguments);
};
}
}
}
log(3, "added tween");
updateTweenProgress();
return Scene;
};
/**
* Remove the tween from the scene.
* This will terminate the control of the Scene over the tween.
*
* Using the reset option you can decide if the tween should remain in the current state or be rewound to set the target elements back to the state they were in before the tween was added to the scene.
* @memberof! animation.GSAP#
*
* @example
* // remove the tween from the scene without resetting it
* scene.removeTween();
*
* // remove the tween from the scene and reset it to initial position
* scene.removeTween(true);
*
* @param {boolean} [reset=false] - If `true` the tween will be reset to its initial values.
* @returns {Scene} Parent object for chaining.
*/
Scene.removeTween = function (reset) {
if (_tween) {
if (reset) {
_tween.progress(0).pause();
}
_tween.kill();
_tween = undefined;
log(3, "removed tween (reset: " + (reset ? "true" : "false") + ")");
}
return Scene;
};
});
});
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__; /*!
* VERSION: 1.20.4
* DATE: 2018-02-15
* UPDATES AND DOCS AT: http://greensock.com
*
* @license Copyright (c) 2008-2018, GreenSock. All rights reserved.
* This work is subject to the terms at http://greensock.com/standard-license or for
* Club GreenSock members, the software agreement that was issued with your membership.
*
* @author: Jack Doyle, jack@greensock.com
*/
var _gsScope = typeof module !== "undefined" && module.exports && typeof global !== "undefined" ? global : undefined || window; //helps ensure compatibility with AMD/RequireJS and CommonJS/Node
(_gsScope._gsQueue || (_gsScope._gsQueue = [])).push(function () {
"use strict";
_gsScope._gsDefine("TimelineMax", ["TimelineLite", "TweenLite", "easing.Ease"], function (TimelineLite, TweenLite, Ease) {
var TimelineMax = function TimelineMax(vars) {
TimelineLite.call(this, vars);
this._repeat = this.vars.repeat || 0;
this._repeatDelay = this.vars.repeatDelay || 0;
this._cycle = 0;
this._yoyo = this.vars.yoyo === true;
this._dirty = true;
},
_tinyNum = 0.0000000001,
TweenLiteInternals = TweenLite._internals,
_lazyTweens = TweenLiteInternals.lazyTweens,
_lazyRender = TweenLiteInternals.lazyRender,
_globals = _gsScope._gsDefine.globals,
_easeNone = new Ease(null, null, 1, 0),
p = TimelineMax.prototype = new TimelineLite();
p.constructor = TimelineMax;
p.kill()._gc = false;
TimelineMax.version = "1.20.4";
p.invalidate = function () {
this._yoyo = this.vars.yoyo === true;
this._repeat = this.vars.repeat || 0;
this._repeatDelay = this.vars.repeatDelay || 0;
this._uncache(true);
return TimelineLite.prototype.invalidate.call(this);
};
p.addCallback = function (callback, position, params, scope) {
return this.add(TweenLite.delayedCall(0, callback, params, scope), position);
};
p.removeCallback = function (callback, position) {
if (callback) {
if (position == null) {
this._kill(null, callback);
} else {
var a = this.getTweensOf(callback, false),
i = a.length,
time = this._parseTimeOrLabel(position);
while (--i > -1) {
if (a[i]._startTime === time) {
a[i]._enabled(false, false);
}
}
}
}
return this;
};
p.removePause = function (position) {
return this.removeCallback(TimelineLite._internals.pauseCallback, position);
};
p.tweenTo = function (position, vars) {
vars = vars || {};
var copy = { ease: _easeNone, useFrames: this.usesFrames(), immediateRender: false, lazy: false },
Engine = vars.repeat && _globals.TweenMax || TweenLite,
duration,p,t;
for (p in vars) {
copy[p] = vars[p];
}
copy.time = this._parseTimeOrLabel(position);
duration = Math.abs(Number(copy.time) - this._time) / this._timeScale || 0.001;
t = new Engine(this, duration, copy);
copy.onStart = function () {
t.target.paused(true);
if (t.vars.time !== t.target.time() && duration === t.duration() && !t.isFromTo) {//don't make the duration zero - if it's supposed to be zero, don't worry because it's already initting the tween and will complete immediately, effectively making the duration zero anyway. If we make duration zero, the tween won't run at all.
t.duration(Math.abs(t.vars.time - t.target.time()) / t.target._timeScale).render(t.time(), true, true); //render() right away to ensure that things look right, especially in the case of .tweenTo(0).
}
if (vars.onStart) {//in case the user had an onStart in the vars - we don't want to overwrite it.
vars.onStart.apply(vars.onStartScope || vars.callbackScope || t, vars.onStartParams || []); //don't use t._callback("onStart") or it'll point to the copy.onStart and we'll get a recursion error.
}
};
return t;
};
p.tweenFromTo = function (fromPosition, toPosition, vars) {
vars = vars || {};
fromPosition = this._parseTimeOrLabel(fromPosition);
vars.startAt = { onComplete: this.seek, onCompleteParams: [fromPosition], callbackScope: this };
vars.immediateRender = vars.immediateRender !== false;
var t = this.tweenTo(toPosition, vars);
t.isFromTo = 1; //to ensure we don't mess with the duration in the onStart (we've got the start and end values here, so lock it in)
return t.duration(Math.abs(t.vars.time - fromPosition) / this._timeScale || 0.001);
};
p.render = function (time, suppressEvents, force) {
if (this._gc) {
this._enabled(true, false);
}
var prevTime = this._time,
totalDur = !this._dirty ? this._totalDuration : this.totalDuration(),
dur = this._duration,
prevTotalTime = this._totalTime,
prevStart = this._startTime,
prevTimeScale = this._timeScale,
prevRawPrevTime = this._rawPrevTime,
prevPaused = this._paused,
prevCycle = this._cycle,
tween,isComplete,next,callback,internalForce,cycleDuration,pauseTween,curTime;
if (prevTime !== this._time) {//if totalDuration() finds a child with a negative startTime and smoothChildTiming is true, things get shifted around internally so we need to adjust the time accordingly. For example, if a tween starts at -30 we must shift EVERYTHING forward 30 seconds and move this timeline's startTime backward by 30 seconds so that things align with the playhead (no jump).
time += this._time - prevTime;
}
if (time >= totalDur - 0.0000001 && time >= 0) {//to work around occasional floating point math artifacts.
if (!this._locked) {
this._totalTime = totalDur;
this._cycle = this._repeat;
}
if (!this._reversed) if (!this._hasPausedChild()) {
isComplete = true;
callback = "onComplete";
internalForce = !!this._timeline.autoRemoveChildren; //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline.
if (this._duration === 0) if (time <= 0 && time >= -0.0000001 || prevRawPrevTime < 0 || prevRawPrevTime === _tinyNum) if (prevRawPrevTime !== time && this._first) {
internalForce = true;
if (prevRawPrevTime > _tinyNum) {
callback = "onReverseComplete";
}
}
}
this._rawPrevTime = this._duration || !suppressEvents || time || this._rawPrevTime === time ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
if (this._yoyo && (this._cycle & 1) !== 0) {
this._time = time = 0;
} else {
this._time = dur;
time = dur + 0.0001; //to avoid occasional floating point rounding errors - sometimes child tweens/timelines were not being fully completed (their progress might be 0.999999999999998 instead of 1 because when _time - tween._startTime is performed, floating point errors would return a value that was SLIGHTLY off). Try (999999999999.7 - 999999999999) * 1 = 0.699951171875 instead of 0.7. We cannot do less then 0.0001 because the same issue can occur when the duration is extremely large like 999999999999 in which case adding 0.00000001, for example, causes it to act like nothing was added.
}
} else if (time < 0.0000001) {//to work around occasional floating point math artifacts, round super small values to 0.
if (!this._locked) {
this._totalTime = this._cycle = 0;
}
this._time = 0;
if (prevTime !== 0 || dur === 0 && prevRawPrevTime !== _tinyNum && (prevRawPrevTime > 0 || time < 0 && prevRawPrevTime >= 0) && !this._locked) {//edge case for checking time < 0 && prevRawPrevTime >= 0: a zero-duration fromTo() tween inside a zero-duration timeline (yeah, very rare)
callback = "onReverseComplete";
isComplete = this._reversed;
}
if (time < 0) {
this._active = false;
if (this._timeline.autoRemoveChildren && this._reversed) {
internalForce = isComplete = true;
callback = "onReverseComplete";
} else if (prevRawPrevTime >= 0 && this._first) {//when going back beyond the start, force a render so that zero-duration tweens that sit at the very beginning render their start values properly. Otherwise, if the parent timeline's playhead lands exactly at this timeline's startTime, and then moves backwards, the zero-duration tweens at the beginning would still be at their end state.
internalForce = true;
}
this._rawPrevTime = time;
} else {
this._rawPrevTime = dur || !suppressEvents || time || this._rawPrevTime === time ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
if (time === 0 && isComplete) {//if there's a zero-duration tween at the very beginning of a timeline and the playhead lands EXACTLY at time 0, that tween will correctly render its end values, but we need to keep the timeline alive for one more render so that the beginning values render properly as the parent's playhead keeps moving beyond the begining. Imagine obj.x starts at 0 and then we do tl.set(obj, {x:100}).to(obj, 1, {x:200}) and then later we tl.reverse()...the goal is to have obj.x revert to 0. If the playhead happens to land on exactly 0, without this chunk of code, it'd complete the timeline and remove it from the rendering queue (not good).
tween = this._first;
while (tween && tween._startTime === 0) {
if (!tween._duration) {
isComplete = false;
}
tween = tween._next;
}
}
time = 0; //to avoid occasional floating point rounding errors (could cause problems especially with zero-duration tweens at the very beginning of the timeline)
if (!this._initted) {
internalForce = true;
}
}
} else {
if (dur === 0 && prevRawPrevTime < 0) {//without this, zero-duration repeating timelines (like with a simple callback nested at the very beginning and a repeatDelay) wouldn't render the first time through.
internalForce = true;
}
this._time = this._rawPrevTime = time;
if (!this._locked) {
this._totalTime = time;
if (this._repeat !== 0) {
cycleDuration = dur + this._repeatDelay;
this._cycle = this._totalTime / cycleDuration >> 0; //originally _totalTime % cycleDuration but floating point errors caused problems, so I normalized it. (4 % 0.8 should be 0 but it gets reported as 0.79999999!)
if (this._cycle !== 0) if (this._cycle === this._totalTime / cycleDuration && prevTotalTime <= time) {
this._cycle--; //otherwise when rendered exactly at the end time, it will act as though it is repeating (at the beginning)
}
this._time = this._totalTime - this._cycle * cycleDuration;
if (this._yoyo) if ((this._cycle & 1) !== 0) {
this._time = dur - this._time;
}
if (this._time > dur) {
this._time = dur;
time = dur + 0.0001; //to avoid occasional floating point rounding error
} else if (this._time < 0) {
this._time = time = 0;
} else {
time = this._time;
}
}
}
if (this._hasPause && !this._forcingPlayhead && !suppressEvents) {
time = this._time;
if (time >= prevTime || this._repeat && prevCycle !== this._cycle) {
tween = this._first;
while (tween && tween._startTime <= time && !pauseTween) {
if (!tween._duration) if (tween.data === "isPause" && !tween.ratio && !(tween._startTime === 0 && this._rawPrevTime === 0)) {
pauseTween = tween;
}
tween = tween._next;
}
} else {
tween = this._last;
while (tween && tween._startTime >= time && !pauseTween) {
if (!tween._duration) if (tween.data === "isPause" && tween._rawPrevTime > 0) {
pauseTween = tween;
}
tween = tween._prev;
}
}
if (pauseTween && pauseTween._startTime < dur) {
this._time = time = pauseTween._startTime;
this._totalTime = time + this._cycle * (this._totalDuration + this._repeatDelay);
}
}
}
if (this._cycle !== prevCycle) if (!this._locked) {
/*
make sure children at the end/beginning of the timeline are rendered properly. If, for example,
a 3-second long timeline rendered at 2.9 seconds previously, and now renders at 3.2 seconds (which
would get transated to 2.8 seconds if the timeline yoyos or 0.2 seconds if it just repeats), there
could be a callback or a short tween that's at 2.95 or 3 seconds in which wouldn't render. So
we need to push the timeline to the end (and/or beginning depending on its yoyo value). Also we must
ensure that zero-duration tweens at the very beginning or end of the TimelineMax work.
*/
var backwards = this._yoyo && (prevCycle & 1) !== 0,
wrap = backwards === (this._yoyo && (this._cycle & 1) !== 0),
recTotalTime = this._totalTime,
recCycle = this._cycle,
recRawPrevTime = this._rawPrevTime,
recTime = this._time;
this._totalTime = prevCycle * dur;
if (this._cycle < prevCycle) {
backwards = !backwards;
} else {
this._totalTime += dur;
}
this._time = prevTime; //temporarily revert _time so that render() renders the children in the correct order. Without this, tweens won't rewind correctly. We could arhictect things in a "cleaner" way by splitting out the rendering queue into a separate method but for performance reasons, we kept it all inside this method.
this._rawPrevTime = dur === 0 ? prevRawPrevTime - 0.0001 : prevRawPrevTime;
this._cycle = prevCycle;
this._locked = true; //prevents changes to totalTime and skips repeat/yoyo behavior when we recursively call render()
prevTime = backwards ? 0 : dur;
this.render(prevTime, suppressEvents, dur === 0);
if (!suppressEvents) if (!this._gc) {
if (this.vars.onRepeat) {
this._cycle = recCycle; //in case the onRepeat alters the playhead or invalidates(), we shouldn't stay locked or use the previous cycle.
this._locked = false;
this._callback("onRepeat");
}
}
if (prevTime !== this._time) {//in case there's a callback like onComplete in a nested tween/timeline that changes the playhead position, like via seek(), we should just abort.
return;
}
if (wrap) {
this._cycle = prevCycle; //if there's an onRepeat, we reverted this above, so make sure it's set properly again. We also unlocked in that scenario, so reset that too.
this._locked = true;
prevTime = backwards ? dur + 0.0001 : -0.0001;
this.render(prevTime, true, false);
}
this._locked = false;
if (this._paused && !prevPaused) {//if the render() triggered callback that paused this timeline, we should abort (very rare, but possible)
return;
}
this._time = recTime;
this._totalTime = recTotalTime;
this._cycle = recCycle;
this._rawPrevTime = recRawPrevTime;
}
if ((this._time === prevTime || !this._first) && !force && !internalForce && !pauseTween) {
if (prevTotalTime !== this._totalTime) if (this._onUpdate) if (!suppressEvents) {//so that onUpdate fires even during the repeatDelay - as long as the totalTime changed, we should trigger onUpdate.
this._callback("onUpdate");
}
return;
} else if (!this._initted) {
this._initted = true;
}
if (!this._active) if (!this._paused && this._totalTime !== prevTotalTime && time > 0) {
this._active = true; //so that if the user renders the timeline (as opposed to the parent timeline rendering it), it is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the timeline already finished but the user manually re-renders it as halfway done, for example.
}
if (prevTotalTime === 0) if (this.vars.onStart) if (this._totalTime !== 0 || !this._totalDuration) if (!suppressEvents) {
this._callback("onStart");
}
curTime = this._time;
if (curTime >= prevTime) {
tween = this._first;
while (tween) {
next = tween._next; //record it here because the value could change after rendering...
if (curTime !== this._time || this._paused && !prevPaused) {//in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
break;
} else if (tween._active || tween._startTime <= this._time && !tween._paused && !tween._gc) {
if (pauseTween === tween) {
this.pause();
}
if (!tween._reversed) {
tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
} else {
tween.render((!tween._dirty ? tween._totalDuration : tween.totalDuration()) - (time - tween._startTime) * tween._timeScale, suppressEvents, force);
}
}
tween = next;
}
} else {
tween = this._last;
while (tween) {
next = tween._prev; //record it here because the value could change after rendering...
if (curTime !== this._time || this._paused && !prevPaused) {//in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
break;
} else if (tween._active || tween._startTime <= prevTime && !tween._paused && !tween._gc) {
if (pauseTween === tween) {
pauseTween = tween._prev; //the linked list is organized by _startTime, thus it's possible that a tween could start BEFORE the pause and end after it, in which case it would be positioned before the pause tween in the linked list, but we should render it before we pause() the timeline and cease rendering. This is only a concern when going in reverse.
while (pauseTween && pauseTween.endTime() > this._time) {
pauseTween.render(pauseTween._reversed ? pauseTween.totalDuration() - (time - pauseTween._startTime) * pauseTween._timeScale : (time - pauseTween._startTime) * pauseTween._timeScale, suppressEvents, force);
pauseTween = pauseTween._prev;
}
pauseTween = null;
this.pause();
}
if (!tween._reversed) {
tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
} else {
tween.render((!tween._dirty ? tween._totalDuration : tween.totalDuration()) - (time - tween._startTime) * tween._timeScale, suppressEvents, force);
}
}
tween = next;
}
}
if (this._onUpdate) if (!suppressEvents) {
if (_lazyTweens.length) {//in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onUpdate on a timeline that reports/checks tweened values.
_lazyRender();
}
this._callback("onUpdate");
}
if (callback) if (!this._locked) if (!this._gc) if (prevStart === this._startTime || prevTimeScale !== this._timeScale) if (this._time === 0 || totalDur >= this.totalDuration()) {//if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline), it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would complete if it was necessary at the new time. The only exception is the timeScale property. Also check _gc because there's a chance that kill() could be called in an onUpdate
if (isComplete) {
if (_lazyTweens.length) {//in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onComplete on a timeline that reports/checks tweened values.
_lazyRender();
}
if (this._timeline.autoRemoveChildren) {
this._enabled(false, false);
}
this._active = false;
}
if (!suppressEvents && this.vars[callback]) {
this._callback(callback);
}
}
};
p.getActive = function (nested, tweens, timelines) {
if (nested == null) {
nested = true;
}
if (tweens == null) {
tweens = true;
}
if (timelines == null) {
timelines = false;
}
var a = [],
all = this.getChildren(nested, tweens, timelines),
cnt = 0,
l = all.length,
i,tween;
for (i = 0; i < l; i++) {
tween = all[i];
if (tween.isActive()) {
a[cnt++] = tween;
}
}
return a;
};
p.getLabelAfter = function (time) {
if (!time) if (time !== 0) {//faster than isNan()
time = this._time;
}
var labels = this.getLabelsArray(),
l = labels.length,
i;
for (i = 0; i < l; i++) {
if (labels[i].time > time) {
return labels[i].name;
}
}
return null;
};
p.getLabelBefore = function (time) {
if (time == null) {
time = this._time;
}
var labels = this.getLabelsArray(),
i = labels.length;
while (--i > -1) {
if (labels[i].time < time) {
return labels[i].name;
}
}
return null;
};
p.getLabelsArray = function () {
var a = [],
cnt = 0,
p;
for (p in this._labels) {
a[cnt++] = { time: this._labels[p], name: p };
}
a.sort(function (a, b) {
return a.time - b.time;
});
return a;
};
p.invalidate = function () {
this._locked = false; //unlock and set cycle in case invalidate() is called from inside an onRepeat
return TimelineLite.prototype.invalidate.call(this);
};
//---- GETTERS / SETTERS -------------------------------------------------------------------------------------------------------
p.progress = function (value, suppressEvents) {
return !arguments.length ? this._time / this.duration() || 0 : this.totalTime(this.duration() * (this._yoyo && (this._cycle & 1) !== 0 ? 1 - value : value) + this._cycle * (this._duration + this._repeatDelay), suppressEvents);
};
p.totalProgress = function (value, suppressEvents) {
return !arguments.length ? this._totalTime / this.totalDuration() || 0 : this.totalTime(this.totalDuration() * value, suppressEvents);
};
p.totalDuration = function (value) {
if (!arguments.length) {
if (this._dirty) {
TimelineLite.prototype.totalDuration.call(this); //just forces refresh
//Instead of Infinity, we use 999999999999 so that we can accommodate reverses.
this._totalDuration = this._repeat === -1 ? 999999999999 : this._duration * (this._repeat + 1) + this._repeatDelay * this._repeat;
}
return this._totalDuration;
}
return this._repeat === -1 || !value ? this : this.timeScale(this.totalDuration() / value);
};
p.time = function (value, suppressEvents) {
if (!arguments.length) {
return this._time;
}
if (this._dirty) {
this.totalDuration();
}
if (value > this._duration) {
value = this._duration;
}
if (this._yoyo && (this._cycle & 1) !== 0) {
value = this._duration - value + this._cycle * (this._duration + this._repeatDelay);
} else if (this._repeat !== 0) {
value += this._cycle * (this._duration + this._repeatDelay);
}
return this.totalTime(value, suppressEvents);
};
p.repeat = function (value) {
if (!arguments.length) {
return this._repeat;
}
this._repeat = value;
return this._uncache(true);
};
p.repeatDelay = function (value) {
if (!arguments.length) {
return this._repeatDelay;
}
this._repeatDelay = value;
return this._uncache(true);
};
p.yoyo = function (value) {
if (!arguments.length) {
return this._yoyo;
}
this._yoyo = value;
return this;
};
p.currentLabel = function (value) {
if (!arguments.length) {
return this.getLabelBefore(this._time + 0.00000001);
}
return this.seek(value, true);
};
return TimelineMax;
}, true);
/*
* ----------------------------------------------------------------
* TimelineLite
* ----------------------------------------------------------------
*/
_gsScope._gsDefine("TimelineLite", ["core.Animation", "core.SimpleTimeline", "TweenLite"], function (Animation, SimpleTimeline, TweenLite) {
var TimelineLite = function TimelineLite(vars) {
SimpleTimeline.call(this, vars);
this._labels = {};
this.autoRemoveChildren = this.vars.autoRemoveChildren === true;
this.smoothChildTiming = this.vars.smoothChildTiming === true;
this._sortChildren = true;
this._onUpdate = this.vars.onUpdate;
var v = this.vars,
val,p;
for (p in v) {
val = v[p];
if (_isArray(val)) if (val.join("").indexOf("{self}") !== -1) {
v[p] = this._swapSelfInParams(val);
}
}
if (_isArray(v.tweens)) {
this.add(v.tweens, 0, v.align, v.stagger);
}
},
_tinyNum = 0.0000000001,
TweenLiteInternals = TweenLite._internals,
_internals = TimelineLite._internals = {},
_isSelector = TweenLiteInternals.isSelector,
_isArray = TweenLiteInternals.isArray,
_lazyTweens = TweenLiteInternals.lazyTweens,
_lazyRender = TweenLiteInternals.lazyRender,
_globals = _gsScope._gsDefine.globals,
_copy = function _copy(vars) {
var copy = {},p;
for (p in vars) {
copy[p] = vars[p];
}
return copy;
},
_applyCycle = function _applyCycle(vars, targets, i) {
var alt = vars.cycle,
p,val;
for (p in alt) {
val = alt[p];
vars[p] = typeof val === "function" ? val(i, targets[i]) : val[i % val.length];
}
delete vars.cycle;
},
_pauseCallback = _internals.pauseCallback = function () {},
_slice = function _slice(a) {//don't use [].slice because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll()
var b = [],
l = a.length,
i;
for (i = 0; i !== l; b.push(a[i++])) {}
return b;
},
p = TimelineLite.prototype = new SimpleTimeline();
TimelineLite.version = "1.20.4";
p.constructor = TimelineLite;
p.kill()._gc = p._forcingPlayhead = p._hasPause = false;
/* might use later...
//translates a local time inside an animation to the corresponding time on the root/global timeline, factoring in all nesting and timeScales.
function localToGlobal(time, animation) {
while (animation) {
time = (time / animation._timeScale) + animation._startTime;
animation = animation.timeline;
}
return time;
}
//translates the supplied time on the root/global timeline into the corresponding local time inside a particular animation, factoring in all nesting and timeScales
function globalToLocal(time, animation) {
var scale = 1;
time -= localToGlobal(0, animation);
while (animation) {
scale *= animation._timeScale;
animation = animation.timeline;
}
return time * scale;
}
*/
p.to = function (target, duration, vars, position) {
var Engine = vars.repeat && _globals.TweenMax || TweenLite;
return duration ? this.add(new Engine(target, duration, vars), position) : this.set(target, vars, position);
};
p.from = function (target, duration, vars, position) {
return this.add((vars.repeat && _globals.TweenMax || TweenLite).from(target, duration, vars), position);
};
p.fromTo = function (target, duration, fromVars, toVars, position) {
var Engine = toVars.repeat && _globals.TweenMax || TweenLite;
return duration ? this.add(Engine.fromTo(target, duration, fromVars, toVars), position) : this.set(target, toVars, position);
};
p.staggerTo = function (targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
var tl = new TimelineLite({ onComplete: onCompleteAll, onCompleteParams: onCompleteAllParams, callbackScope: onCompleteAllScope, smoothChildTiming: this.smoothChildTiming }),
cycle = vars.cycle,
copy,i;
if (typeof targets === "string") {
targets = TweenLite.selector(targets) || targets;
}
targets = targets || [];
if (_isSelector(targets)) {//senses if the targets object is a selector. If it is, we should translate it into an array.
targets = _slice(targets);
}
stagger = stagger || 0;
if (stagger < 0) {
targets = _slice(targets);
targets.reverse();
stagger *= -1;
}
for (i = 0; i < targets.length; i++) {
copy = _copy(vars);
if (copy.startAt) {
copy.startAt = _copy(copy.startAt);
if (copy.startAt.cycle) {
_applyCycle(copy.startAt, targets, i);
}
}
if (cycle) {
_applyCycle(copy, targets, i);
if (copy.duration != null) {
duration = copy.duration;
delete copy.duration;
}
}
tl.to(targets[i], duration, copy, i * stagger);
}
return this.add(tl, position);
};
p.staggerFrom = function (targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
vars.immediateRender = vars.immediateRender != false;
vars.runBackwards = true;
return this.staggerTo(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope);
};
p.staggerFromTo = function (targets, duration, fromVars, toVars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
toVars.startAt = fromVars;
toVars.immediateRender = toVars.immediateRender != false && fromVars.immediateRender != false;
return this.staggerTo(targets, duration, toVars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope);
};
p.call = function (callback, params, scope, position) {
return this.add(TweenLite.delayedCall(0, callback, params, scope), position);
};
p.set = function (target, vars, position) {
position = this._parseTimeOrLabel(position, 0, true);
if (vars.immediateRender == null) {
vars.immediateRender = position === this._time && !this._paused;
}
return this.add(new TweenLite(target, 0, vars), position);
};
TimelineLite.exportRoot = function (vars, ignoreDelayedCalls) {
vars = vars || {};
if (vars.smoothChildTiming == null) {
vars.smoothChildTiming = true;
}
var tl = new TimelineLite(vars),
root = tl._timeline,
hasNegativeStart,time,tween,next;
if (ignoreDelayedCalls == null) {
ignoreDelayedCalls = true;
}
root._remove(tl, true);
tl._startTime = 0;
tl._rawPrevTime = tl._time = tl._totalTime = root._time;
tween = root._first;
while (tween) {
next = tween._next;
if (!ignoreDelayedCalls || !(tween instanceof TweenLite && tween.target === tween.vars.onComplete)) {
time = tween._startTime - tween._delay;
if (time < 0) {
hasNegativeStart = 1;
}
tl.add(tween, time);
}
tween = next;
}
root.add(tl, 0);
if (hasNegativeStart) {//calling totalDuration() will force the adjustment necessary to shift the children forward so none of them start before zero, and moves the timeline backwards the same amount, so the playhead is still aligned where it should be globally, but the timeline doesn't have illegal children that start before zero.
tl.totalDuration();
}
return tl;
};
p.add = function (value, position, align, stagger) {
var curTime, l, i, child, tl, beforeRawTime;
if (typeof position !== "number") {
position = this._parseTimeOrLabel(position, 0, true, value);
}
if (!(value instanceof Animation)) {
if (value instanceof Array || value && value.push && _isArray(value)) {
align = align || "normal";
stagger = stagger || 0;
curTime = position;
l = value.length;
for (i = 0; i < l; i++) {
if (_isArray(child = value[i])) {
child = new TimelineLite({ tweens: child });
}
this.add(child, curTime);
if (typeof child !== "string" && typeof child !== "function") {
if (align === "sequence") {
curTime = child._startTime + child.totalDuration() / child._timeScale;
} else if (align === "start") {
child._startTime -= child.delay();
}
}
curTime += stagger;
}
return this._uncache(true);
} else if (typeof value === "string") {
return this.addLabel(value, position);
} else if (typeof value === "function") {
value = TweenLite.delayedCall(0, value);
} else {
throw "Cannot add " + value + " into the timeline; it is not a tween, timeline, function, or string.";
}
}
SimpleTimeline.prototype.add.call(this, value, position);
if (value._time) {//in case, for example, the _startTime is moved on a tween that has already rendered. Imagine it's at its end state, then the startTime is moved WAY later (after the end of this timeline), it should render at its beginning.
value.render((this.rawTime() - value._startTime) * value._timeScale, false, false);
}
//if the timeline has already ended but the inserted tween/timeline extends the duration, we should enable this timeline again so that it renders properly. We should also align the playhead with the parent timeline's when appropriate.
if (this._gc || this._time === this._duration) if (!this._paused) if (this._duration < this.duration()) {
//in case any of the ancestors had completed but should now be enabled...
tl = this;
beforeRawTime = tl.rawTime() > value._startTime; //if the tween is placed on the timeline so that it starts BEFORE the current rawTime, we should align the playhead (move the timeline). This is because sometimes users will create a timeline, let it finish, and much later append a tween and expect it to run instead of jumping to its end state. While technically one could argue that it should jump to its end state, that's not what users intuitively expect.
while (tl._timeline) {
if (beforeRawTime && tl._timeline.smoothChildTiming) {
tl.totalTime(tl._totalTime, true); //moves the timeline (shifts its startTime) if necessary, and also enables it.
} else if (tl._gc) {
tl._enabled(true, false);
}
tl = tl._timeline;
}
}
return this;
};
p.remove = function (value) {
if (value instanceof Animation) {
this._remove(value, false);
var tl = value._timeline = value.vars.useFrames ? Animation._rootFramesTimeline : Animation._rootTimeline; //now that it's removed, default it to the root timeline so that if it gets played again, it doesn't jump back into this timeline.
value._startTime = (value._paused ? value._pauseTime : tl._time) - (!value._reversed ? value._totalTime : value.totalDuration() - value._totalTime) / value._timeScale; //ensure that if it gets played again, the timing is correct.
return this;
} else if (value instanceof Array || value && value.push && _isArray(value)) {
var i = value.length;
while (--i > -1) {
this.remove(value[i]);
}
return this;
} else if (typeof value === "string") {
return this.removeLabel(value);
}
return this.kill(null, value);
};
p._remove = function (tween, skipDisable) {
SimpleTimeline.prototype._remove.call(this, tween, skipDisable);
var last = this._last;
if (!last) {
this._time = this._totalTime = this._duration = this._totalDuration = 0;
} else if (this._time > this.duration()) {
this._time = this._duration;
this._totalTime = this._totalDuration;
}
return this;
};
p.append = function (value, offsetOrLabel) {
return this.add(value, this._parseTimeOrLabel(null, offsetOrLabel, true, value));
};
p.insert = p.insertMultiple = function (value, position, align, stagger) {
return this.add(value, position || 0, align, stagger);
};
p.appendMultiple = function (tweens, offsetOrLabel, align, stagger) {
return this.add(tweens, this._parseTimeOrLabel(null, offsetOrLabel, true, tweens), align, stagger);
};
p.addLabel = function (label, position) {
this._labels[label] = this._parseTimeOrLabel(position);
return this;
};
p.addPause = function (position, callback, params, scope) {
var t = TweenLite.delayedCall(0, _pauseCallback, params, scope || this);
t.vars.onComplete = t.vars.onReverseComplete = callback;
t.data = "isPause";
this._hasPause = true;
return this.add(t, position);
};
p.removeLabel = function (label) {
delete this._labels[label];
return this;
};
p.getLabelTime = function (label) {
return this._labels[label] != null ? this._labels[label] : -1;
};
p._parseTimeOrLabel = function (timeOrLabel, offsetOrLabel, appendIfAbsent, ignore) {
var clippedDuration, i;
//if we're about to add a tween/timeline (or an array of them) that's already a child of this timeline, we should remove it first so that it doesn't contaminate the duration().
if (ignore instanceof Animation && ignore.timeline === this) {
this.remove(ignore);
} else if (ignore && (ignore instanceof Array || ignore.push && _isArray(ignore))) {
i = ignore.length;
while (--i > -1) {
if (ignore[i] instanceof Animation && ignore[i].timeline === this) {
this.remove(ignore[i]);
}
}
}
clippedDuration = typeof timeOrLabel === "number" && !offsetOrLabel ? 0 : this.duration() > 99999999999 ? this.recent().endTime(false) : this._duration; //in case there's a child that infinitely repeats, users almost never intend for the insertion point of a new child to be based on a SUPER long value like that so we clip it and assume the most recently-added child's endTime should be used instead.
if (typeof offsetOrLabel === "string") {
return this._parseTimeOrLabel(offsetOrLabel, appendIfAbsent && typeof timeOrLabel === "number" && this._labels[offsetOrLabel] == null ? timeOrLabel - clippedDuration : 0, appendIfAbsent);
}
offsetOrLabel = offsetOrLabel || 0;
if (typeof timeOrLabel === "string" && (isNaN(timeOrLabel) || this._labels[timeOrLabel] != null)) {//if the string is a number like "1", check to see if there's a label with that name, otherwise interpret it as a number (absolute value).
i = timeOrLabel.indexOf("=");
if (i === -1) {
if (this._labels[timeOrLabel] == null) {
return appendIfAbsent ? this._labels[timeOrLabel] = clippedDuration + offsetOrLabel : offsetOrLabel;
}
return this._labels[timeOrLabel] + offsetOrLabel;
}
offsetOrLabel = parseInt(timeOrLabel.charAt(i - 1) + "1", 10) * Number(timeOrLabel.substr(i + 1));
timeOrLabel = i > 1 ? this._parseTimeOrLabel(timeOrLabel.substr(0, i - 1), 0, appendIfAbsent) : clippedDuration;
} else if (timeOrLabel == null) {
timeOrLabel = clippedDuration;
}
return Number(timeOrLabel) + offsetOrLabel;
};
p.seek = function (position, suppressEvents) {
return this.totalTime(typeof position === "number" ? position : this._parseTimeOrLabel(position), suppressEvents !== false);
};
p.stop = function () {
return this.paused(true);
};
p.gotoAndPlay = function (position, suppressEvents) {
return this.play(position, suppressEvents);
};
p.gotoAndStop = function (position, suppressEvents) {
return this.pause(position, suppressEvents);
};
p.render = function (time, suppressEvents, force) {
if (this._gc) {
this._enabled(true, false);
}
var totalDur = !this._dirty ? this._totalDuration : this.totalDuration(),
prevTime = this._time,
prevStart = this._startTime,
prevTimeScale = this._timeScale,
prevPaused = this._paused,
tween,isComplete,next,callback,internalForce,pauseTween,curTime;
if (time >= totalDur - 0.0000001 && time >= 0) {//to work around occasional floating point math artifacts.
this._totalTime = this._time = totalDur;
if (!this._reversed) if (!this._hasPausedChild()) {
isComplete = true;
callback = "onComplete";
internalForce = !!this._timeline.autoRemoveChildren; //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline.
if (this._duration === 0) if (time <= 0 && time >= -0.0000001 || this._rawPrevTime < 0 || this._rawPrevTime === _tinyNum) if (this._rawPrevTime !== time && this._first) {
internalForce = true;
if (this._rawPrevTime > _tinyNum) {
callback = "onReverseComplete";
}
}
}
this._rawPrevTime = this._duration || !suppressEvents || time || this._rawPrevTime === time ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
time = totalDur + 0.0001; //to avoid occasional floating point rounding errors - sometimes child tweens/timelines were not being fully completed (their progress might be 0.999999999999998 instead of 1 because when _time - tween._startTime is performed, floating point errors would return a value that was SLIGHTLY off). Try (999999999999.7 - 999999999999) * 1 = 0.699951171875 instead of 0.7.
} else if (time < 0.0000001) {//to work around occasional floating point math artifacts, round super small values to 0.
this._totalTime = this._time = 0;
if (prevTime !== 0 || this._duration === 0 && this._rawPrevTime !== _tinyNum && (this._rawPrevTime > 0 || time < 0 && this._rawPrevTime >= 0)) {
callback = "onReverseComplete";
isComplete = this._reversed;
}
if (time < 0) {
this._active = false;
if (this._timeline.autoRemoveChildren && this._reversed) {//ensures proper GC if a timeline is resumed after it's finished reversing.
internalForce = isComplete = true;
callback = "onReverseComplete";
} else if (this._rawPrevTime >= 0 && this._first) {//when going back beyond the start, force a render so that zero-duration tweens that sit at the very beginning render their start values properly. Otherwise, if the parent timeline's playhead lands exactly at this timeline's startTime, and then moves backwards, the zero-duration tweens at the beginning would still be at their end state.
internalForce = true;
}
this._rawPrevTime = time;
} else {
this._rawPrevTime = this._duration || !suppressEvents || time || this._rawPrevTime === time ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
if (time === 0 && isComplete) {//if there's a zero-duration tween at the very beginning of a timeline and the playhead lands EXACTLY at time 0, that tween will correctly render its end values, but we need to keep the timeline alive for one more render so that the beginning values render properly as the parent's playhead keeps moving beyond the begining. Imagine obj.x starts at 0 and then we do tl.set(obj, {x:100}).to(obj, 1, {x:200}) and then later we tl.reverse()...the goal is to have obj.x revert to 0. If the playhead happens to land on exactly 0, without this chunk of code, it'd complete the timeline and remove it from the rendering queue (not good).
tween = this._first;
while (tween && tween._startTime === 0) {
if (!tween._duration) {
isComplete = false;
}
tween = tween._next;
}
}
time = 0; //to avoid occasional floating point rounding errors (could cause problems especially with zero-duration tweens at the very beginning of the timeline)
if (!this._initted) {
internalForce = true;
}
}
} else {
if (this._hasPause && !this._forcingPlayhead && !suppressEvents) {
if (time >= prevTime) {
tween = this._first;
while (tween && tween._startTime <= time && !pauseTween) {
if (!tween._duration) if (tween.data === "isPause" && !tween.ratio && !(tween._startTime === 0 && this._rawPrevTime === 0)) {
pauseTween = tween;
}
tween = tween._next;
}
} else {
tween = this._last;
while (tween && tween._startTime >= time && !pauseTween) {
if (!tween._duration) if (tween.data === "isPause" && tween._rawPrevTime > 0) {
pauseTween = tween;
}
tween = tween._prev;
}
}
if (pauseTween) {
this._time = time = pauseTween._startTime;
this._totalTime = time + this._cycle * (this._totalDuration + this._repeatDelay);
}
}
this._totalTime = this._time = this._rawPrevTime = time;
}
if ((this._time === prevTime || !this._first) && !force && !internalForce && !pauseTween) {
return;
} else if (!this._initted) {
this._initted = true;
}
if (!this._active) if (!this._paused && this._time !== prevTime && time > 0) {
this._active = true; //so that if the user renders the timeline (as opposed to the parent timeline rendering it), it is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the timeline already finished but the user manually re-renders it as halfway done, for example.
}
if (prevTime === 0) if (this.vars.onStart) if (this._time !== 0 || !this._duration) if (!suppressEvents) {
this._callback("onStart");
}
curTime = this._time;
if (curTime >= prevTime) {
tween = this._first;
while (tween) {
next = tween._next; //record it here because the value could change after rendering...
if (curTime !== this._time || this._paused && !prevPaused) {//in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
break;
} else if (tween._active || tween._startTime <= curTime && !tween._paused && !tween._gc) {
if (pauseTween === tween) {
this.pause();
}
if (!tween._reversed) {
tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
} else {
tween.render((!tween._dirty ? tween._totalDuration : tween.totalDuration()) - (time - tween._startTime) * tween._timeScale, suppressEvents, force);
}
}
tween = next;
}
} else {
tween = this._last;
while (tween) {
next = tween._prev; //record it here because the value could change after rendering...
if (curTime !== this._time || this._paused && !prevPaused) {//in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
break;
} else if (tween._active || tween._startTime <= prevTime && !tween._paused && !tween._gc) {
if (pauseTween === tween) {
pauseTween = tween._prev; //the linked list is organized by _startTime, thus it's possible that a tween could start BEFORE the pause and end after it, in which case it would be positioned before the pause tween in the linked list, but we should render it before we pause() the timeline and cease rendering. This is only a concern when going in reverse.
while (pauseTween && pauseTween.endTime() > this._time) {
pauseTween.render(pauseTween._reversed ? pauseTween.totalDuration() - (time - pauseTween._startTime) * pauseTween._timeScale : (time - pauseTween._startTime) * pauseTween._timeScale, suppressEvents, force);
pauseTween = pauseTween._prev;
}
pauseTween = null;
this.pause();
}
if (!tween._reversed) {
tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
} else {
tween.render((!tween._dirty ? tween._totalDuration : tween.totalDuration()) - (time - tween._startTime) * tween._timeScale, suppressEvents, force);
}
}
tween = next;
}
}
if (this._onUpdate) if (!suppressEvents) {
if (_lazyTweens.length) {//in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onUpdate on a timeline that reports/checks tweened values.
_lazyRender();
}
this._callback("onUpdate");
}
if (callback) if (!this._gc) if (prevStart === this._startTime || prevTimeScale !== this._timeScale) if (this._time === 0 || totalDur >= this.totalDuration()) {//if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline), it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would complete if it was necessary at the new time. The only exception is the timeScale property. Also check _gc because there's a chance that kill() could be called in an onUpdate
if (isComplete) {
if (_lazyTweens.length) {//in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onComplete on a timeline that reports/checks tweened values.
_lazyRender();
}
if (this._timeline.autoRemoveChildren) {
this._enabled(false, false);
}
this._active = false;
}
if (!suppressEvents && this.vars[callback]) {
this._callback(callback);
}
}
};
p._hasPausedChild = function () {
var tween = this._first;
while (tween) {
if (tween._paused || tween instanceof TimelineLite && tween._hasPausedChild()) {
return true;
}
tween = tween._next;
}
return false;
};
p.getChildren = function (nested, tweens, timelines, ignoreBeforeTime) {
ignoreBeforeTime = ignoreBeforeTime || -9999999999;
var a = [],
tween = this._first,
cnt = 0;
while (tween) {
if (tween._startTime < ignoreBeforeTime) {
//do nothing
} else if (tween instanceof TweenLite) {
if (tweens !== false) {
a[cnt++] = tween;
}
} else {
if (timelines !== false) {
a[cnt++] = tween;
}
if (nested !== false) {
a = a.concat(tween.getChildren(true, tweens, timelines));
cnt = a.length;
}
}
tween = tween._next;
}
return a;
};
p.getTweensOf = function (target, nested) {
var disabled = this._gc,
a = [],
cnt = 0,
tweens,i;
if (disabled) {
this._enabled(true, true); //getTweensOf() filters out disabled tweens, and we have to mark them as _gc = true when the timeline completes in order to allow clean garbage collection, so temporarily re-enable the timeline here.
}
tweens = TweenLite.getTweensOf(target);
i = tweens.length;
while (--i > -1) {
if (tweens[i].timeline === this || nested && this._contains(tweens[i])) {
a[cnt++] = tweens[i];
}
}
if (disabled) {
this._enabled(false, true);
}
return a;
};
p.recent = function () {
return this._recent;
};
p._contains = function (tween) {
var tl = tween.timeline;
while (tl) {
if (tl === this) {
return true;
}
tl = tl.timeline;
}
return false;
};
p.shiftChildren = function (amount, adjustLabels, ignoreBeforeTime) {
ignoreBeforeTime = ignoreBeforeTime || 0;
var tween = this._first,
labels = this._labels,
p;
while (tween) {
if (tween._startTime >= ignoreBeforeTime) {
tween._startTime += amount;
}
tween = tween._next;
}
if (adjustLabels) {
for (p in labels) {
if (labels[p] >= ignoreBeforeTime) {
labels[p] += amount;
}
}
}
return this._uncache(true);
};
p._kill = function (vars, target) {
if (!vars && !target) {
return this._enabled(false, false);
}
var tweens = !target ? this.getChildren(true, true, false) : this.getTweensOf(target),
i = tweens.length,
changed = false;
while (--i > -1) {
if (tweens[i]._kill(vars, target)) {
changed = true;
}
}
return changed;
};
p.clear = function (labels) {
var tweens = this.getChildren(false, true, true),
i = tweens.length;
this._time = this._totalTime = 0;
while (--i > -1) {
tweens[i]._enabled(false, false);
}
if (labels !== false) {
this._labels = {};
}
return this._uncache(true);
};
p.invalidate = function () {
var tween = this._first;
while (tween) {
tween.invalidate();
tween = tween._next;
}
return Animation.prototype.invalidate.call(this);;
};
p._enabled = function (enabled, ignoreTimeline) {
if (enabled === this._gc) {
var tween = this._first;
while (tween) {
tween._enabled(enabled, true);
tween = tween._next;
}
}
return SimpleTimeline.prototype._enabled.call(this, enabled, ignoreTimeline);
};
p.totalTime = function (time, suppressEvents, uncapped) {
this._forcingPlayhead = true;
var val = Animation.prototype.totalTime.apply(this, arguments);
this._forcingPlayhead = false;
return val;
};
p.duration = function (value) {
if (!arguments.length) {
if (this._dirty) {
this.totalDuration(); //just triggers recalculation
}
return this._duration;
}
if (this.duration() !== 0 && value !== 0) {
this.timeScale(this._duration / value);
}
return this;
};
p.totalDuration = function (value) {
if (!arguments.length) {
if (this._dirty) {
var max = 0,
tween = this._last,
prevStart = 999999999999,
prev,end;
while (tween) {
prev = tween._prev; //record it here in case the tween changes position in the sequence...
if (tween._dirty) {
tween.totalDuration(); //could change the tween._startTime, so make sure the tween's cache is clean before analyzing it.
}
if (tween._startTime > prevStart && this._sortChildren && !tween._paused && !this._calculatingDuration) {//in case one of the tweens shifted out of order, it needs to be re-inserted into the correct position in the sequence
this._calculatingDuration = 1; //prevent endless recursive calls - there are methods that get triggered that check duration/totalDuration when we add(), like _parseTimeOrLabel().
this.add(tween, tween._startTime - tween._delay);
this._calculatingDuration = 0;
} else {
prevStart = tween._startTime;
}
if (tween._startTime < 0 && !tween._paused) {//children aren't allowed to have negative startTimes unless smoothChildTiming is true, so adjust here if one is found.
max -= tween._startTime;
if (this._timeline.smoothChildTiming) {
this._startTime += tween._startTime / this._timeScale;
this._time -= tween._startTime;
this._totalTime -= tween._startTime;
this._rawPrevTime -= tween._startTime;
}
this.shiftChildren(-tween._startTime, false, -9999999999);
prevStart = 0;
}
end = tween._startTime + tween._totalDuration / tween._timeScale;
if (end > max) {
max = end;
}
tween = prev;
}
this._duration = this._totalDuration = max;
this._dirty = false;
}
return this._totalDuration;
}
return value && this.totalDuration() ? this.timeScale(this._totalDuration / value) : this;
};
p.paused = function (value) {
if (!value) {//if there's a pause directly at the spot from where we're unpausing, skip it.
var tween = this._first,
time = this._time;
while (tween) {
if (tween._startTime === time && tween.data === "isPause") {
tween._rawPrevTime = 0; //remember, _rawPrevTime is how zero-duration tweens/callbacks sense directionality and determine whether or not to fire. If _rawPrevTime is the same as _startTime on the next render, it won't fire.
}
tween = tween._next;
}
}
return Animation.prototype.paused.apply(this, arguments);
};
p.usesFrames = function () {
var tl = this._timeline;
while (tl._timeline) {
tl = tl._timeline;
}
return tl === Animation._rootFramesTimeline;
};
p.rawTime = function (wrapRepeats) {
return wrapRepeats && (this._paused || this._repeat && this.time() > 0 && this.totalProgress() < 1) ? this._totalTime % (this._duration + this._repeatDelay) : this._paused ? this._totalTime : (this._timeline.rawTime(wrapRepeats) - this._startTime) * this._timeScale;
};
return TimelineLite;
}, true);
});if (_gsScope._gsDefine) {_gsScope._gsQueue.pop()();}
//export to AMD/RequireJS and CommonJS/Node (precursor to full modular build system coming at a later date)
(function (name) {
"use strict";
var getGlobal = function getGlobal() {
return (_gsScope.GreenSockGlobals || _gsScope)[name];
};
if (typeof module !== "undefined" && module.exports) {//node
__webpack_require__(4); //dependency
module.exports = getGlobal();
} else if (true) {//AMD
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(4)], __WEBPACK_AMD_DEFINE_FACTORY__ = (getGlobal),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
})("TimelineMax");
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 21 */
/***/ (function(module, exports) {
// removed by extract-text-webpack-plugin
/***/ })
/******/ ]);
//# sourceMappingURL=main.js.map
|
/*************************************************
* Copyright (c) 2015 Ansible, Inc.
*
* All Rights Reserved
*************************************************/
export default ['$scope', '$filter', 'i18n',
function ($scope, $filter, i18n) {
function isFailureState(status) {
return status === 'failed' || status === 'error' || status === 'canceled';
}
function init(){
var singleJobStatus = true;
var firstJobStatus;
var recentJobs = $scope.jobs;
var detailsBaseUrl;
if(!recentJobs){
return;
}
// unless we explicitly define a value for the template-type attribute when invoking the
// directive, assume the status icons are for a regular (non-workflow) job when building
// the details url path
if (typeof $scope.templateType !== 'undefined' && $scope.templateType === 'workflow_job_template') {
detailsBaseUrl = '/#/workflows/';
} else {
detailsBaseUrl = '/#/jobs/playbook/';
}
var sparkData =
_.sortBy(recentJobs.map(function(job) {
const finished = $filter('longDate')(job.finished) || job.status+"";
const data = {
status: job.status,
jobId: job.id,
sortDate: job.finished || "running" + job.id,
finished: finished,
status_tip: `${i18n._('JOB ID')}: ${job.id} <br>${i18n._('STATUS')}: ${job.status.toUpperCase()} <br>${i18n._('FINISHED')}: ${finished}`,
detailsUrl: detailsBaseUrl + job.id
};
// If we've already determined that there are both failed and successful jobs OR if the current job in the loop is
// pending/waiting/running then we don't worry about checking for a single job status
if(singleJobStatus && (isFailureState(job.status) || job.status === "successful")) {
if(firstJobStatus) {
// We've already been through at least once and have a first job status
if(!(isFailureState(firstJobStatus) && isFailureState(job.status) || firstJobStatus === job.status)) {
// We have a different status in the array
singleJobStatus = false;
}
}
else {
// We haven't set a first job status yet so go ahead set it
firstJobStatus = job.status;
}
}
return data;
}), "sortDate").reverse();
$scope.singleJobStatus = singleJobStatus;
$scope.sparkArray = sparkData;
$scope.placeholders = new Array(10 - sparkData.length);
}
$scope.$watchCollection('jobs', function(){
init();
});
}];
//
//
// JOB_STATUS_CHOICES = [
// ('new', _('New')), # Job has been created, but not started.
// ('pending', _('Pending')), # Job has been queued, but is not yet running.
// ('waiting', _('Waiting')), # Job is waiting on an update/dependency.
// ('running', _('Running')), # Job is currently running.
// ('successful', _('Successful')), # Job completed successfully.
// ('failed', _('Failed')), # Job completed, but with failures.
// ('error', _('Error')), # The job was unable to run.
// ('canceled', _('Canceled')), # The job was canceled before completion.
// final states only*****
// ]
//
|
import React from "react";
import "./Home.css";
import { data1, data2, data3 } from "./Data/Data";
import Product from "./Product";
import Image from "./image/1.jpg";
function Home() {
return (
<div className="home">
<div className="home_container">
<img
alt="home pic"
className="home_image" src={Image}
/>
<div className="home_row">
{data1.map((item) => {
return (
<Product
key={item.id}
id={item.id}
title={item.title}
image={item.image}
price={item.price}
rating={item.rating}
/>
);
})}
</div>
<div className="home_row">
{data2.map((item) => {
return (
<Product
key={item.id}
id={item.id}
title={item.title}
image={item.image}
price={item.price}
rating={item.rating}
/>
);
})}
</div>
<div className="home_row">
{data3.map((item) => {
return (
<Product
key={item.id}
id={item.id}
title={item.title}
image={item.image}
price={item.price}
rating={item.rating}
/>
);
})}
</div>
</div>
</div>
);
}
export default Home;
|
/*!
* Bootstrap-select v1.9.3 (http://silviomoreto.github.io/bootstrap-select)
*
* Copyright 2013-2015 bootstrap-select
* Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE)
*/
!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(a){return b(a)}):"object"==typeof exports?module.exports=b(require("jquery")):b(jQuery)}(this,function(a){!function(a){a.fn.selectpicker.defaults={noneSelectedText:"Niets geselecteerd",noneResultsText:"Geen resultaten gevonden voor {0}",countSelectedText:"{0} van {1} geselecteerd",maxOptionsText:["Limiet bereikt ({n} {var} max)","Groep limiet bereikt ({n} {var} max)",["items","item"]],multipleSeparator:", "}}(a)});
|
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['exports', './GoogleApiComponent', './components/Marker', './components/InfoWindow', './components/HeatMap', './components/Polygon', './components/Polyline', './components/Circle', 'react', 'prop-types', 'react-dom', './lib/String', './lib/cancelablePromise'], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require('./GoogleApiComponent'), require('./components/Marker'), require('./components/InfoWindow'), require('./components/HeatMap'), require('./components/Polygon'), require('./components/Polyline'), require('./components/Circle'), require('react'), require('prop-types'), require('react-dom'), require('./lib/String'), require('./lib/cancelablePromise'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.GoogleApiComponent, global.Marker, global.InfoWindow, global.HeatMap, global.Polygon, global.Polyline, global.Circle, global.react, global.propTypes, global.reactDom, global.String, global.cancelablePromise);
global.index = mod.exports;
}
})(this, function (exports, _GoogleApiComponent, _Marker, _InfoWindow, _HeatMap, _Polygon, _Polyline, _Circle, _react, _propTypes, _reactDom, _String, _cancelablePromise) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Map = exports.Circle = exports.Polyline = exports.Polygon = exports.HeatMap = exports.InfoWindow = exports.Marker = exports.GoogleApiWrapper = undefined;
Object.defineProperty(exports, 'GoogleApiWrapper', {
enumerable: true,
get: function () {
return _GoogleApiComponent.wrapper;
}
});
Object.defineProperty(exports, 'Marker', {
enumerable: true,
get: function () {
return _Marker.Marker;
}
});
Object.defineProperty(exports, 'InfoWindow', {
enumerable: true,
get: function () {
return _InfoWindow.InfoWindow;
}
});
Object.defineProperty(exports, 'HeatMap', {
enumerable: true,
get: function () {
return _HeatMap.HeatMap;
}
});
Object.defineProperty(exports, 'Polygon', {
enumerable: true,
get: function () {
return _Polygon.Polygon;
}
});
Object.defineProperty(exports, 'Polyline', {
enumerable: true,
get: function () {
return _Polyline.Polyline;
}
});
Object.defineProperty(exports, 'Circle', {
enumerable: true,
get: function () {
return _Circle.Circle;
}
});
var _react2 = _interopRequireDefault(_react);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _classCallCheck(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;
};
}();
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 mapStyles = {
container: {
position: 'absolute',
width: '100%',
height: '100%'
},
map: {
position: 'absolute',
left: 0,
right: 0,
bottom: 0,
top: 0
}
};
var evtNames = ['ready', 'click', 'dragend', 'recenter', 'bounds_changed', 'center_changed', 'dblclick', 'dragstart', 'heading_change', 'idle', 'maptypeid_changed', 'mousemove', 'mouseout', 'mouseover', 'projection_changed', 'resize', 'rightclick', 'tilesloaded', 'tilt_changed', 'zoom_changed'];
var Map = exports.Map = function (_React$Component) {
_inherits(Map, _React$Component);
function Map(props) {
_classCallCheck(this, Map);
var _this = _possibleConstructorReturn(this, (Map.__proto__ || Object.getPrototypeOf(Map)).call(this, props));
if (!props.hasOwnProperty('google')) {
throw new Error('You must include a `google` prop');
}
_this.listeners = {};
_this.state = {
currentLocation: {
lat: _this.props.initialCenter.lat,
lng: _this.props.initialCenter.lng
}
};
return _this;
}
_createClass(Map, [{
key: 'componentDidMount',
value: function componentDidMount() {
var _this2 = this;
if (this.props.centerAroundCurrentLocation) {
if (navigator && navigator.geolocation) {
this.geoPromise = (0, _cancelablePromise.makeCancelable)(new Promise(function (resolve, reject) {
navigator.geolocation.getCurrentPosition(resolve, reject);
}));
this.geoPromise.promise.then(function (pos) {
var coords = pos.coords;
_this2.setState({
currentLocation: {
lat: coords.latitude,
lng: coords.longitude
}
});
}).catch(function (e) {
return e;
});
}
}
this.loadMap();
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(prevProps, prevState) {
if (prevProps.google !== this.props.google) {
this.loadMap();
}
if (this.props.visible !== prevProps.visible) {
this.restyleMap();
}
if (this.props.zoom !== prevProps.zoom) {
this.map.setZoom(this.props.zoom);
}
if (this.props.center !== prevProps.center) {
this.setState({
currentLocation: this.props.center
});
}
if (prevState.currentLocation !== this.state.currentLocation) {
this.recenterMap();
}
if (this.props.bounds && this.props.bounds !== prevProps.bounds) {
this.map.fitBounds(this.props.bounds);
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
var _this3 = this;
var google = this.props.google;
if (this.geoPromise) {
this.geoPromise.cancel();
}
Object.keys(this.listeners).forEach(function (e) {
google.maps.event.removeListener(_this3.listeners[e]);
});
}
}, {
key: 'loadMap',
value: function loadMap() {
var _this4 = this;
if (this.props && this.props.google) {
var google = this.props.google;
var maps = google.maps;
var mapRef = this.refs.map;
var node = _reactDom2.default.findDOMNode(mapRef);
var curr = this.state.currentLocation;
var center = new maps.LatLng(curr.lat, curr.lng);
var mapTypeIds = this.props.google.maps.MapTypeId || {};
var mapTypeFromProps = String(this.props.mapType).toUpperCase();
var mapConfig = Object.assign({}, {
mapTypeId: mapTypeIds[mapTypeFromProps],
center: center,
zoom: this.props.zoom,
maxZoom: this.props.maxZoom,
minZoom: this.props.minZoom,
clickableIcons: !!this.props.clickableIcons,
disableDefaultUI: this.props.disableDefaultUI,
zoomControl: this.props.zoomControl,
zoomControlOptions: this.props.zoomControlOptions,
mapTypeControl: this.props.mapTypeControl,
scaleControl: this.props.scaleControl,
streetViewControl: this.props.streetViewControl,
panControl: this.props.panControl,
rotateControl: this.props.rotateControl,
fullscreenControl: this.props.fullscreenControl,
scrollwheel: this.props.scrollwheel,
draggable: this.props.draggable,
draggableCursor: this.props.draggableCursor,
keyboardShortcuts: this.props.keyboardShortcuts,
disableDoubleClickZoom: this.props.disableDoubleClickZoom,
noClear: this.props.noClear,
styles: this.props.styles,
gestureHandling: this.props.gestureHandling
});
Object.keys(mapConfig).forEach(function (key) {
// Allow to configure mapConfig with 'false'
if (mapConfig[key] === null) {
delete mapConfig[key];
}
});
this.map = new maps.Map(node, mapConfig);
evtNames.forEach(function (e) {
_this4.listeners[e] = _this4.map.addListener(e, _this4.handleEvent(e));
});
maps.event.trigger(this.map, 'ready');
this.forceUpdate();
}
}
}, {
key: 'handleEvent',
value: function handleEvent(evtName) {
var _this5 = this;
var timeout = void 0;
var handlerName = 'on' + (0, _String.camelize)(evtName);
return function (e) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
timeout = setTimeout(function () {
if (_this5.props[handlerName]) {
_this5.props[handlerName](_this5.props, _this5.map, e);
}
}, 0);
};
}
}, {
key: 'recenterMap',
value: function recenterMap() {
var map = this.map;
var google = this.props.google;
if (!google) return;
var maps = google.maps;
if (map) {
var center = this.state.currentLocation;
if (!(center instanceof google.maps.LatLng)) {
center = new google.maps.LatLng(center.lat, center.lng);
}
// map.panTo(center)
map.setCenter(center);
maps.event.trigger(map, 'recenter');
}
}
}, {
key: 'restyleMap',
value: function restyleMap() {
if (this.map) {
var google = this.props.google;
google.maps.event.trigger(this.map, 'resize');
}
}
}, {
key: 'renderChildren',
value: function renderChildren() {
var _this6 = this;
var children = this.props.children;
if (!children) return;
return _react2.default.Children.map(children, function (c) {
if (!c) return;
return _react2.default.cloneElement(c, {
map: _this6.map,
google: _this6.props.google,
mapCenter: _this6.state.currentLocation
});
});
}
}, {
key: 'render',
value: function render() {
var style = Object.assign({}, mapStyles.map, this.props.style, {
display: this.props.visible ? 'inherit' : 'none'
});
var containerStyles = Object.assign({}, mapStyles.container, this.props.containerStyle);
return _react2.default.createElement(
'div',
{ style: containerStyles, className: this.props.className },
_react2.default.createElement(
'div',
{ style: style, ref: 'map' },
'Loading map...'
),
this.renderChildren()
);
}
}]);
return Map;
}(_react2.default.Component);
Map.propTypes = {
google: _propTypes2.default.object,
zoom: _propTypes2.default.number,
centerAroundCurrentLocation: _propTypes2.default.bool,
center: _propTypes2.default.object,
initialCenter: _propTypes2.default.object,
className: _propTypes2.default.string,
style: _propTypes2.default.object,
containerStyle: _propTypes2.default.object,
visible: _propTypes2.default.bool,
mapType: _propTypes2.default.string,
maxZoom: _propTypes2.default.number,
minZoom: _propTypes2.default.number,
clickableIcons: _propTypes2.default.bool,
disableDefaultUI: _propTypes2.default.bool,
zoomControl: _propTypes2.default.bool,
mapTypeControl: _propTypes2.default.bool,
scaleControl: _propTypes2.default.bool,
streetViewControl: _propTypes2.default.bool,
panControl: _propTypes2.default.bool,
rotateControl: _propTypes2.default.bool,
fullscreenControl: _propTypes2.default.bool,
scrollwheel: _propTypes2.default.bool,
draggable: _propTypes2.default.bool,
draggableCursor: _propTypes2.default.string,
keyboardShortcuts: _propTypes2.default.bool,
disableDoubleClickZoom: _propTypes2.default.bool,
noClear: _propTypes2.default.bool,
styles: _propTypes2.default.array,
gestureHandling: _propTypes2.default.string,
bounds: _propTypes2.default.object
};
evtNames.forEach(function (e) {
return Map.propTypes[(0, _String.camelize)(e)] = _propTypes2.default.func;
});
Map.defaultProps = {
zoom: 14,
initialCenter: {
lat: 37.774929,
lng: -122.419416
},
center: {},
centerAroundCurrentLocation: false,
style: {},
containerStyle: {},
visible: true
};
exports.default = Map;
});
|
var React = require('react');
var SavedArticle = require('./saved-article');
var Saved = React.createClass({
handleNewArticleDelete: function(articleId) {
this.props.onArticleDelete(articleId);
},
handleNewCommentInput: function(object) {
this.props.onCommentInput(object);
},
handleNewCommentSubmit: function(articleId) {
this.props.onCommentSubmit(articleId);
},
handleNewCommentDelete: function(articleId, commentId) {
this.props.onCommentDelete(articleId, commentId);
},
render: function() {
return (
<div className="panel panel-primary">
<div className="panel-heading">
<h3 className="panel-title">
<strong>
<i className="fa fa-file-text-o"></i> Saved Articles
</strong>
</h3>
</div>
<div className="panel-body" id="savedSection">
{ this.props.savedArticles.map(function(article) {
return <SavedArticle article={ article }
key={ article._id }
newComment={ this.props.newComment }
onNewArticleDelete={ function(articleId) {
this.handleNewArticleDelete(articleId)
}.bind(this) }
onNewCommentInput={ function(object) {
this.handleNewCommentInput(object)
}.bind(this) }
onNewCommentSubmit={ function(articleId) {
this.handleNewCommentSubmit(articleId)
}.bind(this) }
onNewCommentDelete={ function(articleId, commentId) {
this.handleNewCommentDelete(articleId, commentId)
}.bind(this) } />
}.bind(this)) }
</div>
</div>
)
}
});
module.exports = Saved;
|
//Creating aliases for Cornerstone tools buttons
export function initCornerstoneToolsAliases() {
cy.get('[data-cy="stack scroll"]').as('stackScrollBtn');
cy.get('[data-cy="zoom"]').as('zoomBtn');
cy.get('[data-cy="levels"]').as('levelsBtn');
cy.get('[data-cy="pan"]').as('panBtn');
cy.get('[data-cy="length"]').as('lengthBtn');
cy.get('[data-cy="annotate"]').as('annotateBtn');
cy.get('[data-cy="angle"]').as('angleBtn');
cy.get('[data-cy="reset"]').as('resetBtn');
cy.get('[data-cy="cine"]').as('cineBtn');
cy.get('[data-cy="more"]').as('moreBtn');
cy.get('[data-cy="layout"]').as('layoutBtn');
cy.get('.viewport-element').as('viewport');
}
//Creating aliases for Common page elements
export function initCommonElementsAliases() {
cy.get(
'.pull-right > .RoundedButtonGroup > .roundedButtonWrapper > .roundedButton'
).as('measurementsBtn');
cy.get('.viewport-element').as('viewport');
cy.get('section.sidepanel.from-right').as('measurementsPanel');
cy.get(
'.pull-left > .RoundedButtonGroup > .roundedButtonWrapper > .roundedButton'
).as('seriesBtn');
cy.get('section.sidepanel.from-left').as('seriesPanel');
cy.get('div.ViewportOverlay > div.bottom-left.overlay-element > div').as(
'viewportInfoBottomLeft'
);
cy.get('div.ViewportOverlay > div.bottom-right.overlay-element > div').as(
'viewportInfoBottomRight'
);
cy.get('.left-mid.orientation-marker').as('viewportInfoMidLeft');
cy.get('.top-mid.orientation-marker').as('viewportInfoMidTop');
}
//Creating aliases for Routes
export function initRouteAliases() {
cy.server();
cy.route('GET', '**/series**').as('getStudySeries');
cy.route('GET', '**/studies**').as('getStudies');
}
//Creating aliases for VTK tools buttons
export function initVTKToolsAliases() {
cy.get('[data-cy="exit 2d mpr"]').as('exit2dmprBtn');
cy.get('[data-cy="crosshairs"]').as('crosshairsBtn');
cy.get('[data-cy="wwwc"]').as('wwwcBtn');
cy.get('[data-cy="rotate"]').as('rotateBtn');
cy.get('.slab-thickness').as('slabSlider');
cy.get('.select-ohif').as('modeDropdown');
cy.get('.ohif-check-label').as('modeCheckbox');
cy.get('[data-cy="layout"]').as('layoutBtn');
}
//Creating aliases for Study List page elements on Desktop experience
export function initStudyListAliasesOnDesktop() {
cy.get('.study-count').as('studyCount');
cy.get('#filter-PatientName').as('PatientName');
cy.get('#filter-PatientID').as('MRN');
cy.get('#filter-AccessionNumber').as('AccessionNumber');
cy.get('#start-date').as('studyListStartDate');
cy.get('#end-date').as('studyListEndDate');
cy.get('#filter-modalities').as('modalities');
cy.get('#filter-StudyDescription').as('StudyDescription');
cy.get('[data-cy="study-list-results"] > tr').as('searchResult');
}
//Creating aliases for Study List page elements on Tablet experience
export function initStudyListAliasesOnTablet() {
cy.get('.study-count').as('studyCount');
cy.get('#filter-patientNameOrId').as('patientNameOrMRN');
cy.get('#filter-accessionOrModalityOrDescription').as(
'accessionModalityDescription'
);
cy.get('#start-date').as('studyListStartDate');
cy.get('#end-date').as('studyListEndDate');
cy.get('[data-cy="study-list-results"] > tr').as('searchResult');
}
//Creating aliases for User Preferences modal
export function initPreferencesModalAliases() {
cy.get('.OHIFModal').as('preferencesModal');
cy.get('[data-cy="hotkeys"]').as('userPreferencesHotkeysTab');
cy.get('[data-cy="general"]').as('userPreferencesGeneralTab');
initPreferencesModalFooterBtnAliases();
}
//Creating aliases for User Preferences modal
export function initPreferencesModalFooterBtnAliases() {
cy.get('.active [data-cy="reset-default-btn"]').as('restoreBtn');
cy.get('.active [data-cy="cancel-btn"]').as('cancelBtn');
cy.get('.active [data-cy="save-btn"]').as('saveBtn');
}
|
const request = require('supertest');
const server = require('../server.js');
it('should response with 404 Not Found when when the request is not supported by any route', (done) => {
request(server)
.get(`/${Math.random().toString(16).substring(7)}`)
.then((response) => {
expect(response.statusCode).toBe(404);
expect(response.body.message).toBeDefined();
done();
});
});
|
/*!
* inputmask.js
* https://github.com/RobinHerbots/Inputmask
* Copyright (c) 2010 - 2019 Robin Herbots
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* Version: 4.0.9
*/
(function (factory) {
if (typeof define === "function" && define.amd) {
define(["./dependencyLibs/inputmask.dependencyLib", "./global/window"], factory);
} else if (typeof exports === "object") {
module.exports = factory(require("./dependencyLibs/inputmask.dependencyLib"), require("./global/window"));
} else {
window.Inputmask = factory(window.dependencyLib || jQuery, window);
}
})(function ($, window, undefined) {
var document = window.document, ua = navigator.userAgent,
ie = ua.indexOf("MSIE ") > 0 || ua.indexOf("Trident/") > 0, mobile = isInputEventSupported("touchstart"),
iemobile = /iemobile/i.test(ua), iphone = /iphone/i.test(ua) && !iemobile;
function Inputmask(alias, options, internal) {
if (!(this instanceof Inputmask)) {
return new Inputmask(alias, options, internal);
}
this.el = undefined;
this.events = {};
this.maskset = undefined;
this.refreshValue = false;
if (internal !== true) {
if ($.isPlainObject(alias)) {
options = alias;
} else {
options = options || {};
if (alias) options.alias = alias;
}
this.opts = $.extend(true, {}, this.defaults, options);
this.noMasksCache = options && options.definitions !== undefined;
this.userOptions = options || {};
this.isRTL = this.opts.numericInput;
resolveAlias(this.opts.alias, options, this.opts);
}
}
Inputmask.prototype = {
dataAttribute: "data-inputmask",
defaults: {
placeholder: "_",
optionalmarker: ["[", "]"],
quantifiermarker: ["{", "}"],
groupmarker: ["(", ")"],
alternatormarker: "|",
escapeChar: "\\",
mask: null,
regex: null,
oncomplete: $.noop,
onincomplete: $.noop,
oncleared: $.noop,
repeat: 0,
greedy: false,
autoUnmask: false,
removeMaskOnSubmit: false,
clearMaskOnLostFocus: true,
insertMode: true,
clearIncomplete: false,
alias: null,
onKeyDown: $.noop,
onBeforeMask: null,
onBeforePaste: function (pastedValue, opts) {
return $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(this, pastedValue, opts) : pastedValue;
},
onBeforeWrite: null,
onUnMask: null,
showMaskOnFocus: true,
showMaskOnHover: true,
onKeyValidation: $.noop,
skipOptionalPartCharacter: " ",
numericInput: false,
rightAlign: false,
undoOnEscape: true,
radixPoint: "",
_radixDance: false,
groupSeparator: "",
keepStatic: null,
positionCaretOnTab: true,
tabThrough: false,
supportsInputType: ["text", "tel", "url", "password", "search"],
ignorables: [8, 9, 13, 19, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 93, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 0, 229],
isComplete: null,
preValidation: null,
postValidation: null,
staticDefinitionSymbol: undefined,
jitMasking: false,
nullable: true,
inputEventOnly: false,
noValuePatching: false,
positionCaretOnClick: "lvp",
casing: null,
inputmode: "verbatim",
colorMask: false,
disablePredictiveText: false,
importDataAttributes: true,
shiftPositions: true
},
definitions: {
9: {
validator: "[0-9\uff11-\uff19]",
definitionSymbol: "*"
},
a: {
validator: "[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",
definitionSymbol: "*"
},
"*": {
validator: "[0-9\uff11-\uff19A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]"
}
},
aliases: {},
masksCache: {},
mask: function (elems) {
var that = this;
function importAttributeOptions(npt, opts, userOptions, dataAttribute) {
if (opts.importDataAttributes === true) {
var attrOptions = npt.getAttribute(dataAttribute), option, dataoptions, optionData, p;
var importOption = function (option, optionData) {
optionData = optionData !== undefined ? optionData : npt.getAttribute(dataAttribute + "-" + option);
if (optionData !== null) {
if (typeof optionData === "string") {
if (option.indexOf("on") === 0) optionData = window[optionData]; else if (optionData === "false") optionData = false; else if (optionData === "true") optionData = true;
}
userOptions[option] = optionData;
}
};
if (attrOptions && attrOptions !== "") {
attrOptions = attrOptions.replace(/'/g, '"');
dataoptions = JSON.parse("{" + attrOptions + "}");
}
if (dataoptions) {
optionData = undefined;
for (p in dataoptions) {
if (p.toLowerCase() === "alias") {
optionData = dataoptions[p];
break;
}
}
}
importOption("alias", optionData);
if (userOptions.alias) {
resolveAlias(userOptions.alias, userOptions, opts);
}
for (option in opts) {
if (dataoptions) {
optionData = undefined;
for (p in dataoptions) {
if (p.toLowerCase() === option.toLowerCase()) {
optionData = dataoptions[p];
break;
}
}
}
importOption(option, optionData);
}
}
$.extend(true, opts, userOptions);
if (npt.dir === "rtl" || opts.rightAlign) {
npt.style.textAlign = "right";
}
if (npt.dir === "rtl" || opts.numericInput) {
npt.dir = "ltr";
npt.removeAttribute("dir");
opts.isRTL = true;
}
return Object.keys(userOptions).length;
}
if (typeof elems === "string") {
elems = document.getElementById(elems) || document.querySelectorAll(elems);
}
elems = elems.nodeName ? [elems] : elems;
$.each(elems, function (ndx, el) {
var scopedOpts = $.extend(true, {}, that.opts);
if (importAttributeOptions(el, scopedOpts, $.extend(true, {}, that.userOptions), that.dataAttribute)) {
var maskset = generateMaskSet(scopedOpts, that.noMasksCache);
if (maskset !== undefined) {
if (el.inputmask !== undefined) {
el.inputmask.opts.autoUnmask = true;
el.inputmask.remove();
}
el.inputmask = new Inputmask(undefined, undefined, true);
el.inputmask.opts = scopedOpts;
el.inputmask.noMasksCache = that.noMasksCache;
el.inputmask.userOptions = $.extend(true, {}, that.userOptions);
el.inputmask.isRTL = scopedOpts.isRTL || scopedOpts.numericInput;
el.inputmask.el = el;
el.inputmask.maskset = maskset;
$.data(el, "_inputmask_opts", scopedOpts);
maskScope.call(el.inputmask, {
action: "mask"
});
}
}
});
return elems && elems[0] ? elems[0].inputmask || this : this;
},
option: function (options, noremask) {
if (typeof options === "string") {
return this.opts[options];
} else if (typeof options === "object") {
$.extend(this.userOptions, options);
if (this.el && noremask !== true) {
this.mask(this.el);
}
return this;
}
},
unmaskedvalue: function (value) {
this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
return maskScope.call(this, {
action: "unmaskedvalue",
value: value
});
},
remove: function () {
return maskScope.call(this, {
action: "remove"
});
},
getemptymask: function () {
this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
return maskScope.call(this, {
action: "getemptymask"
});
},
hasMaskedValue: function () {
return !this.opts.autoUnmask;
},
isComplete: function () {
this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
return maskScope.call(this, {
action: "isComplete"
});
},
getmetadata: function () {
this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
return maskScope.call(this, {
action: "getmetadata"
});
},
isValid: function (value) {
this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
return maskScope.call(this, {
action: "isValid",
value: value
});
},
format: function (value, metadata) {
this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
return maskScope.call(this, {
action: "format",
value: value,
metadata: metadata
});
},
setValue: function (value) {
if (this.el) {
$(this.el).trigger("setvalue", [value]);
}
},
analyseMask: function (mask, regexMask, opts) {
var tokenizer = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?(?:\|[0-9\+\*]*)?\})|[^.?*+^${[]()|\\]+|./g,
regexTokenizer = /\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g,
escaped = false, currentToken = new MaskToken(), match, m, openenings = [], maskTokens = [],
openingToken, currentOpeningToken, alternator, lastMatch, groupToken;
function MaskToken(isGroup, isOptional, isQuantifier, isAlternator) {
this.matches = [];
this.openGroup = isGroup || false;
this.alternatorGroup = false;
this.isGroup = isGroup || false;
this.isOptional = isOptional || false;
this.isQuantifier = isQuantifier || false;
this.isAlternator = isAlternator || false;
this.quantifier = {
min: 1,
max: 1
};
}
function insertTestDefinition(mtoken, element, position) {
position = position !== undefined ? position : mtoken.matches.length;
var prevMatch = mtoken.matches[position - 1];
if (regexMask) {
if (element.indexOf("[") === 0 || escaped && /\\d|\\s|\\w]/i.test(element) || element === ".") {
mtoken.matches.splice(position++, 0, {
fn: new RegExp(element, opts.casing ? "i" : ""),
optionality: false,
newBlockMarker: prevMatch === undefined ? "master" : prevMatch.def !== element,
casing: null,
def: element,
placeholder: undefined,
nativeDef: element
});
} else {
if (escaped) element = element[element.length - 1];
$.each(element.split(""), function (ndx, lmnt) {
prevMatch = mtoken.matches[position - 1];
mtoken.matches.splice(position++, 0, {
fn: null,
optionality: false,
newBlockMarker: prevMatch === undefined ? "master" : prevMatch.def !== lmnt && prevMatch.fn !== null,
casing: null,
def: opts.staticDefinitionSymbol || lmnt,
placeholder: opts.staticDefinitionSymbol !== undefined ? lmnt : undefined,
nativeDef: (escaped ? "'" : "") + lmnt
});
});
}
escaped = false;
} else {
var maskdef = (opts.definitions ? opts.definitions[element] : undefined) || Inputmask.prototype.definitions[element];
if (maskdef && !escaped) {
mtoken.matches.splice(position++, 0, {
fn: maskdef.validator ? typeof maskdef.validator == "string" ? new RegExp(maskdef.validator, opts.casing ? "i" : "") : new function () {
this.test = maskdef.validator;
}() : new RegExp("."),
optionality: false,
newBlockMarker: prevMatch === undefined ? "master" : prevMatch.def !== (maskdef.definitionSymbol || element),
casing: maskdef.casing,
def: maskdef.definitionSymbol || element,
placeholder: maskdef.placeholder,
nativeDef: element
});
} else {
mtoken.matches.splice(position++, 0, {
fn: null,
optionality: false,
newBlockMarker: prevMatch === undefined ? "master" : prevMatch.def !== element && prevMatch.fn !== null,
casing: null,
def: opts.staticDefinitionSymbol || element,
placeholder: opts.staticDefinitionSymbol !== undefined ? element : undefined,
nativeDef: (escaped ? "'" : "") + element
});
escaped = false;
}
}
}
function verifyGroupMarker(maskToken) {
if (maskToken && maskToken.matches) {
$.each(maskToken.matches, function (ndx, token) {
var nextToken = maskToken.matches[ndx + 1];
if ((nextToken === undefined || (nextToken.matches === undefined || nextToken.isQuantifier === false)) && token && token.isGroup) {
token.isGroup = false;
if (!regexMask) {
insertTestDefinition(token, opts.groupmarker[0], 0);
if (token.openGroup !== true) {
insertTestDefinition(token, opts.groupmarker[1]);
}
}
}
verifyGroupMarker(token);
});
}
}
function defaultCase() {
if (openenings.length > 0) {
currentOpeningToken = openenings[openenings.length - 1];
insertTestDefinition(currentOpeningToken, m);
if (currentOpeningToken.isAlternator) {
alternator = openenings.pop();
for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
if (alternator.matches[mndx].isGroup) alternator.matches[mndx].isGroup = false;
}
if (openenings.length > 0) {
currentOpeningToken = openenings[openenings.length - 1];
currentOpeningToken.matches.push(alternator);
} else {
currentToken.matches.push(alternator);
}
}
} else {
insertTestDefinition(currentToken, m);
}
}
function reverseTokens(maskToken) {
function reverseStatic(st) {
if (st === opts.optionalmarker[0]) st = opts.optionalmarker[1]; else if (st === opts.optionalmarker[1]) st = opts.optionalmarker[0]; else if (st === opts.groupmarker[0]) st = opts.groupmarker[1]; else if (st === opts.groupmarker[1]) st = opts.groupmarker[0];
return st;
}
maskToken.matches = maskToken.matches.reverse();
for (var match in maskToken.matches) {
if (maskToken.matches.hasOwnProperty(match)) {
var intMatch = parseInt(match);
if (maskToken.matches[match].isQuantifier && maskToken.matches[intMatch + 1] && maskToken.matches[intMatch + 1].isGroup) {
var qt = maskToken.matches[match];
maskToken.matches.splice(match, 1);
maskToken.matches.splice(intMatch + 1, 0, qt);
}
if (maskToken.matches[match].matches !== undefined) {
maskToken.matches[match] = reverseTokens(maskToken.matches[match]);
} else {
maskToken.matches[match] = reverseStatic(maskToken.matches[match]);
}
}
}
return maskToken;
}
function groupify(matches) {
var groupToken = new MaskToken(true);
groupToken.openGroup = false;
groupToken.matches = matches;
return groupToken;
}
if (regexMask) {
opts.optionalmarker[0] = undefined;
opts.optionalmarker[1] = undefined;
}
while (match = regexMask ? regexTokenizer.exec(mask) : tokenizer.exec(mask)) {
m = match[0];
if (regexMask) {
switch (m.charAt(0)) {
case "?":
m = "{0,1}";
break;
case "+":
case "*":
m = "{" + m + "}";
break;
}
}
if (escaped) {
defaultCase();
continue;
}
switch (m.charAt(0)) {
case "(?=":
break;
case "(?!":
break;
case "(?<=":
break;
case "(?<!":
break;
case opts.escapeChar:
escaped = true;
if (regexMask) {
defaultCase();
}
break;
case opts.optionalmarker[1]:
case opts.groupmarker[1]:
openingToken = openenings.pop();
openingToken.openGroup = false;
if (openingToken !== undefined) {
if (openenings.length > 0) {
currentOpeningToken = openenings[openenings.length - 1];
currentOpeningToken.matches.push(openingToken);
if (currentOpeningToken.isAlternator) {
alternator = openenings.pop();
for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
alternator.matches[mndx].isGroup = false;
alternator.matches[mndx].alternatorGroup = false;
}
if (openenings.length > 0) {
currentOpeningToken = openenings[openenings.length - 1];
currentOpeningToken.matches.push(alternator);
} else {
currentToken.matches.push(alternator);
}
}
} else {
currentToken.matches.push(openingToken);
}
} else defaultCase();
break;
case opts.optionalmarker[0]:
openenings.push(new MaskToken(false, true));
break;
case opts.groupmarker[0]:
openenings.push(new MaskToken(true));
break;
case opts.quantifiermarker[0]:
var quantifier = new MaskToken(false, false, true);
m = m.replace(/[{}]/g, "");
var mqj = m.split("|"), mq = mqj[0].split(","), mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]),
mq1 = mq.length === 1 ? mq0 : isNaN(mq[1]) ? mq[1] : parseInt(mq[1]);
if (mq0 === "*" || mq0 === "+") {
mq0 = mq1 === "*" ? 0 : 1;
}
quantifier.quantifier = {
min: mq0,
max: mq1,
jit: mqj[1]
};
var matches = openenings.length > 0 ? openenings[openenings.length - 1].matches : currentToken.matches;
match = matches.pop();
if (match.isAlternator) {
matches.push(match);
matches = match.matches;
var groupToken = new MaskToken(true);
var tmpMatch = matches.pop();
matches.push(groupToken);
matches = groupToken.matches;
match = tmpMatch;
}
if (!match.isGroup) {
match = groupify([match]);
}
matches.push(match);
matches.push(quantifier);
break;
case opts.alternatormarker:
var groupQuantifier = function (matches) {
var lastMatch = matches.pop();
if (lastMatch.isQuantifier) {
lastMatch = groupify([matches.pop(), lastMatch]);
}
return lastMatch;
};
if (openenings.length > 0) {
currentOpeningToken = openenings[openenings.length - 1];
var subToken = currentOpeningToken.matches[currentOpeningToken.matches.length - 1];
if (currentOpeningToken.openGroup && (subToken.matches === undefined || subToken.isGroup === false && subToken.isAlternator === false)) {
lastMatch = openenings.pop();
} else {
lastMatch = groupQuantifier(currentOpeningToken.matches);
}
} else {
lastMatch = groupQuantifier(currentToken.matches);
}
if (lastMatch.isAlternator) {
openenings.push(lastMatch);
} else {
if (lastMatch.alternatorGroup) {
alternator = openenings.pop();
lastMatch.alternatorGroup = false;
} else {
alternator = new MaskToken(false, false, false, true);
}
alternator.matches.push(lastMatch);
openenings.push(alternator);
if (lastMatch.openGroup) {
lastMatch.openGroup = false;
var alternatorGroup = new MaskToken(true);
alternatorGroup.alternatorGroup = true;
openenings.push(alternatorGroup);
}
}
break;
default:
defaultCase();
}
}
while (openenings.length > 0) {
openingToken = openenings.pop();
currentToken.matches.push(openingToken);
}
if (currentToken.matches.length > 0) {
verifyGroupMarker(currentToken);
maskTokens.push(currentToken);
}
if (opts.numericInput || opts.isRTL) {
reverseTokens(maskTokens[0]);
}
return maskTokens;
},
positionColorMask: function (input, template) {
input.style.left = template.offsetLeft + "px";
}
};
Inputmask.extendDefaults = function (options) {
$.extend(true, Inputmask.prototype.defaults, options);
};
Inputmask.extendDefinitions = function (definition) {
$.extend(true, Inputmask.prototype.definitions, definition);
};
Inputmask.extendAliases = function (alias) {
$.extend(true, Inputmask.prototype.aliases, alias);
};
Inputmask.format = function (value, options, metadata) {
return Inputmask(options).format(value, metadata);
};
Inputmask.unmask = function (value, options) {
return Inputmask(options).unmaskedvalue(value);
};
Inputmask.isValid = function (value, options) {
return Inputmask(options).isValid(value);
};
Inputmask.remove = function (elems) {
if (typeof elems === "string") {
elems = document.getElementById(elems) || document.querySelectorAll(elems);
}
elems = elems.nodeName ? [elems] : elems;
$.each(elems, function (ndx, el) {
if (el.inputmask) el.inputmask.remove();
});
};
Inputmask.setValue = function (elems, value) {
if (typeof elems === "string") {
elems = document.getElementById(elems) || document.querySelectorAll(elems);
}
elems = elems.nodeName ? [elems] : elems;
$.each(elems, function (ndx, el) {
if (el.inputmask) el.inputmask.setValue(value); else $(el).trigger("setvalue", [value]);
});
};
Inputmask.escapeRegex = function (str) {
var specials = ["/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\", "$", "^"];
return str.replace(new RegExp("(\\" + specials.join("|\\") + ")", "gim"), "\\$1");
};
Inputmask.keyCode = {
BACKSPACE: 8,
BACKSPACE_SAFARI: 127,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
INSERT: 45,
LEFT: 37,
PAGE_DOWN: 34,
PAGE_UP: 33,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38,
X: 88,
CONTROL: 17
};
Inputmask.dependencyLib = $;
function resolveAlias(aliasStr, options, opts) {
var aliasDefinition = Inputmask.prototype.aliases[aliasStr];
if (aliasDefinition) {
if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts);
$.extend(true, opts, aliasDefinition);
$.extend(true, opts, options);
return true;
} else if (opts.mask === null) {
opts.mask = aliasStr;
}
return false;
}
function generateMaskSet(opts, nocache) {
function generateMask(mask, metadata, opts) {
var regexMask = false;
if (mask === null || mask === "") {
regexMask = opts.regex !== null;
if (regexMask) {
mask = opts.regex;
mask = mask.replace(/^(\^)(.*)(\$)$/, "$2");
} else {
regexMask = true;
mask = ".*";
}
}
if (mask.length === 1 && opts.greedy === false && opts.repeat !== 0) {
opts.placeholder = "";
}
if (opts.repeat > 0 || opts.repeat === "*" || opts.repeat === "+") {
var repeatStart = opts.repeat === "*" ? 0 : opts.repeat === "+" ? 1 : opts.repeat;
mask = opts.groupmarker[0] + mask + opts.groupmarker[1] + opts.quantifiermarker[0] + repeatStart + "," + opts.repeat + opts.quantifiermarker[1];
}
var masksetDefinition,
maskdefKey = regexMask ? "regex_" + opts.regex : opts.numericInput ? mask.split("").reverse().join("") : mask;
if (Inputmask.prototype.masksCache[maskdefKey] === undefined || nocache === true) {
masksetDefinition = {
mask: mask,
maskToken: Inputmask.prototype.analyseMask(mask, regexMask, opts),
validPositions: {},
_buffer: undefined,
buffer: undefined,
tests: {},
excludes: {},
metadata: metadata,
maskLength: undefined,
jitOffset: {}
};
if (nocache !== true) {
Inputmask.prototype.masksCache[maskdefKey] = masksetDefinition;
masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[maskdefKey]);
}
} else masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[maskdefKey]);
return masksetDefinition;
}
var ms;
if ($.isFunction(opts.mask)) {
opts.mask = opts.mask(opts);
}
if ($.isArray(opts.mask)) {
if (opts.mask.length > 1) {
if (opts.keepStatic === null) {
opts.keepStatic = "auto";
for (var i = 0; i < opts.mask.length; i++) {
if (opts.mask[i].charAt(0) !== opts.mask[0].charAt(0)) {
opts.keepStatic = true;
break;
}
}
}
var altMask = opts.groupmarker[0];
$.each(opts.isRTL ? opts.mask.reverse() : opts.mask, function (ndx, msk) {
if (altMask.length > 1) {
altMask += opts.groupmarker[1] + opts.alternatormarker + opts.groupmarker[0];
}
if (msk.mask !== undefined && !$.isFunction(msk.mask)) {
altMask += msk.mask;
} else {
altMask += msk;
}
});
altMask += opts.groupmarker[1];
return generateMask(altMask, opts.mask, opts);
} else opts.mask = opts.mask.pop();
}
if (opts.mask && opts.mask.mask !== undefined && !$.isFunction(opts.mask.mask)) {
ms = generateMask(opts.mask.mask, opts.mask, opts);
} else {
ms = generateMask(opts.mask, opts.mask, opts);
}
return ms;
}
function isInputEventSupported(eventName) {
var el = document.createElement("input"), evName = "on" + eventName, isSupported = evName in el;
if (!isSupported) {
el.setAttribute(evName, "return;");
isSupported = typeof el[evName] === "function";
}
el = null;
return isSupported;
}
function maskScope(actionObj, maskset, opts) {
maskset = maskset || this.maskset;
opts = opts || this.opts;
var inputmask = this, el = this.el, isRTL = this.isRTL, undoValue, $el, skipKeyPressEvent = false,
skipInputEvent = false, ignorable = false, maxLength, mouseEnter = false, colorMask, originalPlaceholder;
var getMaskTemplate = function (baseOnInput, minimalPos, includeMode, noJit, clearOptionalTail) {
var greedy = opts.greedy;
if (clearOptionalTail) opts.greedy = false;
minimalPos = minimalPos || 0;
var maskTemplate = [], ndxIntlzr, pos = 0, test, testPos, lvp = getLastValidPosition();
do {
if (baseOnInput === true && getMaskSet().validPositions[pos]) {
testPos = clearOptionalTail && getMaskSet().validPositions[pos].match.optionality === true && getMaskSet().validPositions[pos + 1] === undefined && (getMaskSet().validPositions[pos].generatedInput === true || getMaskSet().validPositions[pos].input == opts.skipOptionalPartCharacter && pos > 0) ? determineTestTemplate(pos, getTests(pos, ndxIntlzr, pos - 1)) : getMaskSet().validPositions[pos];
test = testPos.match;
ndxIntlzr = testPos.locator.slice();
maskTemplate.push(includeMode === true ? testPos.input : includeMode === false ? test.nativeDef : getPlaceholder(pos, test));
} else {
testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
test = testPos.match;
ndxIntlzr = testPos.locator.slice();
var jitMasking = noJit === true ? false : opts.jitMasking !== false ? opts.jitMasking : test.jit;
if (jitMasking === false || jitMasking === undefined || typeof jitMasking === "number" && isFinite(jitMasking) && jitMasking > pos) {
maskTemplate.push(includeMode === false ? test.nativeDef : getPlaceholder(pos, test));
}
}
if (opts.keepStatic === "auto") {
if (test.newBlockMarker && test.fn !== null) {
opts.keepStatic = pos - 1;
}
}
pos++;
} while ((maxLength === undefined || pos < maxLength) && (test.fn !== null || test.def !== "") || minimalPos > pos);
if (maskTemplate[maskTemplate.length - 1] === "") {
maskTemplate.pop();
}
if (includeMode !== false || getMaskSet().maskLength === undefined) getMaskSet().maskLength = pos - 1;
opts.greedy = greedy;
return maskTemplate;
};
function getMaskSet() {
return maskset;
}
function resetMaskSet(soft) {
var maskset = getMaskSet();
maskset.buffer = undefined;
if (soft !== true) {
maskset.validPositions = {};
maskset.p = 0;
}
}
function getLastValidPosition(closestTo, strict, validPositions) {
var before = -1, after = -1, valids = validPositions || getMaskSet().validPositions;
if (closestTo === undefined) closestTo = -1;
for (var posNdx in valids) {
var psNdx = parseInt(posNdx);
if (valids[psNdx] && (strict || valids[psNdx].generatedInput !== true)) {
if (psNdx <= closestTo) before = psNdx;
if (psNdx >= closestTo) after = psNdx;
}
}
return before === -1 || before == closestTo ? after : after == -1 ? before : closestTo - before < after - closestTo ? before : after;
}
function getDecisionTaker(tst) {
var decisionTaker = tst.locator[tst.alternation];
if (typeof decisionTaker == "string" && decisionTaker.length > 0) {
decisionTaker = decisionTaker.split(",")[0];
}
return decisionTaker !== undefined ? decisionTaker.toString() : "";
}
function getLocator(tst, align) {
var locator = (tst.alternation != undefined ? tst.mloc[getDecisionTaker(tst)] : tst.locator).join("");
if (locator !== "") while (locator.length < align) locator += "0";
return locator;
}
function determineTestTemplate(pos, tests) {
pos = pos > 0 ? pos - 1 : 0;
var altTest = getTest(pos), targetLocator = getLocator(altTest), tstLocator, closest, bestMatch;
for (var ndx = 0; ndx < tests.length; ndx++) {
var tst = tests[ndx];
tstLocator = getLocator(tst, targetLocator.length);
var distance = Math.abs(tstLocator - targetLocator);
if (closest === undefined || tstLocator !== "" && distance < closest || bestMatch && !opts.greedy && bestMatch.match.optionality && bestMatch.match.newBlockMarker === "master" && (!tst.match.optionality || !tst.match.newBlockMarker) || bestMatch && bestMatch.match.optionalQuantifier && !tst.match.optionalQuantifier) {
closest = distance;
bestMatch = tst;
}
}
return bestMatch;
}
function getTestTemplate(pos, ndxIntlzr, tstPs) {
return getMaskSet().validPositions[pos] || determineTestTemplate(pos, getTests(pos, ndxIntlzr ? ndxIntlzr.slice() : ndxIntlzr, tstPs));
}
function getTest(pos, tests) {
if (getMaskSet().validPositions[pos]) {
return getMaskSet().validPositions[pos];
}
return (tests || getTests(pos))[0];
}
function positionCanMatchDefinition(pos, def) {
var valid = false, tests = getTests(pos);
for (var tndx = 0; tndx < tests.length; tndx++) {
if (tests[tndx].match && tests[tndx].match.def === def) {
valid = true;
break;
}
}
return valid;
}
function getTests(pos, ndxIntlzr, tstPs) {
var maskTokens = getMaskSet().maskToken, testPos = ndxIntlzr ? tstPs : 0,
ndxInitializer = ndxIntlzr ? ndxIntlzr.slice() : [0], matches = [], insertStop = false, latestMatch,
cacheDependency = ndxIntlzr ? ndxIntlzr.join("") : "";
function resolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) {
function handleMatch(match, loopNdx, quantifierRecurse) {
function isFirstMatch(latestMatch, tokenGroup) {
var firstMatch = $.inArray(latestMatch, tokenGroup.matches) === 0;
if (!firstMatch) {
$.each(tokenGroup.matches, function (ndx, match) {
if (match.isQuantifier === true) firstMatch = isFirstMatch(latestMatch, tokenGroup.matches[ndx - 1]); else if (match.hasOwnProperty("matches")) firstMatch = isFirstMatch(latestMatch, match);
if (firstMatch) return false;
});
}
return firstMatch;
}
function resolveNdxInitializer(pos, alternateNdx, targetAlternation) {
var bestMatch, indexPos;
if (getMaskSet().tests[pos] || getMaskSet().validPositions[pos]) {
$.each(getMaskSet().tests[pos] || [getMaskSet().validPositions[pos]], function (ndx, lmnt) {
if (lmnt.mloc[alternateNdx]) {
bestMatch = lmnt;
return false;
}
var alternation = targetAlternation !== undefined ? targetAlternation : lmnt.alternation,
ndxPos = lmnt.locator[alternation] !== undefined ? lmnt.locator[alternation].toString().indexOf(alternateNdx) : -1;
if ((indexPos === undefined || ndxPos < indexPos) && ndxPos !== -1) {
bestMatch = lmnt;
indexPos = ndxPos;
}
});
}
if (bestMatch) {
var bestMatchAltIndex = bestMatch.locator[bestMatch.alternation];
var locator = bestMatch.mloc[alternateNdx] || bestMatch.mloc[bestMatchAltIndex] || bestMatch.locator;
return locator.slice((targetAlternation !== undefined ? targetAlternation : bestMatch.alternation) + 1);
} else {
return targetAlternation !== undefined ? resolveNdxInitializer(pos, alternateNdx) : undefined;
}
}
function isSubsetOf(source, target) {
function expand(pattern) {
var expanded = [], start, end;
for (var i = 0, l = pattern.length; i < l; i++) {
if (pattern.charAt(i) === "-") {
end = pattern.charCodeAt(i + 1);
while (++start < end) expanded.push(String.fromCharCode(start));
} else {
start = pattern.charCodeAt(i);
expanded.push(pattern.charAt(i));
}
}
return expanded.join("");
}
if (opts.regex && source.match.fn !== null && target.match.fn !== null) {
return expand(target.match.def.replace(/[\[\]]/g, "")).indexOf(expand(source.match.def.replace(/[\[\]]/g, ""))) !== -1;
}
return source.match.def === target.match.nativeDef;
}
function staticCanMatchDefinition(source, target) {
var sloc = source.locator.slice(source.alternation).join(""),
tloc = target.locator.slice(target.alternation).join(""), canMatch = sloc == tloc;
canMatch = canMatch && source.match.fn === null && target.match.fn !== null ? target.match.fn.test(source.match.def, getMaskSet(), pos, false, opts, false) : false;
return canMatch;
}
function setMergeLocators(targetMatch, altMatch) {
if (altMatch === undefined || targetMatch.alternation === altMatch.alternation && targetMatch.locator[targetMatch.alternation].toString().indexOf(altMatch.locator[altMatch.alternation]) === -1) {
targetMatch.mloc = targetMatch.mloc || {};
var locNdx = targetMatch.locator[targetMatch.alternation];
if (locNdx === undefined) targetMatch.alternation = undefined; else {
if (typeof locNdx === "string") locNdx = locNdx.split(",")[0];
if (targetMatch.mloc[locNdx] === undefined) targetMatch.mloc[locNdx] = targetMatch.locator.slice();
if (altMatch !== undefined) {
for (var ndx in altMatch.mloc) {
if (typeof ndx === "string") ndx = ndx.split(",")[0];
if (targetMatch.mloc[ndx] === undefined) targetMatch.mloc[ndx] = altMatch.mloc[ndx];
}
targetMatch.locator[targetMatch.alternation] = Object.keys(targetMatch.mloc).join(",");
}
return true;
}
}
return false;
}
if (testPos > 500 && quantifierRecurse !== undefined) {
throw "Inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. " + getMaskSet().mask;
}
if (testPos === pos && match.matches === undefined) {
matches.push({
match: match,
locator: loopNdx.reverse(),
cd: cacheDependency,
mloc: {}
});
return true;
} else if (match.matches !== undefined) {
if (match.isGroup && quantifierRecurse !== match) {
match = handleMatch(maskToken.matches[$.inArray(match, maskToken.matches) + 1], loopNdx, quantifierRecurse);
if (match) return true;
} else if (match.isOptional) {
var optionalToken = match;
match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
if (match) {
$.each(matches, function (ndx, mtch) {
mtch.match.optionality = true;
});
latestMatch = matches[matches.length - 1].match;
if (quantifierRecurse === undefined && isFirstMatch(latestMatch, optionalToken)) {
insertStop = true;
testPos = pos;
} else return true;
}
} else if (match.isAlternator) {
var alternateToken = match, malternateMatches = [], maltMatches,
currentMatches = matches.slice(), loopNdxCnt = loopNdx.length;
var altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1;
if (altIndex === -1 || typeof altIndex === "string") {
var currentPos = testPos, ndxInitializerClone = ndxInitializer.slice(),
altIndexArr = [], amndx;
if (typeof altIndex == "string") {
altIndexArr = altIndex.split(",");
} else {
for (amndx = 0; amndx < alternateToken.matches.length; amndx++) {
altIndexArr.push(amndx.toString());
}
}
if (getMaskSet().excludes[pos]) {
var altIndexArrClone = altIndexArr.slice();
for (var i = 0, el = getMaskSet().excludes[pos].length; i < el; i++) {
altIndexArr.splice(altIndexArr.indexOf(getMaskSet().excludes[pos][i].toString()), 1);
}
if (altIndexArr.length === 0) {
getMaskSet().excludes[pos] = undefined;
altIndexArr = altIndexArrClone;
}
}
if (opts.keepStatic === true || isFinite(parseInt(opts.keepStatic)) && currentPos >= opts.keepStatic) altIndexArr = altIndexArr.slice(0, 1);
var unMatchedAlternation = false;
for (var ndx = 0; ndx < altIndexArr.length; ndx++) {
amndx = parseInt(altIndexArr[ndx]);
matches = [];
ndxInitializer = typeof altIndex === "string" ? resolveNdxInitializer(testPos, amndx, loopNdxCnt) || ndxInitializerClone.slice() : ndxInitializerClone.slice();
if (alternateToken.matches[amndx] && handleMatch(alternateToken.matches[amndx], [amndx].concat(loopNdx), quantifierRecurse)) match = true; else if (ndx === 0) {
unMatchedAlternation = true;
}
maltMatches = matches.slice();
testPos = currentPos;
matches = [];
for (var ndx1 = 0; ndx1 < maltMatches.length; ndx1++) {
var altMatch = maltMatches[ndx1], dropMatch = false;
altMatch.match.jit = altMatch.match.jit || unMatchedAlternation;
altMatch.alternation = altMatch.alternation || loopNdxCnt;
setMergeLocators(altMatch);
for (var ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) {
var altMatch2 = malternateMatches[ndx2];
if (typeof altIndex !== "string" || altMatch.alternation !== undefined && $.inArray(altMatch.locator[altMatch.alternation].toString(), altIndexArr) !== -1) {
if (altMatch.match.nativeDef === altMatch2.match.nativeDef) {
dropMatch = true;
setMergeLocators(altMatch2, altMatch);
break;
} else if (isSubsetOf(altMatch, altMatch2)) {
if (setMergeLocators(altMatch, altMatch2)) {
dropMatch = true;
malternateMatches.splice(malternateMatches.indexOf(altMatch2), 0, altMatch);
}
break;
} else if (isSubsetOf(altMatch2, altMatch)) {
setMergeLocators(altMatch2, altMatch);
break;
} else if (staticCanMatchDefinition(altMatch, altMatch2)) {
if (setMergeLocators(altMatch, altMatch2)) {
dropMatch = true;
malternateMatches.splice(malternateMatches.indexOf(altMatch2), 0, altMatch);
}
break;
}
}
}
if (!dropMatch) {
malternateMatches.push(altMatch);
}
}
}
matches = currentMatches.concat(malternateMatches);
testPos = pos;
insertStop = matches.length > 0;
match = malternateMatches.length > 0;
ndxInitializer = ndxInitializerClone.slice();
} else match = handleMatch(alternateToken.matches[altIndex] || maskToken.matches[altIndex], [altIndex].concat(loopNdx), quantifierRecurse);
if (match) return true;
} else if (match.isQuantifier && quantifierRecurse !== maskToken.matches[$.inArray(match, maskToken.matches) - 1]) {
var qt = match;
for (var qndx = ndxInitializer.length > 0 ? ndxInitializer.shift() : 0; qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max) && testPos <= pos; qndx++) {
var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];
match = handleMatch(tokenGroup, [qndx].concat(loopNdx), tokenGroup);
if (match) {
latestMatch = matches[matches.length - 1].match;
latestMatch.optionalQuantifier = qndx >= qt.quantifier.min;
latestMatch.jit = (qndx || 1) * tokenGroup.matches.indexOf(latestMatch) >= qt.quantifier.jit;
if (latestMatch.optionalQuantifier && isFirstMatch(latestMatch, tokenGroup)) {
insertStop = true;
testPos = pos;
break;
}
if (latestMatch.jit) {
getMaskSet().jitOffset[pos] = tokenGroup.matches.indexOf(latestMatch);
}
return true;
}
}
} else {
match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
if (match) return true;
}
} else {
testPos++;
}
}
for (var tndx = ndxInitializer.length > 0 ? ndxInitializer.shift() : 0; tndx < maskToken.matches.length; tndx++) {
if (maskToken.matches[tndx].isQuantifier !== true) {
var match = handleMatch(maskToken.matches[tndx], [tndx].concat(loopNdx), quantifierRecurse);
if (match && testPos === pos) {
return match;
} else if (testPos > pos) {
break;
}
}
}
}
function mergeLocators(pos, tests) {
var locator = [];
if (!$.isArray(tests)) tests = [tests];
if (tests.length > 0) {
if (tests[0].alternation === undefined) {
locator = determineTestTemplate(pos, tests.slice()).locator.slice();
if (locator.length === 0) locator = tests[0].locator.slice();
} else {
$.each(tests, function (ndx, tst) {
if (tst.def !== "") {
if (locator.length === 0) locator = tst.locator.slice(); else {
for (var i = 0; i < locator.length; i++) {
if (tst.locator[i] && locator[i].toString().indexOf(tst.locator[i]) === -1) {
locator[i] += "," + tst.locator[i];
}
}
}
}
});
}
}
return locator;
}
if (pos > -1) {
if (ndxIntlzr === undefined) {
var previousPos = pos - 1, test;
while ((test = getMaskSet().validPositions[previousPos] || getMaskSet().tests[previousPos]) === undefined && previousPos > -1) {
previousPos--;
}
if (test !== undefined && previousPos > -1) {
ndxInitializer = mergeLocators(previousPos, test);
cacheDependency = ndxInitializer.join("");
testPos = previousPos;
}
}
if (getMaskSet().tests[pos] && getMaskSet().tests[pos][0].cd === cacheDependency) {
return getMaskSet().tests[pos];
}
for (var mtndx = ndxInitializer.shift(); mtndx < maskTokens.length; mtndx++) {
var match = resolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
if (match && testPos === pos || testPos > pos) {
break;
}
}
}
if (matches.length === 0 || insertStop) {
matches.push({
match: {
fn: null,
optionality: false,
casing: null,
def: "",
placeholder: ""
},
locator: [],
mloc: {},
cd: cacheDependency
});
}
if (ndxIntlzr !== undefined && getMaskSet().tests[pos]) {
return $.extend(true, [], matches);
}
getMaskSet().tests[pos] = $.extend(true, [], matches);
return getMaskSet().tests[pos];
}
function getBufferTemplate() {
if (getMaskSet()._buffer === undefined) {
getMaskSet()._buffer = getMaskTemplate(false, 1);
if (getMaskSet().buffer === undefined) getMaskSet().buffer = getMaskSet()._buffer.slice();
}
return getMaskSet()._buffer;
}
function getBuffer(noCache) {
if (getMaskSet().buffer === undefined || noCache === true) {
getMaskSet().buffer = getMaskTemplate(true, getLastValidPosition(), true);
if (getMaskSet()._buffer === undefined) getMaskSet()._buffer = getMaskSet().buffer.slice();
}
return getMaskSet().buffer;
}
function refreshFromBuffer(start, end, buffer) {
var i, p;
if (start === true) {
resetMaskSet();
start = 0;
end = buffer.length;
} else {
for (i = start; i < end; i++) {
delete getMaskSet().validPositions[i];
}
}
p = start;
for (i = start; i < end; i++) {
resetMaskSet(true);
if (buffer[i] !== opts.skipOptionalPartCharacter) {
var valResult = isValid(p, buffer[i], true, true);
if (valResult !== false) {
resetMaskSet(true);
p = valResult.caret !== undefined ? valResult.caret : valResult.pos + 1;
}
}
}
}
function casing(elem, test, pos) {
switch (opts.casing || test.casing) {
case "upper":
elem = elem.toUpperCase();
break;
case "lower":
elem = elem.toLowerCase();
break;
case "title":
var posBefore = getMaskSet().validPositions[pos - 1];
if (pos === 0 || posBefore && posBefore.input === String.fromCharCode(Inputmask.keyCode.SPACE)) {
elem = elem.toUpperCase();
} else {
elem = elem.toLowerCase();
}
break;
default:
if ($.isFunction(opts.casing)) {
var args = Array.prototype.slice.call(arguments);
args.push(getMaskSet().validPositions);
elem = opts.casing.apply(this, args);
}
}
return elem;
}
function checkAlternationMatch(altArr1, altArr2, na) {
var altArrC = opts.greedy ? altArr2 : altArr2.slice(0, 1), isMatch = false,
naArr = na !== undefined ? na.split(",") : [], naNdx;
for (var i = 0; i < naArr.length; i++) {
if ((naNdx = altArr1.indexOf(naArr[i])) !== -1) {
altArr1.splice(naNdx, 1);
}
}
for (var alndx = 0; alndx < altArr1.length; alndx++) {
if ($.inArray(altArr1[alndx], altArrC) !== -1) {
isMatch = true;
break;
}
}
return isMatch;
}
function alternate(pos, c, strict, fromSetValid, rAltPos) {
var validPsClone = $.extend(true, {}, getMaskSet().validPositions), lastAlt, alternation,
isValidRslt = false, altPos, prevAltPos, i, validPos, decisionPos,
lAltPos = rAltPos !== undefined ? rAltPos : getLastValidPosition();
if (lAltPos === -1 && rAltPos === undefined) {
lastAlt = 0;
prevAltPos = getTest(lastAlt);
alternation = prevAltPos.alternation;
} else {
for (; lAltPos >= 0; lAltPos--) {
altPos = getMaskSet().validPositions[lAltPos];
if (altPos && altPos.alternation !== undefined) {
if (prevAltPos && prevAltPos.locator[altPos.alternation] !== altPos.locator[altPos.alternation]) {
break;
}
lastAlt = lAltPos;
alternation = getMaskSet().validPositions[lastAlt].alternation;
prevAltPos = altPos;
}
}
}
if (alternation !== undefined) {
decisionPos = parseInt(lastAlt);
getMaskSet().excludes[decisionPos] = getMaskSet().excludes[decisionPos] || [];
if (pos !== true) {
getMaskSet().excludes[decisionPos].push(getDecisionTaker(prevAltPos));
}
var validInputsClone = [], staticInputsBeforePos = 0;
for (i = decisionPos; i < getLastValidPosition(undefined, true) + 1; i++) {
validPos = getMaskSet().validPositions[i];
if (validPos && validPos.generatedInput !== true) {
validInputsClone.push(validPos.input);
} else if (i < pos) staticInputsBeforePos++;
delete getMaskSet().validPositions[i];
}
while (getMaskSet().excludes[decisionPos] && getMaskSet().excludes[decisionPos].length < 10) {
var posOffset = staticInputsBeforePos * -1, validInputs = validInputsClone.slice();
getMaskSet().tests[decisionPos] = undefined;
resetMaskSet(true);
isValidRslt = true;
while (validInputs.length > 0) {
var input = validInputs.shift();
if (!(isValidRslt = isValid(getLastValidPosition(undefined, true) + 1, input, false, fromSetValid, true))) {
break;
}
}
if (isValidRslt && c !== undefined) {
var targetLvp = getLastValidPosition(pos) + 1;
for (i = decisionPos; i < getLastValidPosition() + 1; i++) {
validPos = getMaskSet().validPositions[i];
if ((validPos === undefined || validPos.match.fn == null) && i < pos + posOffset) {
posOffset++;
}
}
pos = pos + posOffset;
isValidRslt = isValid(pos > targetLvp ? targetLvp : pos, c, strict, fromSetValid, true);
}
if (!isValidRslt) {
resetMaskSet();
prevAltPos = getTest(decisionPos);
getMaskSet().validPositions = $.extend(true, {}, validPsClone);
if (getMaskSet().excludes[decisionPos]) {
var decisionTaker = getDecisionTaker(prevAltPos);
if (getMaskSet().excludes[decisionPos].indexOf(decisionTaker) !== -1) {
isValidRslt = alternate(pos, c, strict, fromSetValid, decisionPos - 1);
break;
}
getMaskSet().excludes[decisionPos].push(decisionTaker);
for (i = decisionPos; i < getLastValidPosition(undefined, true) + 1; i++) delete getMaskSet().validPositions[i];
} else {
isValidRslt = alternate(pos, c, strict, fromSetValid, decisionPos - 1);
break;
}
} else break;
}
}
getMaskSet().excludes[decisionPos] = undefined;
return isValidRslt;
}
function isValid(pos, c, strict, fromSetValid, fromAlternate, validateOnly) {
function isSelection(posObj) {
return isRTL ? posObj.begin - posObj.end > 1 || posObj.begin - posObj.end === 1 : posObj.end - posObj.begin > 1 || posObj.end - posObj.begin === 1;
}
strict = strict === true;
var maskPos = pos;
if (pos.begin !== undefined) {
maskPos = isRTL ? pos.end : pos.begin;
}
function _isValid(position, c, strict) {
var rslt = false;
$.each(getTests(position), function (ndx, tst) {
var test = tst.match;
getBuffer(true);
rslt = test.fn != null ? test.fn.test(c, getMaskSet(), position, strict, opts, isSelection(pos)) : (c === test.def || c === opts.skipOptionalPartCharacter) && test.def !== "" ? {
c: getPlaceholder(position, test, true) || test.def,
pos: position
} : false;
if (rslt !== false) {
var elem = rslt.c !== undefined ? rslt.c : c, validatedPos = position;
elem = elem === opts.skipOptionalPartCharacter && test.fn === null ? getPlaceholder(position, test, true) || test.def : elem;
if (rslt.remove !== undefined) {
if (!$.isArray(rslt.remove)) rslt.remove = [rslt.remove];
$.each(rslt.remove.sort(function (a, b) {
return b - a;
}), function (ndx, lmnt) {
revalidateMask({
begin: lmnt,
end: lmnt + 1
});
});
}
if (rslt.insert !== undefined) {
if (!$.isArray(rslt.insert)) rslt.insert = [rslt.insert];
$.each(rslt.insert.sort(function (a, b) {
return a - b;
}), function (ndx, lmnt) {
isValid(lmnt.pos, lmnt.c, true, fromSetValid);
});
}
if (rslt !== true && rslt.pos !== undefined && rslt.pos !== position) {
validatedPos = rslt.pos;
}
if (rslt !== true && rslt.pos === undefined && rslt.c === undefined) {
return false;
}
if (!revalidateMask(pos, $.extend({}, tst, {
input: casing(elem, test, validatedPos)
}), fromSetValid, validatedPos)) {
rslt = false;
}
return false;
}
});
return rslt;
}
var result = true, positionsClone = $.extend(true, {}, getMaskSet().validPositions);
if ($.isFunction(opts.preValidation) && !strict && fromSetValid !== true && validateOnly !== true) {
result = opts.preValidation(getBuffer(), maskPos, c, isSelection(pos), opts, getMaskSet());
}
if (result === true) {
trackbackPositions(undefined, maskPos, true);
if (maxLength === undefined || maskPos < maxLength) {
result = _isValid(maskPos, c, strict);
if ((!strict || fromSetValid === true) && result === false && validateOnly !== true) {
var currentPosValid = getMaskSet().validPositions[maskPos];
if (currentPosValid && currentPosValid.match.fn === null && (currentPosValid.match.def === c || c === opts.skipOptionalPartCharacter)) {
result = {
caret: seekNext(maskPos)
};
} else {
if ((opts.insertMode || getMaskSet().validPositions[seekNext(maskPos)] === undefined) && (!isMask(maskPos, true) || getMaskSet().jitOffset[maskPos])) {
if (getMaskSet().jitOffset[maskPos] && getMaskSet().validPositions[seekNext(maskPos)] === undefined) {
result = isValid(maskPos + getMaskSet().jitOffset[maskPos], c, strict);
if (result !== false) result.caret = maskPos;
} else for (var nPos = maskPos + 1, snPos = seekNext(maskPos); nPos <= snPos; nPos++) {
result = _isValid(nPos, c, strict);
if (result !== false) {
result = trackbackPositions(maskPos, result.pos !== undefined ? result.pos : nPos) || result;
maskPos = nPos;
break;
}
}
}
}
}
}
if (result === false && opts.keepStatic !== false && (opts.regex == null || isComplete(getBuffer())) && !strict && fromAlternate !== true) {
result = alternate(maskPos, c, strict, fromSetValid);
}
if (result === true) {
result = {
pos: maskPos
};
}
}
if ($.isFunction(opts.postValidation) && result !== false && !strict && fromSetValid !== true && validateOnly !== true) {
var postResult = opts.postValidation(getBuffer(true), pos.begin !== undefined ? isRTL ? pos.end : pos.begin : pos, result, opts);
if (postResult !== undefined) {
if (postResult.refreshFromBuffer && postResult.buffer) {
var refresh = postResult.refreshFromBuffer;
refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, postResult.buffer);
}
result = postResult === true ? result : postResult;
}
}
if (result && result.pos === undefined) {
result.pos = maskPos;
}
if (result === false || validateOnly === true) {
resetMaskSet(true);
getMaskSet().validPositions = $.extend(true, {}, positionsClone);
}
return result;
}
function trackbackPositions(originalPos, newPos, fillOnly) {
var result;
if (originalPos === undefined) {
for (originalPos = newPos - 1; originalPos > 0; originalPos--) {
if (getMaskSet().validPositions[originalPos]) break;
}
}
for (var ps = originalPos; ps < newPos; ps++) {
if (getMaskSet().validPositions[ps] === undefined && !isMask(ps, true)) {
var vp = ps == 0 ? getTest(ps) : getMaskSet().validPositions[ps - 1];
if (vp) {
var tests = getTests(ps).slice();
if (tests[tests.length - 1].match.def === "") tests.pop();
var bestMatch = determineTestTemplate(ps, tests);
bestMatch = $.extend({}, bestMatch, {
input: getPlaceholder(ps, bestMatch.match, true) || bestMatch.match.def
});
bestMatch.generatedInput = true;
revalidateMask(ps, bestMatch, true);
if (fillOnly !== true) {
var cvpInput = getMaskSet().validPositions[newPos].input;
getMaskSet().validPositions[newPos] = undefined;
result = isValid(newPos, cvpInput, true, true);
}
}
}
}
return result;
}
function revalidateMask(pos, validTest, fromSetValid, validatedPos) {
function IsEnclosedStatic(pos, valids, selection) {
var posMatch = valids[pos];
if (posMatch !== undefined && (posMatch.match.fn === null && posMatch.match.optionality !== true || posMatch.input === opts.radixPoint)) {
var prevMatch = selection.begin <= pos - 1 ? valids[pos - 1] && valids[pos - 1].match.fn === null && valids[pos - 1] : valids[pos - 1],
nextMatch = selection.end > pos + 1 ? valids[pos + 1] && valids[pos + 1].match.fn === null && valids[pos + 1] : valids[pos + 1];
return prevMatch && nextMatch;
}
return false;
}
var begin = pos.begin !== undefined ? pos.begin : pos, end = pos.end !== undefined ? pos.end : pos;
if (pos.begin > pos.end) {
begin = pos.end;
end = pos.begin;
}
validatedPos = validatedPos !== undefined ? validatedPos : begin;
if (begin !== end || opts.insertMode && getMaskSet().validPositions[validatedPos] !== undefined && fromSetValid === undefined) {
var positionsClone = $.extend(true, {}, getMaskSet().validPositions),
lvp = getLastValidPosition(undefined, true), i;
getMaskSet().p = begin;
for (i = lvp; i >= begin; i--) {
if (getMaskSet().validPositions[i] && getMaskSet().validPositions[i].match.nativeDef === "+") {
opts.isNegative = false;
}
delete getMaskSet().validPositions[i];
}
var valid = true, j = validatedPos, vps = getMaskSet().validPositions, needsValidation = false,
posMatch = j, i = j;
if (validTest) {
getMaskSet().validPositions[validatedPos] = $.extend(true, {}, validTest);
posMatch++;
j++;
if (begin < end) i++;
}
for (; i <= lvp; i++) {
var t = positionsClone[i];
if (t !== undefined && (i >= end || i >= begin && t.generatedInput !== true && IsEnclosedStatic(i, positionsClone, {
begin: begin,
end: end
}))) {
while (getTest(posMatch).match.def !== "") {
if (needsValidation === false && positionsClone[posMatch] && positionsClone[posMatch].match.nativeDef === t.match.nativeDef) {
getMaskSet().validPositions[posMatch] = $.extend(true, {}, positionsClone[posMatch]);
getMaskSet().validPositions[posMatch].input = t.input;
trackbackPositions(undefined, posMatch, true);
j = posMatch + 1;
valid = true;
} else if (opts.shiftPositions && positionCanMatchDefinition(posMatch, t.match.def)) {
var result = isValid(posMatch, t.input, true, true);
valid = result !== false;
j = result.caret || result.insert ? getLastValidPosition() : posMatch + 1;
needsValidation = true;
} else {
valid = t.generatedInput === true || t.input === opts.radixPoint && opts.numericInput === true;
}
if (valid) break;
if (!valid && posMatch > end && isMask(posMatch, true) && (t.match.fn !== null || posMatch > getMaskSet().maskLength)) {
break;
}
posMatch++;
}
if (getTest(posMatch).match.def == "") valid = false;
posMatch = j;
}
if (!valid) break;
}
if (!valid) {
getMaskSet().validPositions = $.extend(true, {}, positionsClone);
resetMaskSet(true);
return false;
}
} else if (validTest) {
getMaskSet().validPositions[validatedPos] = $.extend(true, {}, validTest);
}
resetMaskSet(true);
return true;
}
function isMask(pos, strict) {
var test = getTestTemplate(pos).match;
if (test.def === "") test = getTest(pos).match;
if (test.fn != null) {
return test.fn;
}
if (strict !== true && pos > -1) {
var tests = getTests(pos);
return tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0);
}
return false;
}
function seekNext(pos, newBlock) {
var position = pos + 1;
while (getTest(position).match.def !== "" && (newBlock === true && (getTest(position).match.newBlockMarker !== true || !isMask(position)) || newBlock !== true && !isMask(position))) {
position++;
}
return position;
}
function seekPrevious(pos, newBlock) {
var position = pos, tests;
if (position <= 0) return 0;
while (--position > 0 && (newBlock === true && getTest(position).match.newBlockMarker !== true || newBlock !== true && !isMask(position) && (tests = getTests(position),
tests.length < 2 || tests.length === 2 && tests[1].match.def === ""))) {
}
return position;
}
function writeBuffer(input, buffer, caretPos, event, triggerEvents) {
if (event && $.isFunction(opts.onBeforeWrite)) {
var result = opts.onBeforeWrite.call(inputmask, event, buffer, caretPos, opts);
if (result) {
if (result.refreshFromBuffer) {
var refresh = result.refreshFromBuffer;
refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer || buffer);
buffer = getBuffer(true);
}
if (caretPos !== undefined) caretPos = result.caret !== undefined ? result.caret : caretPos;
}
}
if (input !== undefined) {
input.inputmask._valueSet(buffer.join(""));
if (caretPos !== undefined && (event === undefined || event.type !== "blur")) {
caret(input, caretPos);
} else renderColorMask(input, caretPos, buffer.length === 0);
if (triggerEvents === true) {
var $input = $(input), nptVal = input.inputmask._valueGet();
skipInputEvent = true;
$input.trigger("input");
setTimeout(function () {
if (nptVal === getBufferTemplate().join("")) {
$input.trigger("cleared");
} else if (isComplete(buffer) === true) {
$input.trigger("complete");
}
}, 0);
}
}
}
function getPlaceholder(pos, test, returnPL) {
test = test || getTest(pos).match;
if (test.placeholder !== undefined || returnPL === true) {
return $.isFunction(test.placeholder) ? test.placeholder(opts) : test.placeholder;
} else if (test.fn === null) {
if (pos > -1 && getMaskSet().validPositions[pos] === undefined) {
var tests = getTests(pos), staticAlternations = [], prevTest;
if (tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0)) {
for (var i = 0; i < tests.length; i++) {
if (tests[i].match.optionality !== true && tests[i].match.optionalQuantifier !== true && (tests[i].match.fn === null || (prevTest === undefined || tests[i].match.fn.test(prevTest.match.def, getMaskSet(), pos, true, opts) !== false))) {
staticAlternations.push(tests[i]);
if (tests[i].match.fn === null) prevTest = tests[i];
if (staticAlternations.length > 1) {
if (/[0-9a-bA-Z]/.test(staticAlternations[0].match.def)) {
return opts.placeholder.charAt(pos % opts.placeholder.length);
}
}
}
}
}
}
return test.def;
}
return opts.placeholder.charAt(pos % opts.placeholder.length);
}
function HandleNativePlaceholder(npt, value) {
if (ie) {
if (npt.inputmask._valueGet() !== value && (npt.placeholder !== value || npt.placeholder === "")) {
var buffer = getBuffer().slice(), nptValue = npt.inputmask._valueGet();
if (nptValue !== value) {
var lvp = getLastValidPosition();
if (lvp === -1 && nptValue === getBufferTemplate().join("")) {
buffer = [];
} else if (lvp !== -1) {
clearOptionalTail(buffer);
}
writeBuffer(npt, buffer);
}
}
} else if (npt.placeholder !== value) {
npt.placeholder = value;
if (npt.placeholder === "") npt.removeAttribute("placeholder");
}
}
var EventRuler = {
on: function (input, eventName, eventHandler) {
var ev = function (e) {
var that = this;
if (that.inputmask === undefined && this.nodeName !== "FORM") {
var imOpts = $.data(that, "_inputmask_opts");
if (imOpts) new Inputmask(imOpts).mask(that); else EventRuler.off(that);
} else if (e.type !== "setvalue" && this.nodeName !== "FORM" && (that.disabled || that.readOnly && !(e.type === "keydown" && (e.ctrlKey && e.keyCode === 67) || opts.tabThrough === false && e.keyCode === Inputmask.keyCode.TAB))) {
e.preventDefault();
} else {
switch (e.type) {
case "input":
if (skipInputEvent === true) {
skipInputEvent = false;
return e.preventDefault();
}
if (mobile) {
var args = arguments;
setTimeout(function () {
eventHandler.apply(that, args);
caret(that, that.inputmask.caretPos, undefined, true);
}, 0);
return false;
}
break;
case "keydown":
skipKeyPressEvent = false;
skipInputEvent = false;
break;
case "keypress":
if (skipKeyPressEvent === true) {
return e.preventDefault();
}
skipKeyPressEvent = true;
break;
case "click":
if (iemobile || iphone) {
var args = arguments;
setTimeout(function () {
eventHandler.apply(that, args);
}, 0);
return false;
}
break;
}
var returnVal = eventHandler.apply(that, arguments);
if (returnVal === false) {
e.preventDefault();
e.stopPropagation();
}
return returnVal;
}
};
input.inputmask.events[eventName] = input.inputmask.events[eventName] || [];
input.inputmask.events[eventName].push(ev);
if ($.inArray(eventName, ["submit", "reset"]) !== -1) {
if (input.form !== null) $(input.form).on(eventName, ev);
} else {
$(input).on(eventName, ev);
}
},
off: function (input, event) {
if (input.inputmask && input.inputmask.events) {
var events;
if (event) {
events = [];
events[event] = input.inputmask.events[event];
} else {
events = input.inputmask.events;
}
$.each(events, function (eventName, evArr) {
while (evArr.length > 0) {
var ev = evArr.pop();
if ($.inArray(eventName, ["submit", "reset"]) !== -1) {
if (input.form !== null) $(input.form).off(eventName, ev);
} else {
$(input).off(eventName, ev);
}
}
delete input.inputmask.events[eventName];
});
}
}
};
var EventHandlers = {
keydownEvent: function (e) {
var input = this, $input = $(input), k = e.keyCode, pos = caret(input);
if (k === Inputmask.keyCode.BACKSPACE || k === Inputmask.keyCode.DELETE || iphone && k === Inputmask.keyCode.BACKSPACE_SAFARI || e.ctrlKey && k === Inputmask.keyCode.X && !isInputEventSupported("cut")) {
e.preventDefault();
handleRemove(input, k, pos);
writeBuffer(input, getBuffer(true), getMaskSet().p, e, input.inputmask._valueGet() !== getBuffer().join(""));
} else if (k === Inputmask.keyCode.END || k === Inputmask.keyCode.PAGE_DOWN) {
e.preventDefault();
var caretPos = seekNext(getLastValidPosition());
caret(input, e.shiftKey ? pos.begin : caretPos, caretPos, true);
} else if (k === Inputmask.keyCode.HOME && !e.shiftKey || k === Inputmask.keyCode.PAGE_UP) {
e.preventDefault();
caret(input, 0, e.shiftKey ? pos.begin : 0, true);
} else if ((opts.undoOnEscape && k === Inputmask.keyCode.ESCAPE || k === 90 && e.ctrlKey) && e.altKey !== true) {
checkVal(input, true, false, undoValue.split(""));
$input.trigger("click");
} else if (k === Inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) {
opts.insertMode = !opts.insertMode;
input.setAttribute("im-insert", opts.insertMode);
} else if (opts.tabThrough === true && k === Inputmask.keyCode.TAB) {
if (e.shiftKey === true) {
if (getTest(pos.begin).match.fn === null) {
pos.begin = seekNext(pos.begin);
}
pos.end = seekPrevious(pos.begin, true);
pos.begin = seekPrevious(pos.end, true);
} else {
pos.begin = seekNext(pos.begin, true);
pos.end = seekNext(pos.begin, true);
if (pos.end < getMaskSet().maskLength) pos.end--;
}
if (pos.begin < getMaskSet().maskLength) {
e.preventDefault();
caret(input, pos.begin, pos.end);
}
}
opts.onKeyDown.call(this, e, getBuffer(), caret(input).begin, opts);
ignorable = $.inArray(k, opts.ignorables) !== -1;
},
keypressEvent: function (e, checkval, writeOut, strict, ndx) {
var input = this, $input = $(input), k = e.which || e.charCode || e.keyCode;
if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
if (k === Inputmask.keyCode.ENTER && undoValue !== getBuffer().join("")) {
undoValue = getBuffer().join("");
setTimeout(function () {
$input.trigger("change");
}, 0);
}
return true;
} else {
if (k) {
if (k === 46 && e.shiftKey === false && opts.radixPoint !== "") k = opts.radixPoint.charCodeAt(0);
var pos = checkval ? {
begin: ndx,
end: ndx
} : caret(input), forwardPosition, c = String.fromCharCode(k), offset = 0;
if (opts._radixDance && opts.numericInput) {
var caretPos = getBuffer().indexOf(opts.radixPoint.charAt(0)) + 1;
if (pos.begin <= caretPos) {
if (k === opts.radixPoint.charCodeAt(0)) offset = 1;
pos.begin -= 1;
pos.end -= 1;
}
}
getMaskSet().writeOutBuffer = true;
var valResult = isValid(pos, c, strict);
if (valResult !== false) {
resetMaskSet(true);
forwardPosition = valResult.caret !== undefined ? valResult.caret : seekNext(valResult.pos.begin ? valResult.pos.begin : valResult.pos);
getMaskSet().p = forwardPosition;
}
forwardPosition = (opts.numericInput && valResult.caret === undefined ? seekPrevious(forwardPosition) : forwardPosition) + offset;
if (writeOut !== false) {
setTimeout(function () {
opts.onKeyValidation.call(input, k, valResult, opts);
}, 0);
if (getMaskSet().writeOutBuffer && valResult !== false) {
var buffer = getBuffer();
writeBuffer(input, buffer, forwardPosition, e, checkval !== true);
}
}
e.preventDefault();
if (checkval) {
if (valResult !== false) valResult.forwardPosition = forwardPosition;
return valResult;
}
}
}
},
pasteEvent: function (e) {
var input = this, ev = e.originalEvent || e, $input = $(input),
inputValue = input.inputmask._valueGet(true), caretPos = caret(input), tempValue;
if (isRTL) {
tempValue = caretPos.end;
caretPos.end = caretPos.begin;
caretPos.begin = tempValue;
}
var valueBeforeCaret = inputValue.substr(0, caretPos.begin),
valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length);
if (valueBeforeCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(0, caretPos.begin).join("")) valueBeforeCaret = "";
if (valueAfterCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(caretPos.end).join("")) valueAfterCaret = "";
if (window.clipboardData && window.clipboardData.getData) {
inputValue = valueBeforeCaret + window.clipboardData.getData("Text") + valueAfterCaret;
} else if (ev.clipboardData && ev.clipboardData.getData) {
inputValue = valueBeforeCaret + ev.clipboardData.getData("text/plain") + valueAfterCaret;
} else return true;
var pasteValue = inputValue;
if ($.isFunction(opts.onBeforePaste)) {
pasteValue = opts.onBeforePaste.call(inputmask, inputValue, opts);
if (pasteValue === false) {
return e.preventDefault();
}
if (!pasteValue) {
pasteValue = inputValue;
}
}
checkVal(input, false, false, pasteValue.toString().split(""));
writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()), e, undoValue !== getBuffer().join(""));
return e.preventDefault();
},
inputFallBackEvent: function (e) {
function radixPointHandler(input, inputValue, caretPos) {
if (inputValue.charAt(caretPos.begin - 1) === "." && opts.radixPoint !== "") {
inputValue = inputValue.split("");
inputValue[caretPos.begin - 1] = opts.radixPoint.charAt(0);
inputValue = inputValue.join("");
}
return inputValue;
}
function ieMobileHandler(input, inputValue, caretPos) {
if (iemobile) {
var inputChar = inputValue.replace(getBuffer().join(""), "");
if (inputChar.length === 1) {
var iv = inputValue.split("");
iv.splice(caretPos.begin, 0, inputChar);
inputValue = iv.join("");
}
}
return inputValue;
}
var input = this, inputValue = input.inputmask._valueGet();
if (getBuffer().join("") !== inputValue) {
var caretPos = caret(input);
inputValue = radixPointHandler(input, inputValue, caretPos);
inputValue = ieMobileHandler(input, inputValue, caretPos);
if (getBuffer().join("") !== inputValue) {
var buffer = getBuffer().join(""),
offset = !opts.numericInput && inputValue.length > buffer.length ? -1 : 0,
frontPart = inputValue.substr(0, caretPos.begin),
backPart = inputValue.substr(caretPos.begin),
frontBufferPart = buffer.substr(0, caretPos.begin + offset),
backBufferPart = buffer.substr(caretPos.begin + offset);
var selection = caretPos, entries = "", isEntry = false;
if (frontPart !== frontBufferPart) {
var fpl = (isEntry = frontPart.length >= frontBufferPart.length) ? frontPart.length : frontBufferPart.length,
i;
for (i = 0; frontPart.charAt(i) === frontBufferPart.charAt(i) && i < fpl; i++) ;
if (isEntry) {
selection.begin = i - offset;
entries += frontPart.slice(i, selection.end);
}
}
if (backPart !== backBufferPart) {
if (backPart.length > backBufferPart.length) {
entries += backPart.slice(0, 1);
} else {
if (backPart.length < backBufferPart.length) {
selection.end += backBufferPart.length - backPart.length;
if (!isEntry && opts.radixPoint !== "" && backPart === "" && frontPart.charAt(selection.begin + offset - 1) === opts.radixPoint) {
selection.begin--;
entries = opts.radixPoint;
}
}
}
}
writeBuffer(input, getBuffer(), {
begin: selection.begin + offset,
end: selection.end + offset
});
if (entries.length > 0) {
$.each(entries.split(""), function (ndx, entry) {
var keypress = new $.Event("keypress");
keypress.which = entry.charCodeAt(0);
ignorable = false;
EventHandlers.keypressEvent.call(input, keypress);
});
} else {
if (selection.begin === selection.end - 1) {
selection.begin = seekPrevious(selection.begin + 1);
if (selection.begin === selection.end - 1) {
caret(input, selection.begin);
} else {
caret(input, selection.begin, selection.end);
}
}
var keydown = new $.Event("keydown");
keydown.keyCode = opts.numericInput ? Inputmask.keyCode.BACKSPACE : Inputmask.keyCode.DELETE;
EventHandlers.keydownEvent.call(input, keydown);
}
e.preventDefault();
}
}
},
beforeInputEvent: function (e) {
if (e.cancelable) {
var input = this;
switch (e.inputType) {
case "insertText":
$.each(e.data.split(""), function (ndx, entry) {
var keypress = new $.Event("keypress");
keypress.which = entry.charCodeAt(0);
ignorable = false;
EventHandlers.keypressEvent.call(input, keypress);
});
return e.preventDefault();
case "deleteContentBackward":
var keydown = new $.Event("keydown");
keydown.keyCode = Inputmask.keyCode.BACKSPACE;
EventHandlers.keydownEvent.call(input, keydown);
return e.preventDefault();
case "deleteContentForward":
var keydown = new $.Event("keydown");
keydown.keyCode = Inputmask.keyCode.DELETE;
EventHandlers.keydownEvent.call(input, keydown);
return e.preventDefault();
}
}
},
setValueEvent: function (e) {
this.inputmask.refreshValue = false;
var input = this, value = e && e.detail ? e.detail[0] : arguments[1],
value = value || input.inputmask._valueGet(true);
if ($.isFunction(opts.onBeforeMask)) value = opts.onBeforeMask.call(inputmask, value, opts) || value;
value = value.toString().split("");
checkVal(input, true, false, value);
undoValue = getBuffer().join("");
if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input.inputmask._valueGet() === getBufferTemplate().join("")) {
input.inputmask._valueSet("");
}
},
focusEvent: function (e) {
var input = this, nptValue = input.inputmask._valueGet();
if (opts.showMaskOnFocus) {
if (nptValue !== getBuffer().join("")) {
writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
} else if (mouseEnter === false) {
caret(input, seekNext(getLastValidPosition()));
}
}
if (opts.positionCaretOnTab === true && mouseEnter === false) {
EventHandlers.clickEvent.apply(input, [e, true]);
}
undoValue = getBuffer().join("");
},
mouseleaveEvent: function (e) {
var input = this;
mouseEnter = false;
if (opts.clearMaskOnLostFocus && document.activeElement !== input) {
HandleNativePlaceholder(input, originalPlaceholder);
}
},
clickEvent: function (e, tabbed) {
function doRadixFocus(clickPos) {
if (opts.radixPoint !== "") {
var vps = getMaskSet().validPositions;
if (vps[clickPos] === undefined || vps[clickPos].input === getPlaceholder(clickPos)) {
if (clickPos < seekNext(-1)) return true;
var radixPos = $.inArray(opts.radixPoint, getBuffer());
if (radixPos !== -1) {
for (var vp in vps) {
if (radixPos < vp && vps[vp].input !== getPlaceholder(vp)) {
return false;
}
}
return true;
}
}
}
return false;
}
var input = this;
setTimeout(function () {
if (document.activeElement === input) {
var selectedCaret = caret(input);
if (tabbed) {
if (isRTL) {
selectedCaret.end = selectedCaret.begin;
} else {
selectedCaret.begin = selectedCaret.end;
}
}
if (selectedCaret.begin === selectedCaret.end) {
switch (opts.positionCaretOnClick) {
case "none":
break;
case "select":
caret(input, 0, getBuffer().length);
break;
case "ignore":
caret(input, seekNext(getLastValidPosition()));
break;
case "radixFocus":
if (doRadixFocus(selectedCaret.begin)) {
var radixPos = getBuffer().join("").indexOf(opts.radixPoint);
caret(input, opts.numericInput ? seekNext(radixPos) : radixPos);
break;
}
default:
var clickPosition = selectedCaret.begin,
lvclickPosition = getLastValidPosition(clickPosition, true),
lastPosition = seekNext(lvclickPosition);
if (clickPosition < lastPosition) {
caret(input, !isMask(clickPosition, true) && !isMask(clickPosition - 1, true) ? seekNext(clickPosition) : clickPosition);
} else {
var lvp = getMaskSet().validPositions[lvclickPosition],
tt = getTestTemplate(lastPosition, lvp ? lvp.match.locator : undefined, lvp),
placeholder = getPlaceholder(lastPosition, tt.match);
if (placeholder !== "" && getBuffer()[lastPosition] !== placeholder && tt.match.optionalQuantifier !== true && tt.match.newBlockMarker !== true || !isMask(lastPosition, opts.keepStatic) && tt.match.def === placeholder) {
var newPos = seekNext(lastPosition);
if (clickPosition >= newPos || clickPosition === lastPosition) {
lastPosition = newPos;
}
}
caret(input, lastPosition);
}
break;
}
}
}
}, 0);
},
cutEvent: function (e) {
var input = this, $input = $(input), pos = caret(input), ev = e.originalEvent || e;
var clipboardData = window.clipboardData || ev.clipboardData,
clipData = isRTL ? getBuffer().slice(pos.end, pos.begin) : getBuffer().slice(pos.begin, pos.end);
clipboardData.setData("text", isRTL ? clipData.reverse().join("") : clipData.join(""));
if (document.execCommand) document.execCommand("copy");
handleRemove(input, Inputmask.keyCode.DELETE, pos);
writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
},
blurEvent: function (e) {
var $input = $(this), input = this;
if (input.inputmask) {
HandleNativePlaceholder(input, originalPlaceholder);
var nptValue = input.inputmask._valueGet(), buffer = getBuffer().slice();
if (nptValue !== "" || colorMask !== undefined) {
if (opts.clearMaskOnLostFocus) {
if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
buffer = [];
} else {
clearOptionalTail(buffer);
}
}
if (isComplete(buffer) === false) {
setTimeout(function () {
$input.trigger("incomplete");
}, 0);
if (opts.clearIncomplete) {
resetMaskSet();
if (opts.clearMaskOnLostFocus) {
buffer = [];
} else {
buffer = getBufferTemplate().slice();
}
}
}
writeBuffer(input, buffer, undefined, e);
}
if (undoValue !== getBuffer().join("")) {
undoValue = buffer.join("");
$input.trigger("change");
}
}
},
mouseenterEvent: function (e) {
var input = this;
mouseEnter = true;
if (document.activeElement !== input && opts.showMaskOnHover) {
HandleNativePlaceholder(input, (isRTL ? getBuffer().slice().reverse() : getBuffer()).join(""));
}
},
submitEvent: function (e) {
if (undoValue !== getBuffer().join("")) {
$el.trigger("change");
}
if (opts.clearMaskOnLostFocus && getLastValidPosition() === -1 && el.inputmask._valueGet && el.inputmask._valueGet() === getBufferTemplate().join("")) {
el.inputmask._valueSet("");
}
if (opts.clearIncomplete && isComplete(getBuffer()) === false) {
el.inputmask._valueSet("");
}
if (opts.removeMaskOnSubmit) {
el.inputmask._valueSet(el.inputmask.unmaskedvalue(), true);
setTimeout(function () {
writeBuffer(el, getBuffer());
}, 0);
}
},
resetEvent: function (e) {
el.inputmask.refreshValue = true;
setTimeout(function () {
$el.trigger("setvalue");
}, 0);
}
};
function checkVal(input, writeOut, strict, nptvl, initiatingEvent) {
var inputmask = this || input.inputmask, inputValue = nptvl.slice(), charCodes = "", initialNdx = -1,
result = undefined;
function isTemplateMatch(ndx, charCodes) {
var charCodeNdx = getMaskTemplate(true, 0, false).slice(ndx, seekNext(ndx)).join("").replace(/'/g, "").indexOf(charCodes);
return charCodeNdx !== -1 && !isMask(ndx) && (getTest(ndx).match.nativeDef === charCodes.charAt(0) || getTest(ndx).match.fn === null && getTest(ndx).match.nativeDef === "'" + charCodes.charAt(0) || getTest(ndx).match.nativeDef === " " && (getTest(ndx + 1).match.nativeDef === charCodes.charAt(0) || getTest(ndx + 1).match.fn === null && getTest(ndx + 1).match.nativeDef === "'" + charCodes.charAt(0)));
}
resetMaskSet();
if (!strict && opts.autoUnmask !== true) {
var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(""),
matches = inputValue.join("").match(new RegExp("^" + Inputmask.escapeRegex(staticInput), "g"));
if (matches && matches.length > 0) {
inputValue.splice(0, matches.length * staticInput.length);
initialNdx = seekNext(initialNdx);
}
} else {
initialNdx = seekNext(initialNdx);
}
if (initialNdx === -1) {
getMaskSet().p = seekNext(initialNdx);
initialNdx = 0;
} else getMaskSet().p = initialNdx;
inputmask.caretPos = {
begin: initialNdx
};
$.each(inputValue, function (ndx, charCode) {
if (charCode !== undefined) {
if (getMaskSet().validPositions[ndx] === undefined && inputValue[ndx] === getPlaceholder(ndx) && isMask(ndx, true) && isValid(ndx, inputValue[ndx], true, undefined, undefined, true) === false) {
getMaskSet().p++;
} else {
var keypress = new $.Event("_checkval");
keypress.which = charCode.charCodeAt(0);
charCodes += charCode;
var lvp = getLastValidPosition(undefined, true);
if (!isTemplateMatch(initialNdx, charCodes)) {
result = EventHandlers.keypressEvent.call(input, keypress, true, false, strict, inputmask.caretPos.begin);
if (result) {
initialNdx = inputmask.caretPos.begin + 1;
charCodes = "";
}
} else {
result = EventHandlers.keypressEvent.call(input, keypress, true, false, strict, lvp + 1);
}
if (result) {
writeBuffer(undefined, getBuffer(), result.forwardPosition, keypress, false);
inputmask.caretPos = {
begin: result.forwardPosition,
end: result.forwardPosition
};
}
}
}
});
if (writeOut) writeBuffer(input, getBuffer(), result ? result.forwardPosition : undefined, initiatingEvent || new $.Event("checkval"), initiatingEvent && initiatingEvent.type === "input");
}
function unmaskedvalue(input) {
if (input) {
if (input.inputmask === undefined) {
return input.value;
}
if (input.inputmask && input.inputmask.refreshValue) {
EventHandlers.setValueEvent.call(input);
}
}
var umValue = [], vps = getMaskSet().validPositions;
for (var pndx in vps) {
if (vps[pndx].match && vps[pndx].match.fn != null) {
umValue.push(vps[pndx].input);
}
}
var unmaskedValue = umValue.length === 0 ? "" : (isRTL ? umValue.reverse() : umValue).join("");
if ($.isFunction(opts.onUnMask)) {
var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join("");
unmaskedValue = opts.onUnMask.call(inputmask, bufferValue, unmaskedValue, opts);
}
return unmaskedValue;
}
function caret(input, begin, end, notranslate) {
function translatePosition(pos) {
if (isRTL && typeof pos === "number" && (!opts.greedy || opts.placeholder !== "") && el) {
pos = el.inputmask._valueGet().length - pos;
}
return pos;
}
var range;
if (begin !== undefined) {
if ($.isArray(begin)) {
end = isRTL ? begin[0] : begin[1];
begin = isRTL ? begin[1] : begin[0];
}
if (begin.begin !== undefined) {
end = isRTL ? begin.begin : begin.end;
begin = isRTL ? begin.end : begin.begin;
}
if (typeof begin === "number") {
begin = notranslate ? begin : translatePosition(begin);
end = notranslate ? end : translatePosition(end);
end = typeof end == "number" ? end : begin;
var scrollCalc = parseInt(((input.ownerDocument.defaultView || window).getComputedStyle ? (input.ownerDocument.defaultView || window).getComputedStyle(input, null) : input.currentStyle).fontSize) * end;
input.scrollLeft = scrollCalc > input.scrollWidth ? scrollCalc : 0;
input.inputmask.caretPos = {
begin: begin,
end: end
};
if (input === document.activeElement) {
if ("selectionStart" in input) {
input.selectionStart = begin;
input.selectionEnd = end;
} else if (window.getSelection) {
range = document.createRange();
if (input.firstChild === undefined || input.firstChild === null) {
var textNode = document.createTextNode("");
input.appendChild(textNode);
}
range.setStart(input.firstChild, begin < input.inputmask._valueGet().length ? begin : input.inputmask._valueGet().length);
range.setEnd(input.firstChild, end < input.inputmask._valueGet().length ? end : input.inputmask._valueGet().length);
range.collapse(true);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (input.createTextRange) {
range = input.createTextRange();
range.collapse(true);
range.moveEnd("character", end);
range.moveStart("character", begin);
range.select();
}
renderColorMask(input, {
begin: begin,
end: end
});
}
}
} else {
if ("selectionStart" in input) {
begin = input.selectionStart;
end = input.selectionEnd;
} else if (window.getSelection) {
range = window.getSelection().getRangeAt(0);
if (range.commonAncestorContainer.parentNode === input || range.commonAncestorContainer === input) {
begin = range.startOffset;
end = range.endOffset;
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
begin = 0 - range.duplicate().moveStart("character", -input.inputmask._valueGet().length);
end = begin + range.text.length;
}
return {
begin: notranslate ? begin : translatePosition(begin),
end: notranslate ? end : translatePosition(end)
};
}
}
function determineLastRequiredPosition(returnDefinition) {
var buffer = getMaskTemplate(true, getLastValidPosition(), true, true), bl = buffer.length, pos,
lvp = getLastValidPosition(), positions = {}, lvTest = getMaskSet().validPositions[lvp],
ndxIntlzr = lvTest !== undefined ? lvTest.locator.slice() : undefined, testPos;
for (pos = lvp + 1; pos < buffer.length; pos++) {
testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
ndxIntlzr = testPos.locator.slice();
positions[pos] = $.extend(true, {}, testPos);
}
var lvTestAlt = lvTest && lvTest.alternation !== undefined ? lvTest.locator[lvTest.alternation] : undefined;
for (pos = bl - 1; pos > lvp; pos--) {
testPos = positions[pos];
if ((testPos.match.optionality || testPos.match.optionalQuantifier && testPos.match.newBlockMarker || lvTestAlt && (lvTestAlt !== positions[pos].locator[lvTest.alternation] && testPos.match.fn != null || testPos.match.fn === null && testPos.locator[lvTest.alternation] && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAlt.toString().split(",")) && getTests(pos)[0].def !== "")) && buffer[pos] === getPlaceholder(pos, testPos.match)) {
bl--;
} else break;
}
return returnDefinition ? {
l: bl,
def: positions[bl] ? positions[bl].match : undefined
} : bl;
}
function clearOptionalTail(buffer) {
buffer.length = 0;
var template = getMaskTemplate(true, 0, true, undefined, true), lmnt, validPos;
while (lmnt = template.shift(), lmnt !== undefined) buffer.push(lmnt);
return buffer;
}
function isComplete(buffer) {
if ($.isFunction(opts.isComplete)) return opts.isComplete(buffer, opts);
if (opts.repeat === "*") return undefined;
var complete = false, lrp = determineLastRequiredPosition(true), aml = seekPrevious(lrp.l);
if (lrp.def === undefined || lrp.def.newBlockMarker || lrp.def.optionality || lrp.def.optionalQuantifier) {
complete = true;
for (var i = 0; i <= aml; i++) {
var test = getTestTemplate(i).match;
if (test.fn !== null && getMaskSet().validPositions[i] === undefined && test.optionality !== true && test.optionalQuantifier !== true || test.fn === null && buffer[i] !== getPlaceholder(i, test)) {
complete = false;
break;
}
}
}
return complete;
}
function handleRemove(input, k, pos, strict, fromIsValid) {
if (opts.numericInput || isRTL) {
if (k === Inputmask.keyCode.BACKSPACE) {
k = Inputmask.keyCode.DELETE;
} else if (k === Inputmask.keyCode.DELETE) {
k = Inputmask.keyCode.BACKSPACE;
}
if (isRTL) {
var pend = pos.end;
pos.end = pos.begin;
pos.begin = pend;
}
}
if (k === Inputmask.keyCode.BACKSPACE && pos.end - pos.begin < 1) {
pos.begin = seekPrevious(pos.begin);
if (getMaskSet().validPositions[pos.begin] !== undefined && getMaskSet().validPositions[pos.begin].input === opts.groupSeparator) {
pos.begin--;
}
} else if (k === Inputmask.keyCode.DELETE && pos.begin === pos.end) {
pos.end = isMask(pos.end, true) && (getMaskSet().validPositions[pos.end] && getMaskSet().validPositions[pos.end].input !== opts.radixPoint) ? pos.end + 1 : seekNext(pos.end) + 1;
if (getMaskSet().validPositions[pos.begin] !== undefined && getMaskSet().validPositions[pos.begin].input === opts.groupSeparator) {
pos.end++;
}
}
revalidateMask(pos);
if (strict !== true && opts.keepStatic !== false || opts.regex !== null) {
var result = alternate(true);
if (result) {
var newPos = result.caret !== undefined ? result.caret : result.pos ? seekNext(result.pos.begin ? result.pos.begin : result.pos) : getLastValidPosition(-1, true);
if (k !== Inputmask.keyCode.DELETE || pos.begin > newPos) {
pos.begin == newPos;
}
}
}
var lvp = getLastValidPosition(pos.begin, true);
if (lvp < pos.begin || pos.begin === -1) {
getMaskSet().p = seekNext(lvp);
} else if (strict !== true) {
getMaskSet().p = pos.begin;
if (fromIsValid !== true) {
while (getMaskSet().p < lvp && getMaskSet().validPositions[getMaskSet().p] === undefined) {
getMaskSet().p++;
}
}
}
}
function initializeColorMask(input) {
var computedStyle = (input.ownerDocument.defaultView || window).getComputedStyle(input, null);
function findCaretPos(clientx) {
var e = document.createElement("span"), caretPos;
for (var style in computedStyle) {
if (isNaN(style) && style.indexOf("font") !== -1) {
e.style[style] = computedStyle[style];
}
}
e.style.textTransform = computedStyle.textTransform;
e.style.letterSpacing = computedStyle.letterSpacing;
e.style.position = "absolute";
e.style.height = "auto";
e.style.width = "auto";
e.style.visibility = "hidden";
e.style.whiteSpace = "nowrap";
document.body.appendChild(e);
var inputText = input.inputmask._valueGet(), previousWidth = 0, itl;
for (caretPos = 0, itl = inputText.length; caretPos <= itl; caretPos++) {
e.innerHTML += inputText.charAt(caretPos) || "_";
if (e.offsetWidth >= clientx) {
var offset1 = clientx - previousWidth;
var offset2 = e.offsetWidth - clientx;
e.innerHTML = inputText.charAt(caretPos);
offset1 -= e.offsetWidth / 3;
caretPos = offset1 < offset2 ? caretPos - 1 : caretPos;
break;
}
previousWidth = e.offsetWidth;
}
document.body.removeChild(e);
return caretPos;
}
var template = document.createElement("div");
template.style.width = computedStyle.width;
template.style.textAlign = computedStyle.textAlign;
colorMask = document.createElement("div");
input.inputmask.colorMask = colorMask;
colorMask.className = "im-colormask";
input.parentNode.insertBefore(colorMask, input);
input.parentNode.removeChild(input);
colorMask.appendChild(input);
colorMask.appendChild(template);
input.style.left = template.offsetLeft + "px";
$(colorMask).on("mouseleave", function (e) {
return EventHandlers.mouseleaveEvent.call(input, [e]);
});
$(colorMask).on("mouseenter", function (e) {
return EventHandlers.mouseenterEvent.call(input, [e]);
});
$(colorMask).on("click", function (e) {
caret(input, findCaretPos(e.clientX));
return EventHandlers.clickEvent.call(input, [e]);
});
}
function renderColorMask(input, caretPos, clear) {
var maskTemplate = [], isStatic = false, test, testPos, ndxIntlzr, pos = 0;
function setEntry(entry) {
if (entry === undefined) entry = "";
if (!isStatic && (test.fn === null || testPos.input === undefined)) {
isStatic = true;
maskTemplate.push("<span class='im-static'>" + entry);
} else if (isStatic && (test.fn !== null && testPos.input !== undefined || test.def === "")) {
isStatic = false;
var mtl = maskTemplate.length;
maskTemplate[mtl - 1] = maskTemplate[mtl - 1] + "</span>";
maskTemplate.push(entry);
} else maskTemplate.push(entry);
}
function setCaret() {
if (document.activeElement === input) {
maskTemplate.splice(caretPos.begin, 0, caretPos.begin === caretPos.end || caretPos.end > getMaskSet().maskLength ? '<mark class="im-caret" style="border-right-width: 1px;border-right-style: solid;">' : '<mark class="im-caret-select">');
maskTemplate.splice(caretPos.end + 1, 0, "</mark>");
}
}
if (colorMask !== undefined) {
var buffer = getBuffer();
if (caretPos === undefined) {
caretPos = caret(input);
} else if (caretPos.begin === undefined) {
caretPos = {
begin: caretPos,
end: caretPos
};
}
if (clear !== true) {
var lvp = getLastValidPosition();
do {
if (getMaskSet().validPositions[pos]) {
testPos = getMaskSet().validPositions[pos];
test = testPos.match;
ndxIntlzr = testPos.locator.slice();
setEntry(buffer[pos]);
} else {
testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
test = testPos.match;
ndxIntlzr = testPos.locator.slice();
if (opts.jitMasking === false || pos < lvp || typeof opts.jitMasking === "number" && isFinite(opts.jitMasking) && opts.jitMasking > pos) {
setEntry(getPlaceholder(pos, test));
} else isStatic = false;
}
pos++;
} while ((maxLength === undefined || pos < maxLength) && (test.fn !== null || test.def !== "") || lvp > pos || isStatic);
if (isStatic) setEntry();
setCaret();
}
var template = colorMask.getElementsByTagName("div")[0];
template.innerHTML = maskTemplate.join("");
input.inputmask.positionColorMask(input, template);
}
}
function mask(elem) {
function isElementTypeSupported(input, opts) {
function patchValueProperty(npt) {
var valueGet;
var valueSet;
function patchValhook(type) {
if ($.valHooks && ($.valHooks[type] === undefined || $.valHooks[type].inputmaskpatch !== true)) {
var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) {
return elem.value;
};
var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
elem.value = value;
return elem;
};
$.valHooks[type] = {
get: function (elem) {
if (elem.inputmask) {
if (elem.inputmask.opts.autoUnmask) {
return elem.inputmask.unmaskedvalue();
} else {
var result = valhookGet(elem);
return getLastValidPosition(undefined, undefined, elem.inputmask.maskset.validPositions) !== -1 || opts.nullable !== true ? result : "";
}
} else return valhookGet(elem);
},
set: function (elem, value) {
var $elem = $(elem), result;
result = valhookSet(elem, value);
if (elem.inputmask) {
$elem.trigger("setvalue", [value]);
}
return result;
},
inputmaskpatch: true
};
}
}
function getter() {
if (this.inputmask) {
return this.inputmask.opts.autoUnmask ? this.inputmask.unmaskedvalue() : getLastValidPosition() !== -1 || opts.nullable !== true ? document.activeElement === this && opts.clearMaskOnLostFocus ? (isRTL ? clearOptionalTail(getBuffer().slice()).reverse() : clearOptionalTail(getBuffer().slice())).join("") : valueGet.call(this) : "";
} else return valueGet.call(this);
}
function setter(value) {
valueSet.call(this, value);
if (this.inputmask) {
$(this).trigger("setvalue", [value]);
}
}
function installNativeValueSetFallback(npt) {
EventRuler.on(npt, "mouseenter", function (event) {
var $input = $(this), input = this, value = input.inputmask._valueGet();
if (value !== getBuffer().join("")) {
$input.trigger("setvalue");
}
});
}
if (!npt.inputmask.__valueGet) {
if (opts.noValuePatching !== true) {
if (Object.getOwnPropertyDescriptor) {
if (typeof Object.getPrototypeOf !== "function") {
Object.getPrototypeOf = typeof "test".__proto__ === "object" ? function (object) {
return object.__proto__;
} : function (object) {
return object.constructor.prototype;
};
}
var valueProperty = Object.getPrototypeOf ? Object.getOwnPropertyDescriptor(Object.getPrototypeOf(npt), "value") : undefined;
if (valueProperty && valueProperty.get && valueProperty.set) {
valueGet = valueProperty.get;
valueSet = valueProperty.set;
Object.defineProperty(npt, "value", {
get: getter,
set: setter,
configurable: true
});
} else if (npt.tagName !== "INPUT") {
valueGet = function () {
return this.textContent;
};
valueSet = function (value) {
this.textContent = value;
};
Object.defineProperty(npt, "value", {
get: getter,
set: setter,
configurable: true
});
}
} else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
valueGet = npt.__lookupGetter__("value");
valueSet = npt.__lookupSetter__("value");
npt.__defineGetter__("value", getter);
npt.__defineSetter__("value", setter);
}
npt.inputmask.__valueGet = valueGet;
npt.inputmask.__valueSet = valueSet;
}
npt.inputmask._valueGet = function (overruleRTL) {
return isRTL && overruleRTL !== true ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el);
};
npt.inputmask._valueSet = function (value, overruleRTL) {
valueSet.call(this.el, value === null || value === undefined ? "" : overruleRTL !== true && isRTL ? value.split("").reverse().join("") : value);
};
if (valueGet === undefined) {
valueGet = function () {
return this.value;
};
valueSet = function (value) {
this.value = value;
};
patchValhook(npt.type);
installNativeValueSetFallback(npt);
}
}
}
var elementType = input.getAttribute("type");
var isSupported = input.tagName === "INPUT" && $.inArray(elementType, opts.supportsInputType) !== -1 || input.isContentEditable || input.tagName === "TEXTAREA";
if (!isSupported) {
if (input.tagName === "INPUT") {
var el = document.createElement("input");
el.setAttribute("type", elementType);
isSupported = el.type === "text";
el = null;
} else isSupported = "partial";
}
if (isSupported !== false) {
patchValueProperty(input);
} else input.inputmask = undefined;
return isSupported;
}
EventRuler.off(elem);
var isSupported = isElementTypeSupported(elem, opts);
if (isSupported !== false) {
el = elem;
$el = $(el);
originalPlaceholder = el.placeholder;
maxLength = el !== undefined ? el.maxLength : undefined;
if (maxLength === -1) maxLength = undefined;
if (opts.colorMask === true) {
initializeColorMask(el);
}
if (mobile) {
if ("inputMode" in el) {
el.inputmode = opts.inputmode;
el.setAttribute("inputmode", opts.inputmode);
}
if (opts.disablePredictiveText === true) {
if ("autocorrect" in el) {
el.autocorrect = false;
} else {
if (opts.colorMask !== true) {
initializeColorMask(el);
}
el.type = "password";
}
}
}
if (isSupported === true) {
el.setAttribute("im-insert", opts.insertMode);
EventRuler.on(el, "submit", EventHandlers.submitEvent);
EventRuler.on(el, "reset", EventHandlers.resetEvent);
EventRuler.on(el, "blur", EventHandlers.blurEvent);
EventRuler.on(el, "focus", EventHandlers.focusEvent);
if (opts.colorMask !== true) {
EventRuler.on(el, "click", EventHandlers.clickEvent);
EventRuler.on(el, "mouseleave", EventHandlers.mouseleaveEvent);
EventRuler.on(el, "mouseenter", EventHandlers.mouseenterEvent);
}
EventRuler.on(el, "paste", EventHandlers.pasteEvent);
EventRuler.on(el, "cut", EventHandlers.cutEvent);
EventRuler.on(el, "complete", opts.oncomplete);
EventRuler.on(el, "incomplete", opts.onincomplete);
EventRuler.on(el, "cleared", opts.oncleared);
if (!mobile && opts.inputEventOnly !== true) {
EventRuler.on(el, "keydown", EventHandlers.keydownEvent);
EventRuler.on(el, "keypress", EventHandlers.keypressEvent);
} else {
el.removeAttribute("maxLength");
}
EventRuler.on(el, "input", EventHandlers.inputFallBackEvent);
EventRuler.on(el, "beforeinput", EventHandlers.beforeInputEvent);
}
EventRuler.on(el, "setvalue", EventHandlers.setValueEvent);
undoValue = getBufferTemplate().join("");
if (el.inputmask._valueGet(true) !== "" || opts.clearMaskOnLostFocus === false || document.activeElement === el) {
var initialValue = $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(inputmask, el.inputmask._valueGet(true), opts) || el.inputmask._valueGet(true) : el.inputmask._valueGet(true);
if (initialValue !== "") checkVal(el, true, false, initialValue.split(""));
var buffer = getBuffer().slice();
undoValue = buffer.join("");
if (isComplete(buffer) === false) {
if (opts.clearIncomplete) {
resetMaskSet();
}
}
if (opts.clearMaskOnLostFocus && document.activeElement !== el) {
if (getLastValidPosition() === -1) {
buffer = [];
} else {
clearOptionalTail(buffer);
}
}
if (opts.clearMaskOnLostFocus === false || opts.showMaskOnFocus && document.activeElement === el || el.inputmask._valueGet(true) !== "") writeBuffer(el, buffer);
if (document.activeElement === el) {
caret(el, seekNext(getLastValidPosition()));
}
}
}
}
var valueBuffer;
if (actionObj !== undefined) {
switch (actionObj.action) {
case "isComplete":
el = actionObj.el;
return isComplete(getBuffer());
case "unmaskedvalue":
if (el === undefined || actionObj.value !== undefined) {
valueBuffer = actionObj.value;
valueBuffer = ($.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(inputmask, valueBuffer, opts) || valueBuffer : valueBuffer).split("");
checkVal.call(this, undefined, false, false, valueBuffer);
if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite.call(inputmask, undefined, getBuffer(), 0, opts);
}
return unmaskedvalue(el);
case "mask":
mask(el);
break;
case "format":
valueBuffer = ($.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(inputmask, actionObj.value, opts) || actionObj.value : actionObj.value).split("");
checkVal.call(this, undefined, true, false, valueBuffer);
if (actionObj.metadata) {
return {
value: isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join(""),
metadata: maskScope.call(this, {
action: "getmetadata"
}, maskset, opts)
};
}
return isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join("");
case "isValid":
if (actionObj.value) {
valueBuffer = actionObj.value.split("");
checkVal.call(this, undefined, true, true, valueBuffer);
} else {
actionObj.value = getBuffer().join("");
}
var buffer = getBuffer();
var rl = determineLastRequiredPosition(), lmib = buffer.length - 1;
for (; lmib > rl; lmib--) {
if (isMask(lmib)) break;
}
buffer.splice(rl, lmib + 1 - rl);
return isComplete(buffer) && actionObj.value === getBuffer().join("");
case "getemptymask":
return getBufferTemplate().join("");
case "remove":
if (el && el.inputmask) {
$.data(el, "_inputmask_opts", null);
$el = $(el);
el.inputmask._valueSet(opts.autoUnmask ? unmaskedvalue(el) : el.inputmask._valueGet(true));
EventRuler.off(el);
if (el.inputmask.colorMask) {
colorMask = el.inputmask.colorMask;
colorMask.removeChild(el);
colorMask.parentNode.insertBefore(el, colorMask);
colorMask.parentNode.removeChild(colorMask);
}
var valueProperty;
if (Object.getOwnPropertyDescriptor && Object.getPrototypeOf) {
valueProperty = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), "value");
if (valueProperty) {
if (el.inputmask.__valueGet) {
Object.defineProperty(el, "value", {
get: el.inputmask.__valueGet,
set: el.inputmask.__valueSet,
configurable: true
});
}
}
} else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
if (el.inputmask.__valueGet) {
el.__defineGetter__("value", el.inputmask.__valueGet);
el.__defineSetter__("value", el.inputmask.__valueSet);
}
}
el.inputmask = undefined;
}
return el;
break;
case "getmetadata":
if ($.isArray(maskset.metadata)) {
var maskTarget = getMaskTemplate(true, 0, false).join("");
$.each(maskset.metadata, function (ndx, mtdt) {
if (mtdt.mask === maskTarget) {
maskTarget = mtdt;
return false;
}
});
return maskTarget;
}
return maskset.metadata;
}
}
}
return Inputmask;
});
|
const { AsyncParser } = require('json2csv');
const fields = ['field1', 'field2', 'field3'];
const opts = { fields };
const transformOpts = { highWaterMark: 8192 };
const asyncParser = new AsyncParser(opts, transformOpts);
let csv = '';
asyncParser.processor
.on('data', chunk => (csv += chunk.toString()))
.on('end', () => console.log(csv))
.on('error', err => console.error(err));
// You can also listen for events on the conversion and see how the header or the lines are coming out.
asyncParser.transform
.on('header', header => console.log(header))
.on('line', line => console.log(line))
.on('error', err => console.log(err));
asyncParser.input.push(data); // This data might come from an HTTP request, etc.
asyncParser.input.push(null); // Sending `null` to a stream signal that no more data is expected and ends it.
|
import { SET_SEND_TYPING } from '../actions/setSendTyping';
import { SET_SEND_TYPING_INDICATOR } from '../actions/setSendTypingIndicator';
const DEFAULT_STATE = false;
export default function (state = DEFAULT_STATE, { payload, type }) {
switch (type) {
// TODO: [P3] Take this deprecation code out when releasing on or after 2020 January 13
case SET_SEND_TYPING:
console.warn('Web Chat: "sendTyping" has been renamed to "sendTypingIndicator". Please use "sendTypingIndicator" instead. This deprecation migration will be removed on or after January 13 2020.');
state = payload.sendTyping;
break;
case SET_SEND_TYPING_INDICATOR:
state = payload.sendTypingIndicator;
break;
default: break;
}
return state;
}
|
// TODO consider replacing this with a generator such as:
// https://github.com/CVarisco/create-component-app
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp-promise');
const { version } = require('../lerna.json');
const componentFolderName = process.argv[2];
const componentName = `${componentFolderName
.charAt(0)
.toUpperCase()}${componentFolderName
.slice(1)
.replace(/-([a-z])/g, g => g[1].toUpperCase())}`;
const folderName = `./components/${componentFolderName}`;
const writeFile = (filename, contents) => {
const pathName = path.join(
filename === 'package.json' ? folderName : `${folderName}/src`,
filename,
);
fs.writeFile(pathName, `${contents}`, err => {
if (err) {
return console.log(err);
}
console.log(`Created file: ${pathName}`);
return false;
});
return false;
};
// write packageJson file
const packageJson = () => {
const filename = 'package.json';
// TODO: this should pull in devDependencies version numbers from package.json
// in the root or from another component so it doesn't need to be maintained.
// also I'm not sure we need the storybook addons for all components,
// can be added manually per component perhaps.
const contents = `{
"name": "@govuk-frederic/${componentFolderName}",
"version": "${version}",
"dependencies": {
"@govuk-react/lib": "^0.6.0-alpha.1",
"govuk-colours": "^1.0.3"
},
"peerDependencies": {
"react": ">=16.2.0",
"styled-components": ">=4"
},
"scripts": {
"build": "yarn build:lib && yarn build:es",
"build:lib": "rimraf lib && babel src -d lib --source-maps --config-file ../../babel.config.js",
"build:es": "rimraf es && cross-env BABEL_ENV=es babel src -d es --source-maps --config-file ../../babel.config.js",
"docs": "doc-component ./lib/index.js ./README.md"
},
"main": "lib/index.js",
"module": "es/index.js",
"author": "Steve Sims",
"license": "MIT",
"homepage": "https://github.com/stevesims/govuk-frederic/tree/master/components/${componentFolderName}",
"description": "govuk-frederic ${componentName} component.",
"private": false,
"publishConfig": {
"access": "public"
}
}
`;
writeFile(filename, contents);
};
// write test.js file
const testScript = () => {
const filename = 'test.js';
const contents = `import React from 'react';
import { mount } from 'enzyme';
import Example from './fixtures';
describe('${componentName}', () => {
it('matches snapshot', () => {
expect(mount(<Example />)).toMatchSnapshot('${componentName}');
});
});
`;
writeFile(filename, contents);
};
// write stories.js file
const storiesScript = () => {
const filename = 'stories.js';
const contents = `import { storiesOf } from '@storybook/react';
import { WithDocsCustom } from '@govuk-react/storybook-components';
import ${componentName} from './fixtures';
import ReadMe from '../README.md';
const stories = storiesOf('${componentName}', module);
stories.addDecorator(WithDocsCustom(ReadMe));
stories.add('Component default', ${componentName});
`;
writeFile(filename, contents);
};
// write fixtures.js file
const exampleScript = () => {
const filename = 'fixtures.js';
const contents = `import React from 'react';
import ${componentName} from '.';
export default () => <${componentName}>${componentName} example</${componentName}>;
`;
writeFile(filename, contents);
};
// write index.js file
const indexScript = () => {
const filename = 'index.js';
const contents = `import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { spacing, typography } from '@govuk-react/lib';
const ${componentName} = styled('div')(
typography.font({ size: 16 }),
spacing.withWhiteSpace(),
);
/**
*
* ### Usage
*
* Simple
* \`\`\`jsx
* <${componentName}>Example</${componentName}>
* \`\`\`
*
* ### References
* - TODO: INSERT A REFERENCE TO EXTERNAL URL IF POSSIBLE
*/
const ${componentName}Documented = props => <${componentName} {...props} />;
${componentName}Documented.propTypes = {
children: PropTypes.node.isRequired,
};
${componentName}.propTypes = ${componentName}Documented.propTypes;
export { ${componentName}Documented };
export default ${componentName};
`;
writeFile(filename, contents);
};
const init = () => {
if (fs.existsSync(path.join(folderName))) {
console.log(`❗️❗️ The component '${componentName}' already exists ❗️❗️
Please use a different name or delete the existing folder 🆗`);
return false;
}
mkdirp(`${folderName}/src`).then(() => {
packageJson();
testScript();
storiesScript();
exampleScript();
indexScript();
console.log(`✅ The component '${componentName}' was created successfully`);
});
return false;
};
init();
|
AJS.toInit(function() {
var baseUrl = AJS.contextPath();
function populateForm() {
AJS.$.ajax({
url: baseUrl + "/rest/buglink-admin/1.0/",
dataType: "json",
success: function(config) {
AJS.$("#headerText").attr("value", config.header);
AJS.$("#regex").attr("value", config.regex);
AJS.$("#urlTemplate").attr("value", config.urlTemplate);
}
});
}
function updateConfig() {
var data = {
header: AJS.$("#headerText").attr("value"),
regex: AJS.$("#regex").attr("value"),
urlTemplate: AJS.$("#urlTemplate").attr("value")
}
AJS.$.ajax({
url: baseUrl + "/rest/buglink-admin/1.0/",
type: "PUT",
contentType: "application/json",
data: JSON.stringify(data),
processData: false,
success: function() {
AJS.messages.success({
title: "Saved!",
fadeout: true
})
}
});
}
populateForm();
AJS.$("#admin").submit(function(e) {
e.preventDefault();
updateConfig();
});
});
|
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import ADB from '../..';
import path from 'path';
import { fs, util } from 'appium-support';
import { rootDir } from '../../lib/helpers.js';
// All paths below assume tests run under /build/test/ so paths are relative from
// that directory.
const contactManagerPath = path.resolve(rootDir, 'test',
'fixtures', 'ContactManager.apk'),
contactMangerSelendroidPath = path.resolve(rootDir, 'test',
'fixtures', 'ContactManager-selendroid.apk'),
tmpDir = path.resolve(rootDir, 'test', 'temp'),
srcManifest = path.resolve(rootDir, 'test', 'fixtures',
'selendroid', 'AndroidManifest.xml'),
serverPath = path.resolve(rootDir, 'test', 'fixtures',
'selendroid', 'selendroid.apk');
chai.use(chaiAsPromised);
describe('Android-manifest', async function () {
let adb;
before(async function () {
adb = await ADB.createADB();
});
it('packageAndLaunchActivityFromManifest should parse package and Activity', async function () {
let {apkPackage, apkActivity} = await adb.packageAndLaunchActivityFromManifest(contactManagerPath);
apkPackage.should.equal('com.example.android.contactmanager');
apkActivity.should.equal('com.example.android.contactmanager.ContactManager');
});
it('hasInternetPermissionFromManifest should be true', async function () {
let flag = await adb.hasInternetPermissionFromManifest(contactMangerSelendroidPath);
flag.should.be.true;
});
it('hasInternetPermissionFromManifest should be false', async function () {
let flag = await adb.hasInternetPermissionFromManifest(contactManagerPath);
flag.should.be.false;
});
// TODO fix this test
it.skip('should compile and insert manifest', async () => {
let appPackage = 'com.example.android.contactmanager',
newServerPath = path.resolve(tmpDir, `selendroid.${appPackage}.apk`),
newPackage = 'com.example.android.contactmanager.selendroid',
dstDir = path.resolve(tmpDir, appPackage),
dstManifest = path.resolve(dstDir, 'AndroidManifest.xml');
// deleting temp directory if present
try {
await fs.rimraf(tmpDir);
} catch (e) {
console.log(`Unable to delete temp directory. It might not be present. ${e.message}`); // eslint-disable-line no-console
}
await fs.mkdir(tmpDir);
await fs.mkdir(dstDir);
await fs.writeFile(dstManifest, await fs.readFile(srcManifest, "utf8"), "utf8");
await adb.compileManifest(dstManifest, newPackage, appPackage);
(await util.fileExists(dstManifest)).should.be.true;
await adb.insertManifest(dstManifest, serverPath, newServerPath);
(await util.fileExists(newServerPath)).should.be.true;
// deleting temp directory
try {
await fs.rimraf(tmpDir);
} catch (e) {
console.log(`Unable to delete temp directory. It might not be present. ${e.message}`); // eslint-disable-line no-console
}
});
});
describe.skip('Android-manifest To be implemented methods', function () {
it('should return correct processFromManifest', async function () { });
});
|
import HttpStatus from 'http-status-codes';
import cloudWatchLogs from '../services/logger/logger_messages';
import UserModel from'../models/user';
import { model as User } from '../models/user';
const TYPE = 'token';
exports.removeToken = (req, res, done) => {
const token = req.header('Authorization');
UserModel.findUserByTokenQuery(token).exec((err, user) => {
if (err) {
cloudWatchLogs.LogMongoError(err);
res.status(HttpStatus.INTERNAL_SERVER_ERROR).send({message: err});
}
if (user === null) {
cloudWatchLogs.LogNotFoundError(err);
return res.status(HttpStatus.NOT_FOUND).send({message: 'Token no longer valid'});
}
let profile = new User();
profile = user;
if (profile.access_token)
profile.access_token = '';
profile.save((err, result) => {
if (err) {
cloudWatchLogs.LogMongoError(err);
res.status(HttpStatus.INTERNAL_SERVER_ERROR).send({message: err});
}
cloudWatchLogs.LogSuccessfullDelete(TYPE);
return done(result);
});
});
}
|
const request = require('request');
const config = require('./config');
const debug = require('debug')('lookup');
const Bottleneck = require('bottleneck');
/* Create Bottleneck limiter for HTTP lookups with limits defined in config */
const limiter = new Bottleneck({
minTime: config.lookups.HTTP.minTime,
maxConcurrent: config.lookups.HTTP.maxConcurrent
});
/* Do a URL lookup */
module.exports.lookup = limiter.wrap(url => {
return new Promise(resolve => {
debug('Requesting ' + url + '...');
request({
url: url,
timeout: config.lookups.HTTP.timeoutAfter,
followAllRedirects: true,
maxRedirects: 5
}, (err, response, body) => {
if(err) resolve(undefined);
else resolve(response);
});
});
});
/* Retrieve latest VirusTotal report (no API key required) */
module.exports.getURLScan = (url) => {
return new Promise((resolve, reject) => {
request('https://urlscan.io/api/v1/search/?q=domain%3A' + url, { json: true }, (err, response, body) => {
if(err) {
reject(err);
} else {
resolve(body)
}
});
});
}
/* Retrieve Google SafeBrowsing status for URL */
module.exports.getGoogleSafeBrowsing = (url) => {
return new Promise((resolve,reject) => {
debug("Google SafeBrowsing: %o",url);
request({
url: 'https://safebrowsing.googleapis.com/v4/threatMatches:find?key=' + encodeURIComponent(config.apiKeys.Google_SafeBrowsing),
method: 'POST',
headers: {
"Content-Type": "application/json"
},
json: {
client: {
clientId: "EtherScamDB",
clientVersion: "3.0.0"
},
threatInfo: {
threatTypes: ["THREAT_TYPE_UNSPECIFIED", "MALWARE", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE", "POTENTIALLY_HARMFUL_APPLICATION"],
platformTypes: ["PLATFORM_TYPE_UNSPECIFIED","WINDOWS","LINUX","ANDROID","OSX","IOS","ANY_PLATFORM","ALL_PLATFORMS","CHROME"],
threatEntryTypes: ["THREAT_ENTRY_TYPE_UNSPECIFIED", "URL", "EXECUTABLE"],
threatEntries: [{
url: url
}]
}
}
}, (err, response, body) => {
debug("%s returned %s %o",url,((response || {}).statusCode || -1),body);
if(err) {
reject(err);
} else if(response.statusCode != 200) {
reject("Google SafeBrowsing returned an invalid status code");
} else if(body && body.matches && body.matches[0]) {
resolve(body.matches[0]);
} else {
resolve(false);
}
});
});
}
/* Retrieve latest VirusTotal report */
module.exports.getVirusTotal = (url) => {
return new Promise((resolve,reject) => {
request({
uri: 'https://www.virustotal.com/vtapi/v2/url/report?apikey=' + encodeURIComponent(config.apiKeys.VirusTotal) + '&resource=' + url,
method: 'GET',
json: true
}, (err, response, body) => {
if(err) {
reject(err);
} else if(response.statusCode != 200) {
reject("VirusTotal returned an invalid status code");
} else if(body.response_code == 0) {
reject("VirusTotal returned an invalid internal status code");
} else {
resolve(body);
}
});
});
}
|
import {
StateMachine
} from "./chunk-4X2SZKK7.js";
import {
queueMutable
} from "./chunk-3GOS4PSR.js";
import {
string
} from "./chunk-ZSQYTL5I.js";
import {
continuously,
retry,
waitFor
} from "./chunk-MLUQT4HB.js";
import {
indexOfCharCode,
omitChars,
splitByLength
} from "./chunk-OE2F6QKM.js";
import {
SimpleEventEmitter
} from "./chunk-R7MIQL7F.js";
import {
__export,
__publicField
} from "./chunk-6SYKIMQH.js";
// src/io/index.ts
var io_exports = {};
__export(io_exports, {
Bluetooth: () => NordicBleDevice_exports,
Camera: () => Camera_exports,
Espruino: () => EspruinoDevice_exports,
Serial: () => Serial_exports
});
// src/io/NordicBleDevice.ts
var NordicBleDevice_exports = {};
__export(NordicBleDevice_exports, {
NordicBleDevice: () => NordicBleDevice,
defaultOpts: () => defaultOpts
});
// src/io/Codec.ts
var Codec = class {
constructor() {
__publicField(this, "enc", new TextEncoder());
__publicField(this, "dec", new TextDecoder(`utf-8`));
}
toBuffer(str) {
return this.enc.encode(str);
}
fromBuffer(buffer) {
return this.dec.decode(buffer);
}
};
// src/io/StringReceiveBuffer.ts
var StringReceiveBuffer = class {
constructor(onData, separator = `
`) {
this.onData = onData;
this.separator = separator;
__publicField(this, "buffer", ``);
__publicField(this, "stream");
}
clear() {
this.buffer = ``;
}
writable() {
if (this.stream === void 0)
this.stream = this.createWritable();
return this.stream;
}
createWritable() {
const b = this;
return new WritableStream({
write(chunk) {
b.add(chunk);
},
close() {
b.clear();
}
});
}
add(str) {
if (str.length === 0)
return;
const pos = str.indexOf(this.separator);
if (pos < 0) {
this.buffer += str;
return;
}
const part = str.substring(0, pos);
try {
this.onData(this.buffer + part);
} catch (ex) {
console.warn(ex);
}
this.buffer = ``;
if (pos < str.length)
return;
this.add(str.substring(pos + 1));
}
};
// src/io/StringWriteBuffer.ts
var StringWriteBuffer = class {
constructor(onData, chunkSize = -1) {
this.onData = onData;
this.chunkSize = chunkSize;
__publicField(this, "paused", false);
__publicField(this, "queue");
__publicField(this, "writer");
__publicField(this, "intervalMs");
__publicField(this, "stream");
this.intervalMs = 10;
this.queue = queueMutable();
this.writer = continuously(() => this.onWrite(), this.intervalMs);
}
clear() {
this.queue = queueMutable();
}
writable() {
if (this.stream === void 0)
this.stream = this.createWritable();
return this.stream;
}
createWritable() {
const b = this;
return new WritableStream({
write(chunk) {
b.add(chunk);
},
close() {
b.clear();
}
});
}
async onWrite() {
console.log(`StringWriteBuffer.onWrite`);
if (this.queue.isEmpty) {
console.log(`WriteBuffer.onWrite: queue empty`);
return false;
}
if (this.paused) {
console.log(`WriteBuffer.onWrite: paused...`);
return true;
}
console.log(`StringWriteBuffer.onWrite pre dequeue`);
const s = this.queue.dequeue();
console.log(`StringWriteBuffer.onWrite s: ${s}`);
if (s === void 0)
return false;
await this.onData(s);
return true;
}
add(str) {
console.log(`StringWriteBuffer add: ${str} chunk: ${this.chunkSize}`);
if (this.chunkSize > 0) {
this.queue.enqueue(...splitByLength(str, this.chunkSize));
} else {
this.queue.enqueue(str);
}
console.log(`StringWriteBuffer add length: ${this.queue.length} isEmpty: ${this.queue.isEmpty}`);
this.writer.start();
}
};
// src/io/BleDevice.ts
var BleDevice = class extends SimpleEventEmitter {
constructor(device, config) {
super();
this.device = device;
this.config = config;
__publicField(this, "states");
__publicField(this, "codec");
__publicField(this, "rx");
__publicField(this, "tx");
__publicField(this, "gatt");
__publicField(this, "verboseLogging", false);
__publicField(this, "rxBuffer");
__publicField(this, "txBuffer");
this.verboseLogging = config.debug;
this.txBuffer = new StringWriteBuffer(async (data) => {
await this.writeInternal(data);
}, config.chunkSize);
this.rxBuffer = new StringReceiveBuffer((line) => {
this.fireEvent(`data`, { data: line });
});
this.codec = new Codec();
this.states = new StateMachine(`ready`, {
ready: `connecting`,
connecting: [`connected`, `closed`],
connected: [`closed`],
closed: `connecting`
});
this.states.addEventListener(`change`, (evt) => {
this.fireEvent(`change`, evt);
this.verbose(`${evt.priorState} -> ${evt.newState}`);
if (evt.priorState === `connected`) {
this.rxBuffer.clear();
this.txBuffer.clear();
}
});
device.addEventListener(`gattserverdisconnected`, () => {
if (this.isClosed)
return;
this.verbose(`GATT server disconnected`);
this.states.state = `closed`;
});
this.verbose(`ctor ${device.name} ${device.id}`);
}
get isConnected() {
return this.states.state === `connected`;
}
get isClosed() {
return this.states.state === `closed`;
}
write(txt) {
if (this.states.state !== `connected`)
throw new Error(`Cannot write while state is ${this.states.state}`);
this.txBuffer.add(txt);
}
async writeInternal(txt) {
this.verbose(`writeInternal ${txt}`);
const tx = this.tx;
if (tx === void 0)
throw new Error(`Unexpectedly without tx characteristic`);
try {
await tx.writeValue(this.codec.toBuffer(txt));
} catch (ex) {
this.warn(ex);
}
}
disconnect() {
if (this.states.state !== `connected`)
return;
this.gatt?.disconnect();
}
async connect() {
const attempts = this.config.connectAttempts ?? 3;
this.states.state = `connecting`;
this.verbose(`connect`);
const gatt = this.device.gatt;
if (gatt === void 0)
throw new Error(`Gatt not available on device`);
await retry(async () => {
const server = await gatt.connect();
this.verbose(`Getting primary service`);
const service = await server.getPrimaryService(this.config.service);
this.verbose(`Getting characteristics`);
const rx = await service.getCharacteristic(this.config.rxGattCharacteristic);
const tx = await service.getCharacteristic(this.config.txGattCharacteristic);
rx.addEventListener(`characteristicvaluechanged`, (evt) => this.onRx(evt));
this.rx = rx;
this.tx = tx;
this.gatt = gatt;
this.states.state = `connected`;
await rx.startNotifications();
}, attempts, 200);
}
onRx(evt) {
const rx = this.rx;
if (rx === void 0)
return;
const view = evt.target.value;
if (view === void 0)
return;
let str = this.codec.fromBuffer(view.buffer);
const plzStop = indexOfCharCode(str, 19);
const plzStart = indexOfCharCode(str, 17);
if (plzStart && plzStop < plzStart) {
this.verbose(`Tx plz start`);
str = omitChars(str, plzStart, 1);
this.txBuffer.paused = false;
}
if (plzStop && plzStop > plzStart) {
this.verbose(`Tx plz stop`);
str = omitChars(str, plzStop, 1);
this.txBuffer.paused = true;
}
this.rxBuffer.add(str);
}
verbose(m) {
if (this.verboseLogging)
console.info(`${this.config.name} `, m);
}
log(m) {
console.log(`${this.config.name} `, m);
}
warn(m) {
console.warn(`${this.config.name} `, m);
}
};
// src/io/NordicBleDevice.ts
var defaultOpts = {
chunkSize: 20,
service: `6e400001-b5a3-f393-e0a9-e50e24dcca9e`,
txGattCharacteristic: `6e400002-b5a3-f393-e0a9-e50e24dcca9e`,
rxGattCharacteristic: `6e400003-b5a3-f393-e0a9-e50e24dcca9e`,
name: `NordicDevice`,
connectAttempts: 5,
debug: false
};
var NordicBleDevice = class extends BleDevice {
constructor(device, opts = {}) {
super(device, { ...defaultOpts, ...opts });
}
};
// src/io/EspruinoDevice.ts
var EspruinoDevice_exports = {};
__export(EspruinoDevice_exports, {
EspruinoDevice: () => EspruinoDevice,
connect: () => connect,
puck: () => puck
});
var EspruinoDevice = class extends NordicBleDevice {
constructor(device, opts = {}) {
super(device, opts);
__publicField(this, "evalTimeoutMs");
this.evalTimeoutMs = opts.evalTimeoutMs ?? 5 * 1e3;
}
async writeScript(code) {
this.write(`reset();
`);
this.write(`${code}
`);
}
async eval(code, opts = {}) {
const timeoutMs = opts.timeoutMs ?? this.evalTimeoutMs;
const assumeExclusive = opts.assumeExclusive ?? true;
if (typeof code !== `string`)
throw new Error(`code parameter should be a string`);
return new Promise((resolve, reject) => {
const id = string(5);
const onData = (d) => {
try {
const dd = JSON.parse(d.data);
if (`reply` in dd) {
if (dd.reply === id) {
done();
if (`result` in dd) {
resolve(dd.result);
}
} else {
this.warn(`Expected reply ${id}, got ${dd.reply}`);
}
}
} catch (ex) {
if (assumeExclusive) {
done(d.data);
} else {
this.warn(ex);
}
}
};
const onStateChange = (e) => {
if (e.newState !== `connected`)
done(`State changed to '${e.newState}', aborting`);
};
this.addEventListener(`data`, onData);
this.addEventListener(`change`, onStateChange);
const done = waitFor(timeoutMs, (reason) => {
reject(reason);
}, () => {
this.removeEventListener(`data`, onData);
this.removeEventListener(`change`, onStateChange);
});
this.write(`Bluetooth.println(JSON.stringify({reply:"${id}", result:JSON.stringify(${code})}))
`);
});
}
};
var puck = async (opts = {}) => {
const name = opts.name ?? `Puck`;
const debug = opts.debug ?? false;
const device = await navigator.bluetooth.requestDevice({
filters: [
{ namePrefix: `Puck.js` },
{ services: [defaultOpts.service] }
],
optionalServices: [defaultOpts.service]
});
const d = new EspruinoDevice(device, { name, debug });
await d.connect();
return d;
};
var connect = async () => {
const device = await navigator.bluetooth.requestDevice({
filters: [
{ namePrefix: `Puck.js` },
{ namePrefix: `Pixl.js` },
{ namePrefix: `MDBT42Q` },
{ namePrefix: `RuuviTag` },
{ namePrefix: `iTracker` },
{ namePrefix: `Thingy` },
{ namePrefix: `Espruino` },
{ services: [defaultOpts.service] }
],
optionalServices: [defaultOpts.service]
});
const d = new EspruinoDevice(device, { name: `Espruino` });
await d.connect();
return d;
};
// src/io/Camera.ts
var Camera_exports = {};
__export(Camera_exports, {
dumpDevices: () => dumpDevices,
start: () => start
});
var dumpDevices = async (filterKind = `videoinput`) => {
const devices = await navigator.mediaDevices.enumerateDevices();
devices.forEach((d) => {
if (d.kind !== filterKind)
return;
console.log(d.label);
console.log(` Kind: ${d.kind}`);
console.log(` Device id: ${d.deviceId}`);
});
};
var start = async (constraints = {}) => {
const videoEl = document.createElement(`VIDEO`);
videoEl.style.display = `none`;
document.body.appendChild(videoEl);
let stopVideo = () => {
};
const dispose = () => {
try {
stopVideo();
} catch {
}
videoEl.remove();
};
try {
const r = await startWithVideoEl(videoEl, constraints);
stopVideo = r.dispose;
} catch (err) {
console.error(err);
dispose();
return;
}
return { videoEl, dispose };
};
var startWithVideoEl = async (videoEl, constraints = {}) => {
if (videoEl === void 0)
throw new Error(`videoEl undefined`);
if (videoEl === null)
throw new Error(`videoEl null`);
const facingMode = constraints.facingMode ?? `user`;
const maxRes = constraints.max;
const minRes = constraints.min;
const c = {
audio: false,
video: {
facingMode,
width: {},
height: {}
}
};
if (maxRes) {
c.video.width = {
max: maxRes.width
};
c.video.height = {
max: maxRes.height
};
}
if (minRes) {
c.video.width = {
min: minRes.width
};
c.video.height = {
min: minRes.height
};
}
const dispose = () => {
console.log(`Camera:dispose`);
videoEl.pause();
const t = stream.getTracks();
t.forEach((track) => track.stop());
};
const stream = await navigator.mediaDevices.getUserMedia(c);
videoEl.srcObject = stream;
const ret = { videoEl, dispose };
const p = new Promise((resolve, reject) => {
videoEl.addEventListener(`loadedmetadata`, () => {
videoEl.play().then(() => {
resolve(ret);
}).catch((ex) => {
reject(ex);
});
});
});
return p;
};
// src/io/Serial.ts
var Serial_exports = {};
__export(Serial_exports, {
Device: () => Device
});
// src/io/JsonDevice.ts
var JsonDevice = class extends SimpleEventEmitter {
constructor(config = {}) {
super();
__publicField(this, "states");
__publicField(this, "codec");
__publicField(this, "verboseLogging", false);
__publicField(this, "name");
__publicField(this, "connectAttempts");
__publicField(this, "chunkSize");
__publicField(this, "rxBuffer");
__publicField(this, "txBuffer");
this.verboseLogging = config.debug ?? false;
this.chunkSize = config.chunkSize ?? 1024;
this.connectAttempts = config.connectAttempts ?? 3;
this.name = config.name ?? `JsonDevice`;
this.txBuffer = new StringWriteBuffer(async (data) => {
this.log(`onData called`);
await this.writeInternal(data);
}, config.chunkSize);
this.rxBuffer = new StringReceiveBuffer((line) => {
this.fireEvent(`data`, { data: line });
});
this.codec = new Codec();
this.states = new StateMachine(`ready`, {
ready: `connecting`,
connecting: [`connected`, `closed`],
connected: [`closed`],
closed: `connecting`
});
this.states.addEventListener(`change`, (evt) => {
this.fireEvent(`change`, evt);
this.verbose(`${evt.priorState} -> ${evt.newState}`);
if (evt.priorState === `connected`) {
this.rxBuffer.clear();
this.txBuffer.clear();
}
});
}
get isConnected() {
return this.states.state === `connected`;
}
get isClosed() {
return this.states.state === `closed`;
}
write(txt) {
if (this.states.state !== `connected`)
throw new Error(`Cannot write while state is ${this.states.state}`);
this.txBuffer.add(txt);
}
disconnect() {
if (this.states.state !== `connected`)
return;
this.onDisconnect();
}
async connect() {
const attempts = this.connectAttempts;
this.states.state = `connecting`;
this.verbose(`connect`);
await this.onPreConnect();
await retry(async () => {
await this.onConnectAttempt();
this.states.state = `connected`;
}, attempts, 200);
}
onRx(evt) {
const view = evt.target.value;
if (view === void 0)
return;
let str = this.codec.fromBuffer(view.buffer);
const plzStop = indexOfCharCode(str, 19);
const plzStart = indexOfCharCode(str, 17);
if (plzStart && plzStop < plzStart) {
this.verbose(`Tx plz start`);
str = omitChars(str, plzStart, 1);
this.txBuffer.paused = false;
}
if (plzStop && plzStop > plzStart) {
this.verbose(`Tx plz stop`);
str = omitChars(str, plzStop, 1);
this.txBuffer.paused = true;
}
this.rxBuffer.add(str);
}
verbose(m) {
if (this.verboseLogging)
console.info(`${this.name} `, m);
}
log(m) {
console.log(`${this.name} `, m);
}
warn(m) {
console.warn(`${this.name} `, m);
}
};
// src/io/Serial.ts
var Device = class extends JsonDevice {
constructor(config = {}) {
super(config);
this.config = config;
__publicField(this, "port");
__publicField(this, "tx");
if (config.name === void 0)
super.name = `Serial.Device`;
}
async writeInternal(txt) {
this.verbose(`writeInternal ${txt}`);
if (this.tx === void 0)
throw new Error(`tx not ready`);
try {
this.log(`writeInternal ${txt}`);
this.tx.write(txt);
} catch (ex) {
this.warn(ex);
}
}
onDisconnect() {
try {
this.port?.close();
} catch (ex) {
this.warn(ex);
}
this.states.state = `disconnected`;
}
onPreConnect() {
return Promise.resolve();
}
async onConnectAttempt() {
let opts = {};
if (this.config.filters)
opts = { filters: [...this.config.filters] };
this.port = await navigator.serial.requestPort(opts);
this.port.addEventListener(`connect`, (_) => {
this.log(`port connect`);
});
this.port.addEventListener(`disconnect`, (_) => {
this.log(`port disconnect`);
});
this.log(`onConnectAttempt`);
const tx = this.port.writable;
const txText = new TextEncoderStream();
if (tx !== null) {
this.log(`Setting up`);
txText.readable.pipeTo(tx);
this.tx = txText.writable.getWriter();
}
this.log(`tx: ${this.tx}`);
}
};
export {
NordicBleDevice_exports,
EspruinoDevice_exports,
Camera_exports,
Serial_exports,
io_exports
};
//# sourceMappingURL=chunk-ENMLUEID.js.map
|
'use strict'
const Command = require('ronin').Command
module.exports = Command.extend({
desc: 'ipscend version',
options: {
},
run: () => {
const pkg = require('../../../package.json')
console.log('Version: ', pkg.version)
}
})
|
// Vendor
import Component from '@ember/component';
import {argument} from '@ember-decorators/argument';
import {type} from '@ember-decorators/argument/type';
export default class ChallengeDetails extends Component {
@argument
@type('object')
challenge;
@argument
@type('object')
league;
oldChallengeSlug = null;
didUpdateAttrs() {
if (this.oldChallengeSlug === this.challenge.slug) return;
this.$().scrollTop(0);
}
didReceiveAttrs() {
this.set('oldChallengeSlug', this.challenge.slug);
}
}
|
'use strict';
// "Root" classes (starting points)
exports.BaseClient = require('./client/BaseClient');
exports.Client = require('./client/Client');
exports.Shard = require('./sharding/Shard');
exports.ShardClientUtil = require('./sharding/ShardClientUtil');
exports.ShardingManager = require('./sharding/ShardingManager');
exports.WebhookClient = require('./client/WebhookClient');
// Utilities
exports.ActivityFlagsBitField = require('./util/ActivityFlagsBitField');
exports.ApplicationFlagsBitField = require('./util/ApplicationFlagsBitField');
exports.BaseManager = require('./managers/BaseManager');
exports.BitField = require('./util/BitField');
exports.Collection = require('@discordjs/collection').Collection;
exports.Constants = require('./util/Constants');
exports.Colors = require('./util/Colors');
exports.DataResolver = require('./util/DataResolver');
exports.EnumResolvers = require('./util/EnumResolvers');
exports.Events = require('./util/Events');
exports.Formatters = require('./util/Formatters');
exports.IntentsBitField = require('./util/IntentsBitField');
exports.LimitedCollection = require('./util/LimitedCollection');
exports.MessageFlagsBitField = require('./util/MessageFlagsBitField');
exports.Options = require('./util/Options');
exports.Partials = require('./util/Partials');
exports.PermissionsBitField = require('./util/PermissionsBitField');
exports.ShardEvents = require('./util/ShardEvents');
exports.Status = require('./util/Status');
exports.SnowflakeUtil = require('@sapphire/snowflake').DiscordSnowflake;
exports.Sweepers = require('./util/Sweepers');
exports.SystemChannelFlagsBitField = require('./util/SystemChannelFlagsBitField');
exports.ThreadMemberFlagsBitField = require('./util/ThreadMemberFlagsBitField');
exports.UserFlagsBitField = require('./util/UserFlagsBitField');
exports.Util = require('./util/Util');
exports.version = require('../package.json').version;
// Managers
exports.ApplicationCommandManager = require('./managers/ApplicationCommandManager');
exports.ApplicationCommandPermissionsManager = require('./managers/ApplicationCommandPermissionsManager');
exports.BaseGuildEmojiManager = require('./managers/BaseGuildEmojiManager');
exports.CachedManager = require('./managers/CachedManager');
exports.ChannelManager = require('./managers/ChannelManager');
exports.ClientVoiceManager = require('./client/voice/ClientVoiceManager');
exports.DataManager = require('./managers/DataManager');
exports.GuildApplicationCommandManager = require('./managers/GuildApplicationCommandManager');
exports.GuildBanManager = require('./managers/GuildBanManager');
exports.GuildChannelManager = require('./managers/GuildChannelManager');
exports.GuildEmojiManager = require('./managers/GuildEmojiManager');
exports.GuildEmojiRoleManager = require('./managers/GuildEmojiRoleManager');
exports.GuildInviteManager = require('./managers/GuildInviteManager');
exports.GuildManager = require('./managers/GuildManager');
exports.GuildMemberManager = require('./managers/GuildMemberManager');
exports.GuildMemberRoleManager = require('./managers/GuildMemberRoleManager');
exports.GuildScheduledEventManager = require('./managers/GuildScheduledEventManager');
exports.GuildStickerManager = require('./managers/GuildStickerManager');
exports.MessageManager = require('./managers/MessageManager');
exports.PermissionOverwriteManager = require('./managers/PermissionOverwriteManager');
exports.PresenceManager = require('./managers/PresenceManager');
exports.ReactionManager = require('./managers/ReactionManager');
exports.ReactionUserManager = require('./managers/ReactionUserManager');
exports.RoleManager = require('./managers/RoleManager');
exports.StageInstanceManager = require('./managers/StageInstanceManager');
exports.ThreadManager = require('./managers/ThreadManager');
exports.ThreadMemberManager = require('./managers/ThreadMemberManager');
exports.UserManager = require('./managers/UserManager');
exports.VoiceStateManager = require('./managers/VoiceStateManager');
exports.WebSocketManager = require('./client/websocket/WebSocketManager');
exports.WebSocketShard = require('./client/websocket/WebSocketShard');
// Structures
exports.ActionRow = require('./structures/ActionRow');
exports.Activity = require('./structures/Presence').Activity;
exports.AnonymousGuild = require('./structures/AnonymousGuild');
exports.Application = require('./structures/interfaces/Application');
exports.ApplicationCommand = require('./structures/ApplicationCommand');
exports.AutocompleteInteraction = require('./structures/AutocompleteInteraction');
exports.Base = require('./structures/Base');
exports.BaseGuild = require('./structures/BaseGuild');
exports.BaseGuildEmoji = require('./structures/BaseGuildEmoji');
exports.BaseGuildTextChannel = require('./structures/BaseGuildTextChannel');
exports.BaseGuildVoiceChannel = require('./structures/BaseGuildVoiceChannel');
exports.ButtonComponent = require('./structures/ButtonComponent');
exports.ButtonInteraction = require('./structures/ButtonInteraction');
exports.CategoryChannel = require('./structures/CategoryChannel');
exports.Channel = require('./structures/Channel').Channel;
exports.ChatInputCommandInteraction = require('./structures/ChatInputCommandInteraction');
exports.ClientApplication = require('./structures/ClientApplication');
exports.ClientPresence = require('./structures/ClientPresence');
exports.ClientUser = require('./structures/ClientUser');
exports.CommandInteraction = require('./structures/CommandInteraction');
exports.Collector = require('./structures/interfaces/Collector');
exports.CommandInteractionOptionResolver = require('./structures/CommandInteractionOptionResolver');
exports.ContextMenuCommandInteraction = require('./structures/ContextMenuCommandInteraction');
exports.DMChannel = require('./structures/DMChannel');
exports.Embed = require('./structures/Embed');
exports.UnsafeEmbed = require('@discordjs/builders').UnsafeEmbed;
exports.Emoji = require('./structures/Emoji').Emoji;
exports.Guild = require('./structures/Guild').Guild;
exports.GuildAuditLogs = require('./structures/GuildAuditLogs');
exports.GuildAuditLogsEntry = require('./structures/GuildAuditLogs').Entry;
exports.GuildBan = require('./structures/GuildBan');
exports.GuildChannel = require('./structures/GuildChannel');
exports.GuildEmoji = require('./structures/GuildEmoji');
exports.GuildMember = require('./structures/GuildMember').GuildMember;
exports.GuildPreview = require('./structures/GuildPreview');
exports.GuildPreviewEmoji = require('./structures/GuildPreviewEmoji');
exports.GuildScheduledEvent = require('./structures/GuildScheduledEvent').GuildScheduledEvent;
exports.GuildTemplate = require('./structures/GuildTemplate');
exports.Integration = require('./structures/Integration');
exports.IntegrationApplication = require('./structures/IntegrationApplication');
exports.Interaction = require('./structures/Interaction');
exports.InteractionCollector = require('./structures/InteractionCollector');
exports.InteractionWebhook = require('./structures/InteractionWebhook');
exports.Invite = require('./structures/Invite');
exports.InviteStageInstance = require('./structures/InviteStageInstance');
exports.InviteGuild = require('./structures/InviteGuild');
exports.Message = require('./structures/Message').Message;
exports.MessageAttachment = require('./structures/MessageAttachment');
exports.MessageCollector = require('./structures/MessageCollector');
exports.MessageComponentInteraction = require('./structures/MessageComponentInteraction');
exports.MessageContextMenuCommandInteraction = require('./structures/MessageContextMenuCommandInteraction');
exports.MessageMentions = require('./structures/MessageMentions');
exports.MessagePayload = require('./structures/MessagePayload');
exports.MessageReaction = require('./structures/MessageReaction');
exports.Modal = require('./structures/Modal');
exports.ModalSubmitInteraction = require('./structures/ModalSubmitInteraction');
exports.ModalSubmitFieldsResolver = require('./structures/ModalSubmitFieldsResolver');
exports.NewsChannel = require('./structures/NewsChannel');
exports.OAuth2Guild = require('./structures/OAuth2Guild');
exports.PartialGroupDMChannel = require('./structures/PartialGroupDMChannel');
exports.PermissionOverwrites = require('./structures/PermissionOverwrites');
exports.Presence = require('./structures/Presence').Presence;
exports.ReactionCollector = require('./structures/ReactionCollector');
exports.ReactionEmoji = require('./structures/ReactionEmoji');
exports.RichPresenceAssets = require('./structures/Presence').RichPresenceAssets;
exports.Role = require('./structures/Role').Role;
exports.SelectMenuComponent = require('./structures/SelectMenuComponent');
exports.SelectMenuInteraction = require('./structures/SelectMenuInteraction');
exports.StageChannel = require('./structures/StageChannel');
exports.StageInstance = require('./structures/StageInstance').StageInstance;
exports.Sticker = require('./structures/Sticker').Sticker;
exports.StickerPack = require('./structures/StickerPack');
exports.StoreChannel = require('./structures/StoreChannel');
exports.Team = require('./structures/Team');
exports.TeamMember = require('./structures/TeamMember');
exports.TextChannel = require('./structures/TextChannel');
exports.TextInputComponent = require('./structures/TextInputComponent');
exports.ThreadChannel = require('./structures/ThreadChannel');
exports.ThreadMember = require('./structures/ThreadMember');
exports.Typing = require('./structures/Typing');
exports.User = require('./structures/User');
exports.UserContextMenuCommandInteraction = require('./structures/UserContextMenuCommandInteraction');
exports.VoiceChannel = require('./structures/VoiceChannel');
exports.VoiceRegion = require('./structures/VoiceRegion');
exports.VoiceState = require('./structures/VoiceState');
exports.Webhook = require('./structures/Webhook');
exports.Widget = require('./structures/Widget');
exports.WidgetMember = require('./structures/WidgetMember');
exports.WelcomeChannel = require('./structures/WelcomeChannel');
exports.WelcomeScreen = require('./structures/WelcomeScreen');
exports.WebSocket = require('./WebSocket');
// External
exports.ActivityType = require('discord-api-types/v9').ActivityType;
exports.ApplicationCommandType = require('discord-api-types/v9').ApplicationCommandType;
exports.ApplicationCommandOptionType = require('discord-api-types/v9').ApplicationCommandOptionType;
exports.ApplicationCommandPermissionType = require('discord-api-types/v9').ApplicationCommandPermissionType;
exports.AuditLogEvent = require('discord-api-types/v9').AuditLogEvent;
exports.ButtonStyle = require('discord-api-types/v9').ButtonStyle;
exports.ChannelType = require('discord-api-types/v9').ChannelType;
exports.ComponentType = require('discord-api-types/v9').ComponentType;
exports.GatewayCloseCodes = require('discord-api-types/v9').GatewayCloseCodes;
exports.GatewayDispatchEvents = require('discord-api-types/v9').GatewayDispatchEvents;
exports.GatewayIntentBits = require('discord-api-types/v9').GatewayIntentBits;
exports.GatewayOpcodes = require('discord-api-types/v9').GatewayOpcodes;
exports.GuildFeature = require('discord-api-types/v9').GuildFeature;
exports.GuildMFALevel = require('discord-api-types/v9').GuildMFALevel;
exports.GuildNSFWLevel = require('discord-api-types/v9').GuildNSFWLevel;
exports.GuildPremiumTier = require('discord-api-types/v9').GuildPremiumTier;
exports.GuildScheduledEventEntityType = require('discord-api-types/v9').GuildScheduledEventEntityType;
exports.GuildScheduledEventPrivacyLevel = require('discord-api-types/v9').GuildScheduledEventPrivacyLevel;
exports.GuildScheduledEventStatus = require('discord-api-types/v9').GuildScheduledEventStatus;
exports.GuildSystemChannelFlags = require('discord-api-types/v9').GuildSystemChannelFlags;
exports.GuildVerificationLevel = require('discord-api-types/v9').GuildVerificationLevel;
exports.InteractionType = require('discord-api-types/v9').InteractionType;
exports.InteractionResponseType = require('discord-api-types/v9').InteractionResponseType;
exports.InviteTargetType = require('discord-api-types/v9').InviteTargetType;
exports.Locale = require('discord-api-types/v9').Locale;
exports.MessageType = require('discord-api-types/v9').MessageType;
exports.MessageFlags = require('discord-api-types/v9').MessageFlags;
exports.OAuth2Scopes = require('discord-api-types/v9').OAuth2Scopes;
exports.PermissionFlagsBits = require('discord-api-types/v9').PermissionFlagsBits;
exports.RESTJSONErrorCodes = require('discord-api-types/v9').RESTJSONErrorCodes;
exports.StageInstancePrivacyLevel = require('discord-api-types/v9').StageInstancePrivacyLevel;
exports.StickerType = require('discord-api-types/v9').StickerType;
exports.StickerFormatType = require('discord-api-types/v9').StickerFormatType;
exports.TextInputStyle = require('discord-api-types/v9').TextInputStyle;
exports.UserFlags = require('discord-api-types/v9').UserFlags;
exports.WebhookType = require('discord-api-types/v9').WebhookType;
exports.UnsafeButtonComponent = require('@discordjs/builders').UnsafeButtonComponent;
exports.UnsafeSelectMenuComponent = require('@discordjs/builders').UnsafeSelectMenuComponent;
exports.SelectMenuOption = require('@discordjs/builders').SelectMenuOption;
exports.UnsafeSelectMenuOption = require('@discordjs/builders').UnsafeSelectMenuOption;
exports.DiscordAPIError = require('@discordjs/rest').DiscordAPIError;
exports.HTTPError = require('@discordjs/rest').HTTPError;
exports.RateLimitError = require('@discordjs/rest').RateLimitError;
|
import React from 'react';
import * as S from './styled';
import { socialLinks } from '@config';
import { useIsMounted } from '@hooks';
import { Icon } from '@icons';
import { Tooltip, Transition } from '@components';
const Social = () => {
const isMounted = useIsMounted();
return (
<S.SocialList>
<ul>
{socialLinks &&
socialLinks.map(({ url, name }, i) => (
<li key={i}>
<Transition
delay={`${i * 100 + 900}ms`}
animation="fadeInRight"
skip={isMounted}>
<Tooltip content={name} placement="left">
<a
href={url}
aria-label={name}
target="_blank"
title={name}
rel="noopener noreferrer">
<Icon name={name} />
</a>
</Tooltip>
</Transition>
</li>
))}
</ul>
</S.SocialList>
);
};
export default Social;
|
import { axios } from '@/utils/request'
/**
* 获取table nature enum 信息 func
* @param parameter
* @returns {*}
*/
export function tableNatureEnumInfo(parameter) {
return axios({
url: '/etlTask/getTableNatureEnumInfo',
method: 'get',
params: parameter
})
}
/**
* 查询分组列表 func
* @param parameter
* @returns {*}
*/
export function tableGroupList(parameter) {
return axios({
url: '/cdp-etl/cdpTable/getTableGroupList',
method: 'get',
params: parameter
})
}
/**
* cdp table 列表 func
* @param parameter
* @returns {*}
*/
export function cdpTableList(parameter) {
return axios({
url: '/cdp-etl/etlTask/cdpTableList',
method: 'post',
data: parameter
})
}
/**
* 根据table id获取表的列 func
* @param parameter
* @returns {*}
*/
export function tableColumnsForMarkTag(parameter) {
return axios({
url: '/cdpTable/getTableColumnsForMarkTag',
method: 'get',
params: parameter
})
}
/**
* 任务列表查询 func
* @param parameter
* @returns {*}
*/
export function etlTaskList(parameter) {
return axios({
url: 'cdp-etl/etlTask/pageList',
method: 'post',
data: parameter
})
}
/**
* 数据源列表查询 func
* @param parameter
* @returns {*}
*/
export function dataSourceList(parameter) {
return axios({
url: 'cdp-etl/dataSource/pageList',
method: 'post',
data: parameter
})
}
/**
* 数据源列表查询 func
* @param parameter
* @returns {*}
*/
export function dataSourceType(parameter) {
return axios({
url: 'cdp-etl/dataSource/getAvailableDataSourceType',
method: 'get',
data: parameter
})
}
/**
* 新增数据源 func
* @param parameter
* @returns {*}
*/
export function saveDataSource(parameter) {
return axios({
url: 'cdp-etl/dataSource/save',
method: 'post',
data: parameter
})
}
/**
* 新增数据源--检测 func
* @param parameter
* @returns {*}
*/
export function checkDataSource(parameter) {
return axios({
url: 'cdp-etl/jobApi/testDbConnect',
method: 'get',
params: parameter
})
}
/**
* 编辑数据源--检测 func
* @param parameter
* @returns {*}
*/
export function checkEditDataSource(parameter) {
return axios({
url: 'cdp-etl/dataSource/testConsumerConnectKafka',
method: 'post',
data: parameter
})
}
/**
* 删除数据源 func
* @param parameter
* @returns {*}
*/
export function deleteDataSource(parameter) {
return axios({
url: 'cdp-etl/dataSource/delete',
method: 'get',
params: parameter
})
}
|
/**
* Copyright 2018 The AMP HTML 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.
*/
import {jsonLiteral} from '../../../../src/json';
const DYNATRACE_CONFIG = jsonLiteral({
'requests': {
'endpoint':
'${protocol}://${tenant}${separator}${environment}:${port}/ampbf/${tenantpath}',
'pageview':
'${endpoint}?type=js&' +
'flavor=amp&' +
'v=1&' +
'a=1%7C1%7C_load_%7C_load_%7C-%7C${navTiming(navigationStart)}%7C' +
'${navTiming(domContentLoadedEventEnd)}%7C0%2C2%7C2%7C_onload_%7C' +
'_load_%7C-%7C${navTiming(domContentLoadedEventStart)}%7C' +
'${navTiming(domContentLoadedEventEnd)}%7C0&' +
'fId=${pageViewId}&' +
'vID=${clientId(rxVisitor)}&' +
'url=${sourceUrl}&' +
'title=${title}&' +
'sw=${screenWidth}&' +
'sh=${screenHeight}&' +
'w=${viewportWidth}&' +
'h=${viewportHeight}&' +
'nt=a${navType}' +
'b${navTiming(navigationStart)}' +
'c${navTiming(navigationStart,redirectStart)}' +
'd${navTiming(navigationStart,redirectEnd)}' +
'e${navTiming(navigationStart,fetchStart)}' +
'f${navTiming(navigationStart,domainLookupStart)}' +
'g${navTiming(navigationStart,domainLookupEnd)}' +
'h${navTiming(navigationStart,connectStart)}' +
'i${navTiming(navigationStart,connectEnd)}' +
'j${navTiming(navigationStart,secureConnectionStart)}' +
'k${navTiming(navigationStart,requestStart)}' +
'l${navTiming(navigationStart,responseStart)}' +
'm${navTiming(navigationStart,responseEnd)}' +
'n${navTiming(navigationStart,domLoading)}' +
'o${navTiming(navigationStart,domInteractive)}' +
'p${navTiming(navigationStart,domContentLoadedEventStart)}' +
'q${navTiming(navigationStart,domContentLoadedEventEnd)}' +
'r${navTiming(navigationStart,domComplete)}' +
's${navTiming(navigationStart,loadEventStart)}' +
't${navTiming(navigationStart,loadEventEnd)}&' +
'app=${app}&' +
'time=${timestamp}',
},
'triggers': {
'trackPageview': {
'on': 'visible',
'request': 'pageview',
},
},
'transport': {
'beacon': false,
'xhrpost': false,
'image': true,
},
'vars': {
'app': 'ampapp',
'protocol': 'https',
'tenant': '',
'environment': 'live.dynatrace.com',
'port': '443',
'separator': '.',
},
});
export {DYNATRACE_CONFIG};
|
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
{
"file": "plugins/cordova-plugin-whitelist/whitelist.js",
"id": "cordova-plugin-whitelist.whitelist",
"runs": true
},
{
"file": "plugins/cordova-plugin-camera/www/CameraConstants.js",
"id": "cordova-plugin-camera.Camera",
"clobbers": [
"Camera"
]
},
{
"file": "plugins/cordova-plugin-camera/www/CameraPopoverOptions.js",
"id": "cordova-plugin-camera.CameraPopoverOptions",
"clobbers": [
"CameraPopoverOptions"
]
},
{
"file": "plugins/cordova-plugin-camera/www/Camera.js",
"id": "cordova-plugin-camera.camera",
"clobbers": [
"navigator.camera"
]
},
{
"file": "plugins/cordova-plugin-camera/www/CameraPopoverHandle.js",
"id": "cordova-plugin-camera.CameraPopoverHandle",
"clobbers": [
"CameraPopoverHandle"
]
},
{
"file": "plugins/cordova-plugin-device/www/device.js",
"id": "cordova-plugin-device.device",
"clobbers": [
"device"
]
},
{
"file": "plugins/cordova-plugin-dialogs/www/notification.js",
"id": "cordova-plugin-dialogs.notification",
"merges": [
"navigator.notification"
]
},
{
"file": "plugins/cordova-plugin-dialogs/www/android/notification.js",
"id": "cordova-plugin-dialogs.notification_android",
"merges": [
"navigator.notification"
]
},
{
"file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",
"id": "cordova-plugin-file.DirectoryEntry",
"clobbers": [
"window.DirectoryEntry"
]
},
{
"file": "plugins/cordova-plugin-file/www/DirectoryReader.js",
"id": "cordova-plugin-file.DirectoryReader",
"clobbers": [
"window.DirectoryReader"
]
},
{
"file": "plugins/cordova-plugin-file/www/Entry.js",
"id": "cordova-plugin-file.Entry",
"clobbers": [
"window.Entry"
]
},
{
"file": "plugins/cordova-plugin-file/www/File.js",
"id": "cordova-plugin-file.File",
"clobbers": [
"window.File"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileEntry.js",
"id": "cordova-plugin-file.FileEntry",
"clobbers": [
"window.FileEntry"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileError.js",
"id": "cordova-plugin-file.FileError",
"clobbers": [
"window.FileError"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileReader.js",
"id": "cordova-plugin-file.FileReader",
"clobbers": [
"window.FileReader"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileSystem.js",
"id": "cordova-plugin-file.FileSystem",
"clobbers": [
"window.FileSystem"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",
"id": "cordova-plugin-file.FileUploadOptions",
"clobbers": [
"window.FileUploadOptions"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileUploadResult.js",
"id": "cordova-plugin-file.FileUploadResult",
"clobbers": [
"window.FileUploadResult"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileWriter.js",
"id": "cordova-plugin-file.FileWriter",
"clobbers": [
"window.FileWriter"
]
},
{
"file": "plugins/cordova-plugin-file/www/Flags.js",
"id": "cordova-plugin-file.Flags",
"clobbers": [
"window.Flags"
]
},
{
"file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",
"id": "cordova-plugin-file.LocalFileSystem",
"clobbers": [
"window.LocalFileSystem"
],
"merges": [
"window"
]
},
{
"file": "plugins/cordova-plugin-file/www/Metadata.js",
"id": "cordova-plugin-file.Metadata",
"clobbers": [
"window.Metadata"
]
},
{
"file": "plugins/cordova-plugin-file/www/ProgressEvent.js",
"id": "cordova-plugin-file.ProgressEvent",
"clobbers": [
"window.ProgressEvent"
]
},
{
"file": "plugins/cordova-plugin-file/www/fileSystems.js",
"id": "cordova-plugin-file.fileSystems"
},
{
"file": "plugins/cordova-plugin-file/www/requestFileSystem.js",
"id": "cordova-plugin-file.requestFileSystem",
"clobbers": [
"window.requestFileSystem"
]
},
{
"file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js",
"id": "cordova-plugin-file.resolveLocalFileSystemURI",
"merges": [
"window"
]
},
{
"file": "plugins/cordova-plugin-file/www/browser/isChrome.js",
"id": "cordova-plugin-file.isChrome",
"runs": true
},
{
"file": "plugins/cordova-plugin-file/www/android/FileSystem.js",
"id": "cordova-plugin-file.androidFileSystem",
"merges": [
"FileSystem"
]
},
{
"file": "plugins/cordova-plugin-file/www/fileSystems-roots.js",
"id": "cordova-plugin-file.fileSystems-roots",
"runs": true
},
{
"file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",
"id": "cordova-plugin-file.fileSystemPaths",
"merges": [
"cordova"
],
"runs": true
},
{
"file": "plugins/cordova-plugin-file-transfer/www/FileTransferError.js",
"id": "cordova-plugin-file-transfer.FileTransferError",
"clobbers": [
"window.FileTransferError"
]
},
{
"file": "plugins/cordova-plugin-file-transfer/www/FileTransfer.js",
"id": "cordova-plugin-file-transfer.FileTransfer",
"clobbers": [
"window.FileTransfer"
]
},
{
"file": "plugins/cordova-plugin-media-capture/www/CaptureAudioOptions.js",
"id": "cordova-plugin-media-capture.CaptureAudioOptions",
"clobbers": [
"CaptureAudioOptions"
]
},
{
"file": "plugins/cordova-plugin-media-capture/www/CaptureImageOptions.js",
"id": "cordova-plugin-media-capture.CaptureImageOptions",
"clobbers": [
"CaptureImageOptions"
]
},
{
"file": "plugins/cordova-plugin-media-capture/www/CaptureVideoOptions.js",
"id": "cordova-plugin-media-capture.CaptureVideoOptions",
"clobbers": [
"CaptureVideoOptions"
]
},
{
"file": "plugins/cordova-plugin-media-capture/www/CaptureError.js",
"id": "cordova-plugin-media-capture.CaptureError",
"clobbers": [
"CaptureError"
]
},
{
"file": "plugins/cordova-plugin-media-capture/www/MediaFileData.js",
"id": "cordova-plugin-media-capture.MediaFileData",
"clobbers": [
"MediaFileData"
]
},
{
"file": "plugins/cordova-plugin-media-capture/www/MediaFile.js",
"id": "cordova-plugin-media-capture.MediaFile",
"clobbers": [
"MediaFile"
]
},
{
"file": "plugins/cordova-plugin-media-capture/www/capture.js",
"id": "cordova-plugin-media-capture.capture",
"clobbers": [
"navigator.device.capture"
]
},
{
"file": "plugins/cordova-plugin-splashscreen/www/splashscreen.js",
"id": "cordova-plugin-splashscreen.SplashScreen",
"clobbers": [
"navigator.splashscreen"
]
},
{
"file": "plugins/cordova-plugin-statusbar/www/statusbar.js",
"id": "cordova-plugin-statusbar.statusbar",
"clobbers": [
"window.StatusBar"
]
},
{
"file": "plugins/io.litehelpers.cordova.sqlite/www/SQLitePlugin.js",
"id": "io.litehelpers.cordova.sqlite.SQLitePlugin",
"clobbers": [
"SQLitePlugin"
]
}
];
module.exports.metadata =
// TOP OF METADATA
{
"cordova-plugin-whitelist": "1.2.1",
"cordova-plugin-camera": "2.1.1",
"cordova-plugin-device": "1.1.1",
"cordova-plugin-dialogs": "1.2.0",
"cordova-plugin-file": "4.1.1",
"cordova-plugin-file-transfer": "1.5.0",
"cordova-plugin-media-capture": "1.2.0",
"cordova-plugin-splashscreen": "3.2.1",
"cordova-plugin-statusbar": "2.1.2",
"io.litehelpers.cordova.sqlite": "0.7.7"
};
// BOTTOM OF METADATA
});
|
window.__NUXT__=(function(a,b,c,d){return {staticAssetsBase:"\u002Fstatic\u002F1597376630",layout:"default",error:b,state:{notification:{show:a,title:c,message:c},isShowSidebar:a,isSupportWebShare:a,headerTitle:"e-AlQur'an",page:"home",lastReadVerse:b,settingActiveTheme:{name:"dark",bgColor:"#071e3d",fgColor:"#fff"},settingShowTranslation:a,settingShowTafsir:a,settingShowMuqaddimah:d,surahFavorite:[]},serverRendered:d,routePath:"\u002Famp\u002F24\u002F63",config:{}}}(false,null,"",true));
|
function initMap(e,o,t,l){void 0===e&&(e="map"),void 0===o&&(o=40.728157),void 0===t&&(t=-74.077644),void 0===l&&(l="../images/map-marker.png");let r={lat:o,lng:t},a=document.getElementById(e);if("undefined"==typeof google)return;let n=new google.maps.Map(a,{zoom:13,scrollwheel:!1,center:r,mapTypeControl:!1,fullscreenControl:!1,streetViewControl:!1,styles:[{featureType:"road",stylers:[{color:"#ffffff"}]},{featureType:"water",stylers:[{color:"#e9e9e9"}]},{featureType:"landscape",stylers:[{color:"#f5f5f5"}]},{elementType:"labels.text.fill",stylers:[{color:"transparent"}]},{featureType:"poi",stylers:[{color:"#fefefe"}]},{elementType:"labels.text",stylers:[{saturation:1},{weight:.1},{color:"#737980"}]}]});new google.maps.Marker({position:r,map:n,icon:l,animation:google.maps.Animation.BOUNCE})}
|
var searchData=
[
['active_5fml_5fmodel_191',['Active_ML_Model',['../classapp_1_1_m_l___class_1_1_active___m_l___model.html',1,'app::ML_Class']]],
['al_5fencoder_192',['AL_Encoder',['../classapp_1_1_m_l___class_1_1_a_l___encoder.html',1,'app::ML_Class']]]
];
|
'use strict';
const Record = require('../schemas/Record');
const runUpdate = require('../utils/runUpdate');
const add = async data => {
return Record.create(data);
};
const update = async (id, data) => {
return runUpdate(Record, id, data);
};
const anonymize = async (clientId, ignoreId) => {
return Record.updateMany(
{
$and: [
{ clientId },
{
id: {
$ne: ignoreId,
},
},
],
},
{
clientId: null,
siteLanguage: null,
screenWidth: null,
screenHeight: null,
screenColorDepth: null,
deviceName: null,
deviceManufacturer: null,
osName: null,
osVersion: null,
browserName: null,
browserVersion: null,
browserWidth: null,
browserHeight: null,
},
);
};
module.exports = {
add,
update,
anonymize,
};
|
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft Corporation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
this.WScript.LoadScriptFile("..\\UnitTestFramework\\SimdJsHelpers.js");
function asmModule(stdlib, imports) {
"use asm";
var ui4 = stdlib.SIMD.Uint32x4;
var ui4check = ui4.check;
var ui4lessThan = ui4.lessThan;
var ui4equal = ui4.equal;
var ui4greaterThan = ui4.greaterThan;
var ui4lessThanOrEqual = ui4.lessThanOrEqual;
var ui4greaterThanOrEqual = ui4.greaterThanOrEqual;
var ui4notEqual = ui4.notEqual;
var ui4select = ui4.select;
var b4 = stdlib.SIMD.Bool32x4;
var globImportui4 = ui4check(imports.g1); // global var import
var ui4g1 = ui4(1065353216, 1073741824, 1077936128, 1082130432); // global var initialized
var ui4g2 = ui4(6531634, 74182444, 779364128, 821730432);
var loopCOUNT = 5;
var i4 = stdlib.SIMD.Int32x4;
var i4check = i4.check;
var i4fu4 = i4.fromUint32x4Bits;
function testLessThan()
{
var b = ui4(8488484, 4848848, 29975939, 9493872);
var c = ui4(99371, 18848392, 888288822, 100012);
var d = ui4(0, 0, 0, 0);
var mask = b4(0, 0, 0, 0);
var loopIndex = 0;
while ((loopIndex | 0) < (loopCOUNT | 0))
{
mask = ui4lessThan(b, c);
d = ui4select(mask, b, c);
loopIndex = (loopIndex + 1) | 0;
}
return i4check(i4fu4(d));
}
function testLessThanOrEqual()
{
var b = ui4(8488484, 4848848, 29975939, 9493872);
var c = ui4(99372621, 18848392, 888288822, 1000010012);
var d = ui4(0, 0, 0, 0);
var mask = b4(0, 0, 0, 0);
var loopIndex = 0;
while ((loopIndex | 0) < (loopCOUNT | 0)) {
mask = ui4lessThanOrEqual(b, c);
d = ui4select(mask, b, c);
loopIndex = (loopIndex + 1) | 0;
}
return i4check(i4fu4(d));
}
function testGreaterThan()
{
var b = ui4(8488484, 4848848, 29975939, 9493872);
var c = ui4(99372621, 18848392, 888288822, 1000010012);
var d = ui4(0, 0, 0, 0);
var mask = b4(0, 0, 0, 0);
var loopIndex = 0;
while ((loopIndex | 0) < (loopCOUNT | 0)) {
mask = ui4greaterThan(b, c);
d = ui4select(mask, b, c);
loopIndex = (loopIndex + 1) | 0;
}
return i4check(i4fu4(d));
}
function testGreaterThanOrEqual()
{
var b = ui4(8488484, 4848848, 29975939, 9493872);
var c = ui4(99372621, 18848392, 888288822, 1000010012);
var d = ui4(0, 0, 0, 0);
var mask = b4(0, 0, 0, 0);
var loopIndex = 0;
while ((loopIndex | 0) < (loopCOUNT | 0)) {
mask = ui4greaterThanOrEqual(b, c);
d = ui4select(mask, b, c);
loopIndex = (loopIndex + 1) | 0;
}
return i4check(i4fu4(d));
}
function testEqual()
{
var b = ui4(8488484, 18848392, 29975939, 1000010012);
var c = ui4(99372621, 18848392, 888288822, 1000010012);
var d = ui4(0, 0, 0, 0);
var mask = b4(0, 0, 0, 0);
var loopIndex = 0;
while ((loopIndex | 0) < (loopCOUNT | 0)) {
mask = ui4equal(b, c);
d = ui4select(mask, b, c);
loopIndex = (loopIndex + 1) | 0;
}
return i4check(i4fu4(d));
}
function testNotEqual()
{
var b = ui4(8488484, 4848848, 29975939, 9493872);
var c = ui4(99372621, 18848392, 888288822, 1000010012);
var d = ui4(0, 0, 0, 0);
var mask = b4(0, 0, 0, 0);
var loopIndex = 0;
while ((loopIndex | 0) < (loopCOUNT | 0)) {
mask = ui4notEqual(b, c);
d = ui4select(mask, b, c);
loopIndex = (loopIndex + 1) | 0;
}
return i4check(i4fu4(d));
}
return { testLessThan: testLessThan, testLessThanOrEqual: testLessThanOrEqual, testGreaterThan: testGreaterThan, testGreaterThanOrEqual: testGreaterThanOrEqual, testEqual: testEqual, testNotEqual: testNotEqual };
}
var m = asmModule(this, { g1: SIMD.Uint32x4(100, 1073741824, 1028, 102) });
var ret1 = SIMD.Uint32x4.fromInt32x4Bits(m.testLessThan());
var ret2 = SIMD.Uint32x4.fromInt32x4Bits(m.testLessThanOrEqual());
var ret3 = SIMD.Uint32x4.fromInt32x4Bits(m.testGreaterThan());
var ret4 = SIMD.Uint32x4.fromInt32x4Bits(m.testGreaterThanOrEqual());
var ret5 = SIMD.Uint32x4.fromInt32x4Bits(m.testEqual());
var ret6 = SIMD.Uint32x4.fromInt32x4Bits(m.testNotEqual());
equalSimd([99371, 4848848, 29975939, 100012], ret1, SIMD.Uint32x4, "Func1");
equalSimd([8488484, 4848848, 29975939, 9493872], ret2, SIMD.Uint32x4, "Func2");
equalSimd([99372621, 18848392, 888288822, 1000010012], ret3, SIMD.Uint32x4, "Func3");
equalSimd([99372621, 18848392, 888288822, 1000010012], ret4, SIMD.Uint32x4, "Func4");
equalSimd([99372621, 18848392, 888288822, 1000010012], ret5, SIMD.Uint32x4, "Func5");
equalSimd([8488484, 4848848, 29975939, 9493872], ret6, SIMD.Uint32x4, "Func6");
print("PASS");
|
module.exports = [
{
url: 'http://localhost:3000/#/checkboxes',
label: 'Checkbox responsive',
responsive: true,
selectors: [
'document',
'[data-backstop="checkbox-responsive"]',
],
},
// TODO: need method for focus/hovering one element but snapshotting it's parent
{
url: 'http://localhost:3000/#/checkboxes',
label: 'Checkbox',
selectors: [
'[data-backstop="checkbox-checked"]',
],
focusSelectors: [
{
target: '[data-backstop="checkbox-checked"] input',
capture: '[data-backstop="checkbox-checked"]',
},
],
},
];
|
/*
* Copyright 2012-2017 Frank Breedijk
*
* 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.
*/
steal(
'jquery/controller',
'jquery/view/ejs',
'jquery/controller/view',
'seccubus/models'
)
.then( './views/init.ejs',
function($){
/**
* @class Seccubus.Event.Select
* @parent Event
* @inherits jQuery.Controller
* Builds a dropdown selector of events
*/
$.Controller('Seccubus.Event.Select',
/** @Static */
{
defaults : {
/*
* @attribute options.selected
* This attribute indicates which item in the dropdown is
* initially selected.
* Default value: -1
*/
selected : -1
}
},
/** @Prototype */
{
/* This funciton calls updateView to render the control
*/
init : function(el, fn){
this.updateView();
},
// (re-)Render on delete
"{Seccubus.Models.Event} destroyed" : function(Event, ev, event) {
this.updateView();
},
// (re-)Render on create
"{Seccubus.Models.Event} created" : function(Event, ev, event){
this.updateView();
},
// Apend on update
"{Seccubus.Models.Event} updated" : function(Event, ev, event){
event.elements(this.element)
.html(this.view('event', event) );
},
/*
* This fuction rerenders the entire control with data from findAll
*/
updateView : function() {
this.element.html(
this.view(
'init',
Seccubus.Models.Event.findAll(),
{
selected : this.options.selected
}
)
);
/*
if ( this.options.selected != -1 ) {
//alert(this.element.attr("html"));
this.element.attr("value",this.options.selected);
};
*/
}
}); // Controller
}); // Steal
|
'use strict';
// Test specific configuration
// ===========================
module.exports = {
// MongoDB connection options
mongo: {
uri: 'mongodb://localhost/paizaqa-test'
},
sequelize: {
uri: 'sqlite://',
options: {
logging: false,
storage: 'test.sqlite',
define: {
timestamps: false
}
}
}
};
|
const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB.DocumentClient();
module.exports.list = (event, context, callback) => {
let env = event.pathParameters.env;
let component = event.pathParameters.component;
const params = {
TableName: process.env.DYNAMODB_TABLE,
FilterExpression: 'env = :env and component = :component',
ExpressionAttributeValues: {
':env': env,
':component': component,
}
};
dynamoDb.scan(params, (error, result) => {
if (error) {
console.error(error);
callback(null, {
statusCode: error.statusCode || 501,
headers: { 'Content-Type': 'text/plain' },
body: 'couldn\'t fetch the logs.',
});
return;
}
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin" : "*" // Required for CORS support to work
},
body: JSON.stringify(result.Items),
};
callback(null, response);
});
};
|
'use strict';
(function() {
const loginUser = require('./login_auth');
const UserChats = require('./chat_app');
const bodyParser = require('body-parser');
const User = require('../db/schema.js');
const TockenServ = require('../service/tocken_service');
function routes(app) {
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/api', loginUser)
/*
* User Authorization Checking Process
*/
app.use('/api/chat', (req, res, next) => {
const token = (req.headers || {}).authorization
console.log(token)
if (!token) {
res.status(401).json({ msg: 'Your Not Authorized' })
}
let tokenVerify;
try {
tokenVerify = TockenServ.verifyToken(token)
next();
} catch (error) {
res.status(401).json({ message: error.message })
next();
}
})
app.use('/api/chat', UserChats)
}
module.exports = routes;
})();
|
const path = require('path')
module.exports ={
entry: path.resolve(__dirname, 'index.js'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
devServer: {
contentBase: path.resolve(__dirname),
compress: true,
port: 8080,
open: true
}
}
|
define(["exports","./when-229515d6"],(function(t,e){"use strict";function n(t){let e;this.name="DeveloperError",this.message=t;try{throw new Error}catch(t){e=t.stack}this.stack=e}e.defined(Object.create)&&(n.prototype=Object.create(Error.prototype),n.prototype.constructor=n),n.prototype.toString=function(){let t=`${this.name}: ${this.message}`;return e.defined(this.stack)&&(t+=`\n${this.stack.toString()}`),t},n.throwInstantiationError=function(){throw new n("This function defines an interface and should not be called directly.")};const o={};function r(t,e,n){return`Expected ${n} to be typeof ${e}, actual typeof was ${t}`}function i(t){let e;this.name="RuntimeError",this.message=t;try{throw new Error}catch(t){e=t.stack}this.stack=e}o.typeOf={},o.defined=function(t,o){if(!e.defined(o))throw new n(function(t){return`${t} is required, actual value was undefined`}(t))},o.typeOf.func=function(t,e){if("function"!=typeof e)throw new n(r(typeof e,"function",t))},o.typeOf.string=function(t,e){if("string"!=typeof e)throw new n(r(typeof e,"string",t))},o.typeOf.number=function(t,e){if("number"!=typeof e)throw new n(r(typeof e,"number",t))},o.typeOf.number.lessThan=function(t,e,r){if(o.typeOf.number(t,e),e>=r)throw new n(`Expected ${t} to be less than ${r}, actual value was ${e}`)},o.typeOf.number.lessThanOrEquals=function(t,e,r){if(o.typeOf.number(t,e),e>r)throw new n(`Expected ${t} to be less than or equal to ${r}, actual value was ${e}`)},o.typeOf.number.greaterThan=function(t,e,r){if(o.typeOf.number(t,e),e<=r)throw new n(`Expected ${t} to be greater than ${r}, actual value was ${e}`)},o.typeOf.number.greaterThanOrEquals=function(t,e,r){if(o.typeOf.number(t,e),e<r)throw new n(`Expected ${t} to be greater than or equal to ${r}, actual value was ${e}`)},o.typeOf.object=function(t,e){if("object"!=typeof e)throw new n(r(typeof e,"object",t))},o.typeOf.bool=function(t,e){if("boolean"!=typeof e)throw new n(r(typeof e,"boolean",t))},o.typeOf.bigint=function(t,e){if("bigint"!=typeof e)throw new n(r(typeof e,"bigint",t))},o.typeOf.number.equals=function(t,e,r,i){if(o.typeOf.number(t,r),o.typeOf.number(e,i),r!==i)throw new n(`${t} must be equal to ${e}, the actual values are ${r} and ${i}`)},e.defined(Object.create)&&(i.prototype=Object.create(Error.prototype),i.prototype.constructor=i),i.prototype.toString=function(){let t=`${this.name}: ${this.message}`;return e.defined(this.stack)&&(t+=`\n${this.stack.toString()}`),t},t.Check=o,t.DeveloperError=n,t.RuntimeError=i}));
|
/**
* Created by shakamann on 1/11/2015.
*/
/*!
* jQuery blockUI plugin
* Version 2.70.0-2014.11.23
* Requires jQuery v1.7 or later
*
* Examples at: http://malsup.com/jquery/block/
* Copyright (c) 2007-2013 M. Alsup
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Thanks to Amir-Hossein Sobhi for some excellent contributions!
*/
;(function() {
/*jshint eqeqeq:false curly:false latedef:false */
"use strict";
function setup($) {
$.fn._fadeIn = $.fn.fadeIn;
var noOp = $.noop || function() {};
// this bit is to ensure we don't call setExpression when we shouldn't (with extra muscle to handle
// confusing userAgent strings on Vista)
var msie = /MSIE/.test(navigator.userAgent);
var ie6 = /MSIE 6.0/.test(navigator.userAgent) && ! /MSIE 8.0/.test(navigator.userAgent);
var mode = document.documentMode || 0;
var setExpr = $.isFunction( document.createElement('div').style.setExpression );
// global $ methods for blocking/unblocking the entire page
$.blockUI = function(opts) { install(window, opts); };
$.unblockUI = function(opts) { remove(window, opts); };
// convenience method for quick growl-like notifications (http://www.google.com/search?q=growl)
$.growlUI = function(title, message, timeout, onClose) {
var $m = $('<div class="growlUI"></div>');
if (title) $m.append('<h1>'+title+'</h1>');
if (message) $m.append('<h2>'+message+'</h2>');
if (timeout === undefined) timeout = 3000;
// Added by konapun: Set timeout to 30 seconds if this growl is moused over, like normal toast notifications
var callBlock = function(opts) {
opts = opts || {};
$.blockUI({
message: $m,
fadeIn : typeof opts.fadeIn !== 'undefined' ? opts.fadeIn : 700,
fadeOut: typeof opts.fadeOut !== 'undefined' ? opts.fadeOut : 1000,
timeout: typeof opts.timeout !== 'undefined' ? opts.timeout : timeout,
centerY: false,
showOverlay: false,
onUnblock: onClose,
css: $.blockUI.defaults.growlCSS
});
};
callBlock();
var nonmousedOpacity = $m.css('opacity');
$m.mouseover(function() {
callBlock({
fadeIn: 0,
timeout: 30000
});
var displayBlock = $('.blockMsg');
displayBlock.stop(); // cancel fadeout if it has started
displayBlock.fadeTo(300, 1); // make it easier to read the message by removing transparency
}).mouseout(function() {
$('.blockMsg').fadeOut(1000);
});
// End konapun additions
};
// plugin method for blocking element content
$.fn.block = function(opts) {
if ( this[0] === window ) {
$.blockUI( opts );
return this;
}
var fullOpts = $.extend({}, $.blockUI.defaults, opts || {});
this.each(function() {
var $el = $(this);
if (fullOpts.ignoreIfBlocked && $el.data('blockUI.isBlocked'))
return;
$el.unblock({ fadeOut: 0 });
});
return this.each(function() {
if ($.css(this,'position') == 'static') {
this.style.position = 'relative';
$(this).data('blockUI.static', true);
}
this.style.zoom = 1; // force 'hasLayout' in ie
install(this, opts);
});
};
// plugin method for unblocking element content
$.fn.unblock = function(opts) {
if ( this[0] === window ) {
$.unblockUI( opts );
return this;
}
return this.each(function() {
remove(this, opts);
});
};
$.blockUI.version = 2.70; // 2nd generation blocking at no extra cost!
// override these in your code to change the default behavior and style
$.blockUI.defaults = {
// message displayed when blocking (use null for no message)
message: '<h1>Please wait...</h1>',
title: null, // title string; only used when theme == true
draggable: true, // only used when theme == true (requires jquery-ui.js to be loaded)
theme: false, // set to true to use with jQuery UI themes
// styles for the message when blocking; if you wish to disable
// these and use an external stylesheet then do this in your code:
// $.blockUI.defaults.css = {};
css: {
padding: 0,
margin: 0,
width: '30%',
top: '40%',
left: '35%',
textAlign: 'center',
color: '#000',
border: '3px solid #aaa',
backgroundColor:'#fff',
cursor: 'wait'
},
// minimal style set used when themes are used
themedCSS: {
width: '30%',
top: '40%',
left: '35%'
},
// styles for the overlay
overlayCSS: {
backgroundColor: '#000',
opacity: 0.6,
cursor: 'wait'
},
// style to replace wait cursor before unblocking to correct issue
// of lingering wait cursor
cursorReset: 'default',
// styles applied when using $.growlUI
growlCSS: {
width: '350px',
top: '10px',
left: '',
right: '10px',
border: 'none',
padding: '5px',
opacity: 0.6,
cursor: 'default',
color: '#fff',
backgroundColor: '#000',
'-webkit-border-radius':'10px',
'-moz-border-radius': '10px',
'border-radius': '10px'
},
// IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w
// (hat tip to Jorge H. N. de Vasconcelos)
/*jshint scripturl:true */
iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank',
// force usage of iframe in non-IE browsers (handy for blocking applets)
forceIframe: false,
// z-index for the blocking overlay
baseZ: 1000,
// set these to true to have the message automatically centered
centerX: true, // <-- only effects element blocking (page block controlled via css above)
centerY: true,
// allow body element to be stetched in ie6; this makes blocking look better
// on "short" pages. disable if you wish to prevent changes to the body height
allowBodyStretch: true,
// enable if you want key and mouse events to be disabled for content that is blocked
bindEvents: true,
// be default blockUI will supress tab navigation from leaving blocking content
// (if bindEvents is true)
constrainTabKey: true,
// fadeIn time in millis; set to 0 to disable fadeIn on block
fadeIn: 200,
// fadeOut time in millis; set to 0 to disable fadeOut on unblock
fadeOut: 400,
// time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock
timeout: 0,
// disable if you don't want to show the overlay
showOverlay: true,
// if true, focus will be placed in the first available input field when
// page blocking
focusInput: true,
// elements that can receive focus
focusableElements: ':input:enabled:visible',
// suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity)
// no longer needed in 2012
// applyPlatformOpacityRules: true,
// callback method invoked when fadeIn has completed and blocking message is visible
onBlock: null,
// callback method invoked when unblocking has completed; the callback is
// passed the element that has been unblocked (which is the window object for page
// blocks) and the options that were passed to the unblock call:
// onUnblock(element, options)
onUnblock: null,
// callback method invoked when the overlay area is clicked.
// setting this will turn the cursor to a pointer, otherwise cursor defined in overlayCss will be used.
onOverlayClick: null,
// don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493
quirksmodeOffsetHack: 4,
// class name of the message block
blockMsgClass: 'blockMsg',
// if it is already blocked, then ignore it (don't unblock and reblock)
ignoreIfBlocked: false
};
// private data and functions follow...
var pageBlock = null;
var pageBlockEls = [];
function install(el, opts) {
var css, themedCSS;
var full = (el == window);
var msg = (opts && opts.message !== undefined ? opts.message : undefined);
opts = $.extend({}, $.blockUI.defaults, opts || {});
if (opts.ignoreIfBlocked && $(el).data('blockUI.isBlocked'))
return;
opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {});
css = $.extend({}, $.blockUI.defaults.css, opts.css || {});
if (opts.onOverlayClick)
opts.overlayCSS.cursor = 'pointer';
themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {});
msg = msg === undefined ? opts.message : msg;
// remove the current block (if there is one)
if (full && pageBlock)
remove(window, {fadeOut:0});
// if an existing element is being used as the blocking content then we capture
// its current place in the DOM (and current display style) so we can restore
// it when we unblock
if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) {
var node = msg.jquery ? msg[0] : msg;
var data = {};
$(el).data('blockUI.history', data);
data.el = node;
data.parent = node.parentNode;
data.display = node.style.display;
data.position = node.style.position;
if (data.parent)
data.parent.removeChild(node);
}
$(el).data('blockUI.onUnblock', opts.onUnblock);
var z = opts.baseZ;
// blockUI uses 3 layers for blocking, for simplicity they are all used on every platform;
// layer1 is the iframe layer which is used to supress bleed through of underlying content
// layer2 is the overlay layer which has opacity and a wait cursor (by default)
// layer3 is the message content that is displayed while blocking
var lyr1, lyr2, lyr3, s;
if (msie || opts.forceIframe)
lyr1 = $('<iframe class="blockUI" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="'+opts.iframeSrc+'"></iframe>');
else
lyr1 = $('<div class="blockUI" style="display:none"></div>');
if (opts.theme)
lyr2 = $('<div class="blockUI blockOverlay ui-widget-overlay" style="z-index:'+ (z++) +';display:none"></div>');
else
lyr2 = $('<div class="blockUI blockOverlay" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');
if (opts.theme && full) {
s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:fixed">';
if ( opts.title ) {
s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || ' ')+'</div>';
}
s += '<div class="ui-widget-content ui-dialog-content"></div>';
s += '</div>';
}
else if (opts.theme) {
s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:absolute">';
if ( opts.title ) {
s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || ' ')+'</div>';
}
s += '<div class="ui-widget-content ui-dialog-content"></div>';
s += '</div>';
}
else if (full) {
s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage" style="z-index:'+(z+10)+';display:none;position:fixed"></div>';
}
else {
s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement" style="z-index:'+(z+10)+';display:none;position:absolute"></div>';
}
lyr3 = $(s);
// if we have a message, style it
if (msg) {
if (opts.theme) {
lyr3.css(themedCSS);
lyr3.addClass('ui-widget-content');
}
else
lyr3.css(css);
}
// style the overlay
if (!opts.theme /*&& (!opts.applyPlatformOpacityRules)*/)
lyr2.css(opts.overlayCSS);
lyr2.css('position', full ? 'fixed' : 'absolute');
// make iframe layer transparent in IE
if (msie || opts.forceIframe)
lyr1.css('opacity',0.0);
//$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el);
var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el);
$.each(layers, function() {
this.appendTo($par);
});
if (opts.theme && opts.draggable && $.fn.draggable) {
lyr3.draggable({
handle: '.ui-dialog-titlebar',
cancel: 'li'
});
}
// ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling)
var expr = setExpr && (!$.support.boxModel || $('object,embed', full ? null : el).length > 0);
if (ie6 || expr) {
// give body 100% height
if (full && opts.allowBodyStretch && $.support.boxModel)
$('html,body').css('height','100%');
// fix ie6 issue when blocked element has a border width
if ((ie6 || !$.support.boxModel) && !full) {
var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth');
var fixT = t ? '(0 - '+t+')' : 0;
var fixL = l ? '(0 - '+l+')' : 0;
}
// simulate fixed position
$.each(layers, function(i,o) {
var s = o[0].style;
s.position = 'absolute';
if (i < 2) {
if (full)
s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.support.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"');
else
s.setExpression('height','this.parentNode.offsetHeight + "px"');
if (full)
s.setExpression('width','jQuery.support.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"');
else
s.setExpression('width','this.parentNode.offsetWidth + "px"');
if (fixL) s.setExpression('left', fixL);
if (fixT) s.setExpression('top', fixT);
}
else if (opts.centerY) {
if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');
s.marginTop = 0;
}
else if (!opts.centerY && full) {
var top = (opts.css && opts.css.top) ? parseInt(opts.css.top, 10) : 0;
var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"';
s.setExpression('top',expression);
}
});
}
// show the message
if (msg) {
if (opts.theme)
lyr3.find('.ui-widget-content').append(msg);
else
lyr3.append(msg);
if (msg.jquery || msg.nodeType)
$(msg).show();
}
if ((msie || opts.forceIframe) && opts.showOverlay)
lyr1.show(); // opacity is zero
if (opts.fadeIn) {
var cb = opts.onBlock ? opts.onBlock : noOp;
var cb1 = (opts.showOverlay && !msg) ? cb : noOp;
var cb2 = msg ? cb : noOp;
if (opts.showOverlay)
lyr2._fadeIn(opts.fadeIn, cb1);
if (msg)
lyr3._fadeIn(opts.fadeIn, cb2);
}
else {
if (opts.showOverlay)
lyr2.show();
if (msg)
lyr3.show();
if (opts.onBlock)
opts.onBlock.bind(lyr3)();
}
// bind key and mouse events
bind(1, el, opts);
if (full) {
pageBlock = lyr3[0];
pageBlockEls = $(opts.focusableElements,pageBlock);
if (opts.focusInput)
setTimeout(focus, 20);
}
else
center(lyr3[0], opts.centerX, opts.centerY);
if (opts.timeout) {
// auto-unblock
var to = setTimeout(function() {
if (full)
$.unblockUI(opts);
else
$(el).unblock(opts);
}, opts.timeout);
$(el).data('blockUI.timeout', to);
}
}
// remove the block
function remove(el, opts) {
var count;
var full = (el == window);
var $el = $(el);
var data = $el.data('blockUI.history');
var to = $el.data('blockUI.timeout');
if (to) {
clearTimeout(to);
$el.removeData('blockUI.timeout');
}
opts = $.extend({}, $.blockUI.defaults, opts || {});
bind(0, el, opts); // unbind events
if (opts.onUnblock === null) {
opts.onUnblock = $el.data('blockUI.onUnblock');
$el.removeData('blockUI.onUnblock');
}
var els;
if (full) // crazy selector to handle odd field errors in ie6/7
els = $('body').children().filter('.blockUI').add('body > .blockUI');
else
els = $el.find('>.blockUI');
// fix cursor issue
if ( opts.cursorReset ) {
if ( els.length > 1 )
els[1].style.cursor = opts.cursorReset;
if ( els.length > 2 )
els[2].style.cursor = opts.cursorReset;
}
if (full)
pageBlock = pageBlockEls = null;
if (opts.fadeOut) {
count = els.length;
els.stop().fadeOut(opts.fadeOut, function() {
if ( --count === 0)
reset(els,data,opts,el);
});
}
else
reset(els, data, opts, el);
}
// move blocking element back into the DOM where it started
function reset(els,data,opts,el) {
var $el = $(el);
if ( $el.data('blockUI.isBlocked') )
return;
els.each(function(i,o) {
// remove via DOM calls so we don't lose event handlers
if (this.parentNode)
this.parentNode.removeChild(this);
});
if (data && data.el) {
data.el.style.display = data.display;
data.el.style.position = data.position;
data.el.style.cursor = 'default'; // #59
if (data.parent)
data.parent.appendChild(data.el);
$el.removeData('blockUI.history');
}
if ($el.data('blockUI.static')) {
$el.css('position', 'static'); // #22
}
if (typeof opts.onUnblock == 'function')
opts.onUnblock(el,opts);
// fix issue in Safari 6 where block artifacts remain until reflow
var body = $(document.body), w = body.width(), cssW = body[0].style.width;
body.width(w-1).width(w);
body[0].style.width = cssW;
}
// bind/unbind the handler
function bind(b, el, opts) {
var full = el == window, $el = $(el);
// don't bother unbinding if there is nothing to unbind
if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked')))
return;
$el.data('blockUI.isBlocked', b);
// don't bind events when overlay is not in use or if bindEvents is false
if (!full || !opts.bindEvents || (b && !opts.showOverlay))
return;
// bind anchors and inputs for mouse and key events
var events = 'mousedown mouseup keydown keypress keyup touchstart touchend touchmove';
if (b)
$(document).bind(events, opts, handler);
else
$(document).unbind(events, handler);
// former impl...
// var $e = $('a,:input');
// b ? $e.bind(events, opts, handler) : $e.unbind(events, handler);
}
// event handler to suppress keyboard/mouse events when blocking
function handler(e) {
// allow tab navigation (conditionally)
if (e.type === 'keydown' && e.keyCode && e.keyCode == 9) {
if (pageBlock && e.data.constrainTabKey) {
var els = pageBlockEls;
var fwd = !e.shiftKey && e.target === els[els.length-1];
var back = e.shiftKey && e.target === els[0];
if (fwd || back) {
setTimeout(function(){focus(back);},10);
return false;
}
}
}
var opts = e.data;
var target = $(e.target);
if (target.hasClass('blockOverlay') && opts.onOverlayClick)
opts.onOverlayClick(e);
// allow events within the message content
if (target.parents('div.' + opts.blockMsgClass).length > 0)
return true;
// allow events for content that is not being blocked
return target.parents().children().filter('div.blockUI').length === 0;
}
function focus(back) {
if (!pageBlockEls)
return;
var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0];
if (e)
e.focus();
}
function center(el, x, y) {
var p = el.parentNode, s = el.style;
var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth');
var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth');
if (x) s.left = l > 0 ? (l+'px') : '0';
if (y) s.top = t > 0 ? (t+'px') : '0';
}
function sz(el, p) {
return parseInt($.css(el,p),10)||0;
}
}
/*global define:true */
if (typeof define === 'function' && define.amd && define.amd.jQuery) {
define(['jquery'], setup);
} else {
setup(jQuery);
}
})();
|
import React, { useContext } from 'react';
import { NavigationContext } from './Navigation';
const DEFAULT_OPTIONS = {
privacy: true,
optional: true,
}
export default (notes, options = DEFAULT_OPTIONS) => {
const { setPage } = useContext(NavigationContext);
const goPrivacy = () => setPage('privacy');
return (
<>
<span className="label">Notes</span>
<ul className="notes">
{options.optional && <li>all inputs are optional</li>}
{notes.map((note) => (
<li key={note}>{note}</li>
))}
<>
{options.privacy && <li>for information about data, see <button className="link" onClick={goPrivacy}>Privacy Policy</button></li>}
</>
</ul>
</>
);
};
|
import {React, useState, useEffect} from 'react'
import { BrowserRouter as Router, Link, Route, Switch } from 'react-router-dom'
import NaveBar from '../components/NaveBar'
import SearchPage from './SearchPage'
import FavoritesPage from './FavoritesPage'
import FeauturedPage from './FeauturedPage'
import "../styles/FavoritePage.css"
import "../styles/HomePage.css"
function HomePage() {
// movie component states
const [SingleMovieData, setSignelMovieData] = useState({})
const [imdbID, setimdbID] = useState("")
const [fav, setFav] = useState([])
useEffect(() => {
fetch(`http://www.omdbapi.com/?apikey=d8898664&i=${imdbID}`)
.then(res => res.json())
.then(data => setSignelMovieData(data))
}, [imdbID])
function storeLocaly(newMovie) {
fav.push(newMovie)
setFav(fav)
localStorage.setItem("favorites", JSON.stringify(fav));
}
return (
<Router>
<NaveBar/>
<Switch>
<Route path="/" exact>
<div>
<section className="infoContainer">
<h2>Welcome to The World of <br/> Movies!</h2>
<p>Its Just a Fun Project i created with My Beginner React skills!</p>
<Link className="btn-main" to="/">Take a tour</Link>
</section>
</div>
</Route>
<Route path="/search" exact>
<SearchPage handleClick={setimdbID} SingleMovieData={SingleMovieData} storeLocaly={storeLocaly}/>
</Route>
<Route path="/favorites" exact>
<FavoritesPage/>
</Route>
<Route path="/feautured">
<FeauturedPage page={2}/>
</Route>
</Switch>
</Router>
)
}
export default HomePage
|
import React, { Component } from "react";
import axios from "axios";
import PortfolioItem from "./portfolio-item";
export default class PortfolioContainer extends Component {
constructor() {
super();
this.state = {
pageTitle: "Welcome to my portfolio",
isLoading: false,
data: []
};
this.handleFilter = this.handleFilter.bind(this);
}
handleFilter(filter) {
if (filter === "CLEAR_FILTERS") {
this.getPortfolioItems();
} else {
this.getPortfolioItems(filter);
}
}
getPortfolioItems(filter = null) {
axios
.get("https://eduardosj.devcamp.space/portfolio/portfolio_items")
.then(response => {
if (filter) {
this.setState({
data: response.data.portfolio_items.filter(item => {
return item.category === filter;
}),
});
} else {
this.setState({
data: response.data.portfolio_items
});
}
})
.catch(error => {
console.log(error);
});
}
portfolioItems() {
return this.state.data.map(item => {
return <PortfolioItem key={item.id} item={item} />;
});
}
componentDidMount() {
this.getPortfolioItems();
}
render() {
if (this.state.isLoading) {
return <div>Loading...</div>;
}
return (
<div className="homepage-wrapper">
<div className="filter-links">
<button className="btn" onClick={() => this.handleFilter("eCommerce")}>
eCommerce
</button>
<button className="btn" onClick={() => this.handleFilter("Scheduling")}>
Scheduling
</button>
<button className="btn" onClick={() => this.handleFilter("Enterprise")}>
Enterprise
</button>
<button className="btn" onClick={() => this.handleFilter("CLEAR_FILTERS")}>
ALL
</button>
</div>
<div className="portfolio-items-wrapper">
{this.portfolioItems()}
</div>
</div>
);
}
}
|
/**
* Sinon.JS 1.5.0, 2012/10/19
*
* @author Christian Johansen (christian@cjohansen.no)
* @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS
*
* (The BSD License)
*
* Copyright (c) 2010-2012, Christian Johansen, christian@cjohansen.no
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Christian Johansen nor the names of his contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*global sinon, setTimeout, setInterval, clearTimeout, clearInterval, Date*/
/**
* Helps IE run the fake timers. By defining global functions, IE allows
* them to be overwritten at a later point. If these are not defined like
* this, overwriting them will result in anything from an exception to browser
* crash.
*
* If you don't require fake timers to work in IE, don't include this file.
*
* @author Christian Johansen (christian@cjohansen.no)
* @license BSD
*
* Copyright (c) 2010-2011 Christian Johansen
*/
function setTimeout() {}
function clearTimeout() {}
function setInterval() {}
function clearInterval() {}
function Date() {}
// Reassign the original functions. Now their writable attribute
// should be true. Hackish, I know, but it works.
setTimeout = sinon.timers.setTimeout;
clearTimeout = sinon.timers.clearTimeout;
setInterval = sinon.timers.setInterval;
clearInterval = sinon.timers.clearInterval;
Date = sinon.timers.Date;
/*global sinon*/
/**
* Helps IE run the fake XMLHttpRequest. By defining global functions, IE allows
* them to be overwritten at a later point. If these are not defined like
* this, overwriting them will result in anything from an exception to browser
* crash.
*
* If you don't require fake XHR to work in IE, don't include this file.
*
* @author Christian Johansen (christian@cjohansen.no)
* @license BSD
*
* Copyright (c) 2010-2011 Christian Johansen
*/
function XMLHttpRequest() {}
// Reassign the original function. Now its writable attribute
// should be true. Hackish, I know, but it works.
XMLHttpRequest = sinon.xhr.XMLHttpRequest || undefined;
|
// https://tonicdev.com/npm/msr
var MediaStreamRecorder = require('msr');
console.log('require-msr', MediaStreamRecorder);
console.log('\n\n-------\n\n');
var recorder = new MediaStreamRecorder({});
console.log('MediaStreamRecorder', recorder);
console.log('\n\n-------\n\n');
var multiStreamRecorder = new MediaStreamRecorder.MultiStreamRecorder({});
console.log('MultiStreamRecorder', multiStreamRecorder);
|
angular.module('ovh-api-services').service('OvhApiTelephonyOvhPabxDialplanExtensionConditionTimeV6', ($resource) => $resource('/telephony/:billingAccount/ovhPabx/:serviceName/dialplan/:dialplanId/extension/:extensionId/conditionTime/:conditionId', {
billingAccount: '@billingAccount',
serviceName: '@serviceName',
dialplanId: '@dialplanId',
extensionId: '@extensionId',
conditionId: '@conditionId',
}, {
getBatch: {
method: 'GET',
isArray: true,
headers: {
'X-Ovh-Batch': ',',
},
},
save: {
method: 'PUT',
isArray: false,
},
create: {
method: 'POST',
isArray: false,
},
}));
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[8],{254:function(t,e,n){var content=n(330);content.__esModule&&(content=content.default),"string"==typeof content&&(content=[[t.i,content,""]]),content.locals&&(t.exports=content.locals);(0,n(22).default)("66a9c1c4",content,!0,{sourceMap:!1})},257:function(t,e,n){var content=n(380);content.__esModule&&(content=content.default),"string"==typeof content&&(content=[[t.i,content,""]]),content.locals&&(t.exports=content.locals);(0,n(22).default)("cf101f88",content,!0,{sourceMap:!1})},274:function(t,e,n){"use strict";e.a={hello:"مرحبا بالعالم",doctor:"طبيب",auction:"المزاد",bid:"مزايدة",bids:"مزايدات",win:"رابح",end_time:"تاريخ الانتهاء",doctors:"الأطباء",pharmacy:"صيدلي",pharmacies:"الصيادلة",reservations:"الحجوزات",search:"البحث",setting:"الاعدادات",change_password:"تغيير كلمة السر",save:"حفظ",continue:"استمرار",job:"مهنة",aboutUs:"من نحن",features:"خصائص",reserve_now:"احجز الان",current_price:"السعر الحالي",min_increment:"حد الادنى للمزايدة",map:"خريطة",detail:"معلومات",wilaya:"ولاية",address:"عنوان",lng:"خط الطول",lat:"خط العرض",description:"وصف",close:"اغلاق",another_email:"يبدو ان هذا البريد الالكتروني موجود بالفعل",create:"انشاء",browse_products:"تصفح المنتجات",my_products:"منتوجاتي",new_product:"منتوج جديد",edit_product:"تعديل جديد",category:"الفئة",price:"السعر",images:"الصور",product:{name:"اسم المنتج",new:" جديد",used:"مستخدم"},auth:{username:"اسم المستخدم",login:"تسجيل الدخول",phone:"هاتف",forgot:"نسيت كلمة السر",email:"الريد الالكتروني",notAuthorized:"لا يمكنك تسجيل الدخول كلمة السر او البريد الالكتروني خاطئ",password:"كلمة السر",confirm_password:"تأكيد كلمة السر",name:"الاسم الكامل",remember:"تذكرني",register:"حساب جديد",avatar:"صورة حساب",change_password:"تغيير كلمة السر",logout:"تسجيل الخروج",current_password:"كلمة السر الحالية"},validation:{email:"يجب ان يكون البريد الاكتروني صحيح",unique:"هذا مستعمل من قبل",phone:"يجب ان يكون رقم الهاتف صحيح",required:"هذا الحقل مطلوب",confirm_password:"كلمة السر لا تطابق"},messages:{missed_phone:"لاستخدام حسابك تحتاج الى رقم هاتفك",unverified_phone:"يجب التحقق من رقم هاتفك",unverified_email:"يجب التحقق من البريدك الالكتروني",unverified_payment:"يجب التحقق من الدفع"},pages:{home:"الرئيسية",contacts:"اتصال"}}},288:function(t,e,n){"use strict";var r={name:"ProfileMenu",data:function(){return{verification:33,links:[{icon:"account",link:"/account/profile",name:"profile"},{icon:"shield-edit",link:"/setting/password",name:"auth.change_password"},{icon:"check-decagram",link:"/setting/profile",name:"verification"},{icon:"credit-card-settings-outline",link:"/setting/billing",name:"billing"}]}},computed:{auth:function(){return this.$auth.loggedIn},user:function(){return this.$auth.user}},methods:{logout:function(){this.$auth.logout(),this.$apollo.mutate({mutation:n(335)}),this.$apolloHelpers.onLogout(),this.$router.push("/auth/login")}}},o=n(68),c=n(79),l=n.n(c),v=n(197),d=n(220),m=n(198),f=n(78),_=n(442),h=n(199),k=n(162),w=n(200),x=n(126),V=n(201),L=n(202),y=n(29),I=n(108),C=n(443),$=n(456),component=Object(o.a)(r,(function(){var t=this,e=t.$createElement,n=t._self._c||e;return t.auth?n("v-menu",{attrs:{"nudge-width":200,"offset-x":""},scopedSlots:t._u([{key:"activator",fn:function(e){var r=e.on;return[n("v-btn",t._g({attrs:{icon:""}},r),[n("v-avatar",{attrs:{color:"color"}},[/(https?:\/\/[^\s]+)/.test(t.user.avatar)?n("v-img",{attrs:{alt:t.user.name,src:t.user.avatar}}):n("v-img",{attrs:{alt:t.user.name,src:"/storage/"+t.user.avatar}})],1)],1)]}}],null,!1,1688751899)},[t._v(" "),n("v-card",[n("v-list",[n("v-list-item",[n("v-list-item-avatar",[/(https?:\/\/[^\s]+)/.test(t.user.avatar)?n("v-img",{attrs:{alt:t.user.name,src:t.user.avatar}}):n("v-img",{attrs:{alt:t.user.name,src:"/storage/"+t.user.avatar}})],1),t._v(" "),n("v-list-item-content",[n("v-list-item-title",[t._v(t._s(t.user.name))]),t._v(" "),n("v-list-item-subtitle",[t.user.verified?n("span",[t._v("Verified")]):t._e()])],1),t._v(" "),n("v-list-item-action",[n("v-btn",{attrs:{nuxt:"",to:"/setting",icon:""}},[n("v-icon",[t._v("mdi-settings")])],1)],1)],1),t._v(" "),n("v-divider"),t._v(" "),t._l(t.links,(function(link){return n("v-list-item",{attrs:{to:link.link,nuxt:""}},[n("v-list-item-icon",[n("v-icon",[t._v("mdi-"+t._s(link.icon))])],1),t._v(" "),n("v-list-item-content",[n("v-list-item-title",[t._v(t._s(t.$t(link.name)))])],1)],1)}))],2),t._v(" "),n("v-card-actions",[n("v-spacer"),t._v(" "),n("v-btn",{attrs:{color:"red",dark:"",text:""},on:{click:function(e){return t.logout()}}},[n("v-icon",[t._v("mdi-power")]),t._v("\n "+t._s(t.$t("auth.logout"))+"\n ")],1),t._v(" "),n("v-spacer")],1)],1)],1):n("div",[n("v-btn",{staticClass:"white--text font-weight-black pink-special-bg",attrs:{nuxt:"",to:"/auth/login",rounded:""}},[t._v("\n تسجيل الدخول\n ")])],1)}),[],!1,null,"c6a77984",null),S=component.exports;l()(component,{VAvatar:v.a,VBtn:d.a,VCard:m.a,VCardActions:f.a,VDivider:_.a,VIcon:h.a,VImg:k.a,VList:w.a,VListItem:x.a,VListItemAction:V.a,VListItemAvatar:L.a,VListItemContent:y.a,VListItemIcon:I.a,VListItemSubtitle:y.b,VListItemTitle:y.c,VMenu:C.a,VSpacer:$.a});n(49);var A={name:"ChangeLang",mounted:function(){this.rtl()},methods:{rtl:function(){this.$vuetify.rtl="ar"===this.$i18n.locale},switchLang:function(t){this.$i18n.setLocaleCookie(t),this.$vuetify.rtl="ar"===t,this.$router.replace(this.switchLocalePath(t))}}},D=Object(o.a)(A,(function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("v-menu",{attrs:{"offset-y":""},scopedSlots:t._u([{key:"activator",fn:function(e){var r=e.on;return[n("v-btn",t._g({attrs:{color:"white",dark:"",icon:""}},r),[t._v("\n "+t._s(t.$i18n.locale)+" "),n("v-icon",[t._v("mdi-menu-down")])],1)]}}])},[t._v(" "),n("v-list",t._l(t.$i18n.locales,(function(e){return n("v-list-item",{on:{click:function(n){return t.switchLang(e.code)}}},[n("v-list-item-title",[t._v(t._s(e.name))])],1)})),1)],1)}),[],!1,null,"bc2ed00e",null),E=D.exports;l()(D,{VBtn:d.a,VIcon:h.a,VList:w.a,VListItem:x.a,VListItemTitle:y.c,VMenu:C.a});var N={components:{ProfileMenu:S,ChangeLang:E},data:function(){return{links:[{icon:"facebook",link:"https://www.fb.com"},{icon:"instagram",link:"https://www.instagram.com"},{icon:"twitter",link:"https://www.twitter.com"}],drawer:!1,items:[{title:"blog",icon:"mdi-help-box"}]}},computed:{auth:function(){return this.$auth.loggedIn}},mounted:function(){},methods:{}},M=(n(379),n(452)),F=n(457),T=n(458),j=n(459),O=n(460),B=n(461),P=n(462),z=n(463),H=n(464),G=Object(o.a)(N,(function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("v-app",{attrs:{light:""}},[t.$vuetify.breakpoint.smAndDown?n("v-navigation-drawer",{attrs:{app:"",fixed:"",dark:"",color:"pink darken-3"},model:{value:t.drawer,callback:function(e){t.drawer=e},expression:"drawer"}},[n("v-list",{staticClass:"py-0",attrs:{dense:"",nav:""}},[n("v-list-item",{attrs:{"two-line":""}},[n("v-list-item-avatar",[n("v-img",{attrs:{src:"https://randomuser.me/api/portraits/men/81.jpg"}})],1),t._v(" "),n("v-list-item-content",[n("v-list-item-title",[t._v("Application")]),t._v(" "),n("v-list-item-subtitle",[t._v("Subtext")])],1)],1),t._v(" "),n("v-divider"),t._v(" "),t._l(t.items,(function(e){return n("v-list-item",{key:e.title,attrs:{to:e.link,nuxt:""}},[n("v-list-item-icon",[n("v-icon",[t._v(t._s(e.icon))])],1),t._v(" "),n("v-list-item-content",[n("v-list-item-title",[t._v(t._s(t.$t(e.title)))])],1)],1)}))],2)],1):t._e(),t._v(" "),n("v-app-bar",{attrs:{"elevate-on-scroll":"",color:"white",light:"",app:""}},[n("v-container",{staticClass:"pa-0 fill-height"},[t.$vuetify.breakpoint.smAndDown?n("v-app-bar-nav-icon",{on:{click:function(e){t.drawer=!t.drawer}}}):t._e(),t._v(" "),n("v-btn",{staticClass:"font-weight-black pink-special-text",attrs:{nuxt:"",to:"/",color:"pink darken-3",text:""}},[t._v("الرئيسية")]),t._v(" "),n("v-btn",{staticClass:"font-weight-black pink-special-text",attrs:{text:""}},[t._v("اعلانات ثابتة")]),t._v(" "),n("v-btn",{staticClass:"font-weight-black pink-special-text",attrs:{nuxt:"",to:"/page/about-us",text:""}},[t._v("من نحن")]),t._v(" "),n("v-spacer"),t._v(" "),n("nuxt-link",{staticClass:"pa-0",attrs:{to:"/"}},[n("v-img",{attrs:{src:"/logo.png",width:"100px",height:"64px"}})],1),t._v(" "),n("v-spacer"),t._v(" "),n("ProfileMenu")],1)],1),t._v(" "),n("v-main",[n("nuxt")],1),t._v(" "),n("v-footer",{attrs:{color:"white",padless:""}},[n("v-row",{attrs:{justify:"center","no-gutters":""}},[t._l(t.links,(function(link){return n("v-btn",{key:link,staticClass:"my-2",attrs:{href:link.link,color:"black",text:"",taget:"_blank",tag:"a",rounded:""}},[n("v-icon",[t._v("mdi-"+t._s(link.icon))])],1)})),t._v(" "),n("v-col",{attrs:{cols:"12"}},[n("v-container",[n("v-row",[n("v-col",{attrs:{cols:"12",md:"6",sm:"12"}},[n("v-card",{attrs:{color:"transparent",flat:""}},[n("v-card-title",[t._v("مزادك للمزادات")]),t._v(" "),n("v-card-text",[t._v("\n شركة قطرية ,\n توفر منصة موثوقة للمزاد الالكتروني تتيح من خلالها عرض العقارات\n والأصول والسلع والمنتجات بغرض بيعها عن طريق المزادات, وتتميز\n المنصة بالمرونة في البيع والشراء الكترونياً وتهدف لافعال مبدأ\n العدالة والشفافية والنزاهة وتكافؤ الفرص وبخضوع تام للعرض\n والطلب.\n ")])],1)],1),t._v(" "),n("v-col",{attrs:{cols:"12",md:"3",sm:"12"}},[n("v-card",{attrs:{color:"transparent",flat:""}},[n("v-card-title",[t._v("اعرف عنا")]),t._v(" "),n("v-card-text",[n("v-btn",{attrs:{tag:"a",small:"",nuxt:"",to:"/page/about-us",text:""}},[t._v("من نحن ؟")]),n("br"),t._v(" "),n("v-btn",{attrs:{tag:"a",small:"",nuxt:"",to:"/page/privacy",text:""}},[t._v("سياسة الخصوصية")]),n("br"),t._v(" "),n("v-btn",{attrs:{tag:"a",small:"",nuxt:"",to:"/terms",text:""}},[t._v("شروط الاستخدام")]),n("br")],1)],1)],1),t._v(" "),n("v-col",{attrs:{cols:"12",md:"3",sm:"12"}},[n("v-card",{attrs:{color:"transparent",flat:""}},[n("v-card-title",[t._v("روابط هامة")]),t._v(" "),n("v-card-text",[n("v-btn",{attrs:{tag:"a",small:"",nuxt:"",to:"/how",text:""}},[t._v("كيفية العمل")]),n("br"),t._v(" "),n("v-btn",{attrs:{tag:"a",small:"",nuxt:"",to:"/questions",text:""}},[t._v("اسئلة شائعة")]),n("br"),t._v(" "),n("v-btn",{attrs:{tag:"a",small:"",nuxt:"",to:"/ticket/list",text:""}},[t._v("الدعم")]),n("br")],1)],1)],1)],1)],1)],1),t._v(" "),n("v-col",{staticClass:"py-4 text-center",attrs:{cols:"12"}},[t._v("\n "+t._s((new Date).getFullYear())+" — "),n("strong",[t._v("© mazadak")])])],2)],1)],1)}),[],!1,null,null,null);e.a=G.exports;l()(G,{VApp:M.a,VAppBar:F.a,VAppBarNavIcon:T.a,VBtn:d.a,VCard:m.a,VCardText:f.b,VCardTitle:f.c,VCol:j.a,VContainer:O.a,VDivider:_.a,VFooter:B.a,VIcon:h.a,VImg:k.a,VList:w.a,VListItem:x.a,VListItemAvatar:L.a,VListItemContent:y.a,VListItemIcon:I.a,VListItemSubtitle:y.b,VListItemTitle:y.c,VMain:P.a,VNavigationDrawer:z.a,VRow:H.a,VSpacer:$.a})},304:function(t,e,n){t.exports=n(305)},321:function(t,e,n){"use strict";n.r(e),e.default=function(t){var e=t.store,n=t.redirect;e.$auth.loggedIn&&n("/home")}},322:function(t,e,n){"use strict";n.r(e),e.default=function(t){t.isHMR,t.app,t.store,t.route,t.params,t.error,t.redirect;var e=new Date;e.setTime(e.getTime()+31536e6),document.cookie="lang=ar; path=/; expires="+e.toUTCString(),console.log("lang")}},329:function(t,e,n){"use strict";n(254)},330:function(t,e,n){var r=n(21)((function(i){return i[1]}));r.push([t.i,"h1[data-v-bb822b6a]{font-size:20px}",""]),t.exports=r},335:function(t,e){var n={kind:"Document",definitions:[{kind:"OperationDefinition",operation:"mutation",variableDefinitions:[],directives:[],selectionSet:{kind:"SelectionSet",selections:[{kind:"Field",name:{kind:"Name",value:"logout"},arguments:[],directives:[],selectionSet:{kind:"SelectionSet",selections:[{kind:"Field",name:{kind:"Name",value:"status"},arguments:[],directives:[]},{kind:"Field",name:{kind:"Name",value:"message"},arguments:[],directives:[]}]}}]}}],loc:{start:0,end:53}};n.loc.source={body:"mutation\n{\n logout\n {\n status\n message\n }\n}\n",name:"GraphQL request",locationOffset:{line:1,column:1}};function r(t,e){if("FragmentSpread"===t.kind)e.add(t.name.value);else if("VariableDefinition"===t.kind){var n=t.type;"NamedType"===n.kind&&e.add(n.name.value)}t.selectionSet&&t.selectionSet.selections.forEach((function(t){r(t,e)})),t.variableDefinitions&&t.variableDefinitions.forEach((function(t){r(t,e)})),t.definitions&&t.definitions.forEach((function(t){r(t,e)}))}var o={};n.definitions.forEach((function(t){if(t.name){var e=new Set;r(t,e),o[t.name.value]=e}})),t.exports=n},379:function(t,e,n){"use strict";n(257)},380:function(t,e,n){var r=n(21)((function(i){return i[1]}));r.push([t.i,".pink-special-text{color:#8e143a}.pink-special-bg{background:#b51a57;background:linear-gradient(90deg,#b51a57,#803150)}",""]),t.exports=r},396:function(t,e,n){"use strict";n.r(e),n.d(e,"state",(function(){return r})),n.d(e,"mutations",(function(){return o}));n(45),n(31);var r=function(){return{locales:["en","ar"],locale:"en"}},o={SET_LANG:function(t,e){t.locales.includes(e)&&(t.locale=e)}}},89:function(t,e,n){"use strict";var r={layout:"empty",props:{error:{type:Object,default:null}},head:function(){return{title:404===this.error.statusCode?this.pageNotFound:this.otherError}},data:function(){return{pageNotFound:"404 Not Found",otherError:"An error occurred"}}},o=(n(329),n(68)),c=n(79),l=n.n(c),v=n(452),component=Object(o.a)(r,(function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("v-app",{attrs:{dark:""}},[404===t.error.statusCode?n("h1",[t._v("\n "+t._s(t.pageNotFound)+"\n ")]):n("h1",[t._v("\n "+t._s(t.otherError)+"\n ")]),t._v(" "),n("NuxtLink",{attrs:{to:"/"}},[t._v("\n Home page\n ")])],1)}),[],!1,null,"bb822b6a",null);e.a=component.exports;l()(component,{VApp:v.a})}},[[304,37,10,12,13,11,39,42,40,45,46,47,48,41,38,52,51,43,50,49,44,9,6,7]]]);
|
const User = require('./User');
const Notes = require('./Note');
module.exports = { User, Notes };
|
import create from "zustand";
import produce from "immer";
// 这里使用Map存储数据,Map可以保证元素的插入顺序不变,并且拥有log2n的效率
// 设计上,该hook提供了一些简便的modifier,可以根据需要模仿定制
// Map的增删机制是顺序的,添加永远在末尾,修改一定要用set,如果没有则添加,有则修改
// 修改某一元素的某一项内容,推荐用get,然后赋值,这样保证异步操作,同时该元素的其他项目保持不变,写法也很简单
// zustand在运行时会开辟一个独立的状态机,全局的hook
// create函数接收一个自动生成的set函数,set可以实现从n到n+1的状态修改(所有modifier都是set包装的函数,只要输出是difference就可以了)
// immer 保证了直接用brains修改数据会异常,而且代码写出来更优雅
const useControls = create((set) => ({
controls: {
oit: false,
grid: true,
axis: ["x", "y", "z"],
background: true,
slicing: false,
sliceX: { visible: true, value: 66 },
sliceY: { visible: true, value: 40 },
sliceZ: { visible: true, value: 57 },
camera: { far: 10000, position: [300, 200, 300] },
},
setCamera: (camera) =>
set(
produce((state) => {
state.controls.camera = camera;
})
),
setOit: (flag) =>
set(
produce((state) => {
state.controls.oit = flag;
})
),
setSliceX: (flag, value) =>
set(
produce((state) => {
state.controls.sliceX.visible = flag;
state.controls.sliceX.value = value;
})
),
setSliceY: (flag, value) =>
set(
produce((state) => {
state.controls.sliceY.visible = flag;
state.controls.sliceY.value = value;
})
),
setSliceZ: (flag, value) =>
set(
produce((state) => {
state.controls.sliceZ.visible = flag;
state.controls.sliceZ.value = value;
})
),
setGrid: (flag) =>
set(
produce((state) => {
state.controls.grid = flag;
})
),
setAxis: (val) =>
set(
produce((state) => {
state.controls.axis = val;
})
),
setBackground: (flag) =>
set(
produce((state) => {
state.controls.background = flag;
})
),
setSlicing: (flag) =>
set(
produce((state) => {
state.controls.slicing = flag;
})
),
}));
export default useControls;
|
// Generated by BUCKLESCRIPT VERSION 2.2.0, PLEASE EDIT WITH CARE
'use strict';
var Curry = require("bs-platform/lib/js/curry.js");
var Js_boolean = require("bs-platform/lib/js/js_boolean.js");
var ReasonReact = require("reason-react/lib/js/src/ReasonReact.js");
var Js_primitive = require("bs-platform/lib/js/js_primitive.js");
var Js_undefined = require("bs-platform/lib/js/js_undefined.js");
var ReactNative = require("react-native");
var UtilsRN$BsReactNative = require("../private/utilsRN.js");
function scrollToEnd(ref, animated) {
ref.scrollToEnd({
animated: Js_boolean.to_js_boolean(animated)
});
return /* () */0;
}
function scrollToIndex(ref, index, animated, viewOffset, viewPosition, _) {
ref._scrollToIndex({
index: index,
viewOffset: Js_undefined.fromOption(viewOffset),
viewPosition: Js_undefined.fromOption(viewPosition),
animated: Js_undefined.fromOption(animated)
});
return /* () */0;
}
function scrollToItem(ref, item, animated, viewPosition, _) {
ref._scrollToIndex({
item: item,
viewPosition: Js_undefined.fromOption(viewPosition),
animated: Js_undefined.fromOption(animated)
});
return /* () */0;
}
function scrollToOffset(ref, offset, animated, _) {
ref._scrollToIndex({
offset: Js_undefined.fromOption(offset),
animated: Js_undefined.fromOption(animated)
});
return /* () */0;
}
function renderItem(reRenderItem, jsRenderBag) {
return Curry._1(reRenderItem, /* record */[
/* item */jsRenderBag.item,
/* index */jsRenderBag.index
]);
}
function separatorComponent(reSeparatorComponent, jsSeparatorProps) {
return Curry._1(reSeparatorComponent, /* record */[
/* highlighted */+jsSeparatorProps.highlighted,
/* leadingItem */Js_primitive.undefined_to_opt(jsSeparatorProps.leadingItem)
]);
}
function make(data, renderItem, keyExtractor, itemSeparatorComponent, bounces, listFooterComponent, listHeaderComponent, columnWrapperStyle, extraData, getItemLayout, horizontal, initialNumToRender, initialScrollIndex, numColumns, onEndReached, onEndReachedThreshold, onRefresh, onViewableItemsChanged, overScrollMode, pagingEnabled, refreshing, removeClippedSubviews, scrollEnabled, showsHorizontalScrollIndicator, showsVerticalScrollIndicator, windowSize, maxToRenderPerBatch, viewabilityConfig, onScroll, style) {
var partial_arg = {
bounces: Js_undefined.fromOption(UtilsRN$BsReactNative.optBoolToOptJsBoolean(bounces)),
ItemSeparatorComponent: Js_undefined.fromOption(itemSeparatorComponent),
ListFooterComponent: Js_undefined.fromOption(listFooterComponent),
ListHeaderComponent: Js_undefined.fromOption(listHeaderComponent),
columnWrapperStyle: Js_undefined.fromOption(columnWrapperStyle),
data: data,
extraData: Js_undefined.fromOption(extraData),
getItemLayout: Js_undefined.fromOption(UtilsRN$BsReactNative.option_map((function (f, data, index) {
return Curry._2(f, data === undefined ? /* None */0 : [data], index);
}), getItemLayout)),
horizontal: Js_undefined.fromOption(UtilsRN$BsReactNative.optBoolToOptJsBoolean(horizontal)),
initialNumToRender: Js_undefined.fromOption(initialNumToRender),
initialScrollIndex: Js_undefined.fromOption(initialScrollIndex),
keyExtractor: keyExtractor,
numColumns: Js_undefined.fromOption(numColumns),
onEndReached: Js_undefined.fromOption(onEndReached),
onEndReachedThreshold: Js_undefined.fromOption(onEndReachedThreshold),
onRefresh: Js_undefined.fromOption(onRefresh),
onViewableItemsChanged: Js_undefined.fromOption(onViewableItemsChanged),
overScrollMode: Js_undefined.fromOption(UtilsRN$BsReactNative.option_map((function (x) {
if (x !== -958984497) {
if (x >= 422592140) {
return "never";
} else {
return "auto";
}
} else {
return "always";
}
}), overScrollMode)),
pagingEnabled: Js_undefined.fromOption(UtilsRN$BsReactNative.optBoolToOptJsBoolean(pagingEnabled)),
refreshing: Js_undefined.fromOption(UtilsRN$BsReactNative.optBoolToOptJsBoolean(refreshing)),
renderItem: renderItem,
removeClippedSubviews: Js_undefined.fromOption(UtilsRN$BsReactNative.optBoolToOptJsBoolean(removeClippedSubviews)),
scrollEnabled: Js_undefined.fromOption(UtilsRN$BsReactNative.optBoolToOptJsBoolean(scrollEnabled)),
showsHorizontalScrollIndicator: Js_undefined.fromOption(UtilsRN$BsReactNative.optBoolToOptJsBoolean(showsHorizontalScrollIndicator)),
showsVerticalScrollIndicator: Js_undefined.fromOption(UtilsRN$BsReactNative.optBoolToOptJsBoolean(showsVerticalScrollIndicator)),
windowSize: Js_undefined.fromOption(windowSize),
maxToRenderPerBatch: Js_undefined.fromOption(maxToRenderPerBatch),
viewabilityConfig: Js_undefined.fromOption(viewabilityConfig),
onScroll: Js_undefined.fromOption(onScroll),
style: Js_undefined.fromOption(style)
};
var partial_arg$1 = ReactNative.FlatList;
return (function (param) {
return ReasonReact.wrapJsForReason(partial_arg$1, partial_arg, param);
});
}
exports.scrollToEnd = scrollToEnd;
exports.scrollToIndex = scrollToIndex;
exports.scrollToItem = scrollToItem;
exports.scrollToOffset = scrollToOffset;
exports.renderItem = renderItem;
exports.separatorComponent = separatorComponent;
exports.make = make;
/* ReasonReact Not a pure module */
|
import { Model } from 'backbone';
import { result, forEach } from 'underscore';
import Frames from 'canvas/model/Frames';
export default class Page extends Model {
defaults() {
return {
frames: [],
_undo: true
};
}
initialize(props, opts = {}) {
const { config = {} } = opts;
const { em } = config;
const defFrame = {};
this.em = em;
if (!props.frames) {
defFrame.component = props.component;
defFrame.styles = props.styles;
['component', 'styles'].map(i => this.unset(i));
}
const frms = props.frames || [defFrame];
const frames = new Frames(frms, config);
frames.page = this;
this.set('frames', frames);
const um = em && em.get('UndoManager');
um && um.add(frames);
}
onRemove() {
this.get('frames').reset();
}
getFrames() {
return this.get('frames');
}
getMainFrame() {
return this.getFrames().at(0);
}
getMainComponent() {
const frame = this.getMainFrame();
return frame && frame.getComponent();
}
toJSON(opts = {}) {
const obj = Model.prototype.toJSON.call(this, opts);
const defaults = result(this, 'defaults');
// Remove private keys
forEach(obj, (value, key) => {
key.indexOf('_') === 0 && delete obj[key];
});
forEach(defaults, (value, key) => {
if (obj[key] === value) delete obj[key];
});
return obj;
}
}
|
import {Program} from "../../../../../webgl/Program.js";
import {RENDER_PASSES} from "../../../RENDER_PASSES.js";
import {createRTCViewMat, getPlaneRTCPos} from "../../../../../math/rtcCoords.js";
import {math} from "../../../../../math/math.js";
import {WEBGL_INFO} from "../../../../../webglInfo.js";
const tempVec3a = math.vec3();
/**
* @private
*/
class LinesInstancingSilhouetteRenderer {
constructor(scene) {
this._scene = scene;
this._hash = this._getHash();
this._allocate();
}
getValid() {
return this._hash === this._getHash();
};
_getHash() {
return this._scene._sectionPlanesState.getHash();
}
drawLayer(frameCtx, instancingLayer, renderPass) {
const model = instancingLayer.model;
const scene = model.scene;
const camera = scene.camera;
const gl = scene.canvas.gl;
const state = instancingLayer._state;
const instanceExt = this._instanceExt;
const rtcCenter = instancingLayer._state.rtcCenter;
if (!this._program) {
this._allocate(instancingLayer.model.scene);
if (this.errors) {
return;
}
}
if (frameCtx.lastProgramId !== this._program.id) {
frameCtx.lastProgramId = this._program.id;
this._bindProgram();
}
gl.uniform1i(this._uRenderPass, renderPass);
if (renderPass === RENDER_PASSES.SILHOUETTE_XRAYED) {
const material = scene.xrayMaterial._state;
const fillColor = material.fillColor;
const fillAlpha = material.fillAlpha;
gl.uniform4f(this._uColor, fillColor[0], fillColor[1], fillColor[2], fillAlpha);
} else if (renderPass === RENDER_PASSES.SILHOUETTE_HIGHLIGHTED) {
const material = scene.highlightMaterial._state;
const fillColor = material.fillColor;
const fillAlpha = material.fillAlpha;
gl.uniform4f(this._uColor, fillColor[0], fillColor[1], fillColor[2], fillAlpha);
} else if (renderPass === RENDER_PASSES.SILHOUETTE_SELECTED) {
const material = scene.selectedMaterial._state;
const fillColor = material.fillColor;
const fillAlpha = material.fillAlpha;
gl.uniform4f(this._uColor, fillColor[0], fillColor[1], fillColor[2], fillAlpha);
} else {
gl.uniform4fv(this._uColor, math.vec3([1, 1, 1]));
}
gl.uniformMatrix4fv(this._uViewMatrix, false, (rtcCenter) ? createRTCViewMat(camera.viewMatrix, rtcCenter) : camera.viewMatrix);
gl.uniformMatrix4fv(this._uWorldMatrix, false, model.worldMatrix);
gl.lineWidth(scene.linesMaterial.lineWidth);
const numSectionPlanes = scene._sectionPlanesState.sectionPlanes.length;
if (numSectionPlanes > 0) {
const sectionPlanes = scene._sectionPlanesState.sectionPlanes;
const baseIndex = instancingLayer.layerIndex * numSectionPlanes;
const renderFlags = model.renderFlags;
for (let sectionPlaneIndex = 0; sectionPlaneIndex < numSectionPlanes; sectionPlaneIndex++) {
const sectionPlaneUniforms = this._uSectionPlanes[sectionPlaneIndex];
if (sectionPlaneUniforms) {
const active = renderFlags.sectionPlanesActivePerLayer[baseIndex + sectionPlaneIndex];
gl.uniform1i(sectionPlaneUniforms.active, active ? 1 : 0);
if (active) {
const sectionPlane = sectionPlanes[sectionPlaneIndex];
if (rtcCenter) {
const rtcSectionPlanePos = getPlaneRTCPos(sectionPlane.dist, sectionPlane.dir, rtcCenter, tempVec3a);
gl.uniform3fv(sectionPlaneUniforms.pos, rtcSectionPlanePos);
} else {
gl.uniform3fv(sectionPlaneUniforms.pos, sectionPlane.pos);
}
gl.uniform3fv(sectionPlaneUniforms.dir, sectionPlane.dir);
}
}
}
}
gl.uniformMatrix4fv(this._uPositionsDecodeMatrix, false, instancingLayer._state.positionsDecodeMatrix);
this._aModelMatrixCol0.bindArrayBuffer(state.modelMatrixCol0Buf);
this._aModelMatrixCol1.bindArrayBuffer(state.modelMatrixCol1Buf);
this._aModelMatrixCol2.bindArrayBuffer(state.modelMatrixCol2Buf);
instanceExt.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location, 1);
instanceExt.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location, 1);
instanceExt.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location, 1);
this._aPosition.bindArrayBuffer(state.positionsBuf);
this._aFlags.bindArrayBuffer(state.flagsBuf, gl.UNSIGNED_BYTE, true);
instanceExt.vertexAttribDivisorANGLE(this._aFlags.location, 1);
if (this._aFlags2) {
this._aFlags2.bindArrayBuffer(state.flags2Buf, gl.UNSIGNED_BYTE, true);
instanceExt.vertexAttribDivisorANGLE(this._aFlags2.location, 1);
}
if (this._aOffset) {
this._aOffset.bindArrayBuffer(state.offsetsBuf);
instanceExt.vertexAttribDivisorANGLE(this._aOffset.location, 1);
}
state.indicesBuf.bind();
instanceExt.drawElementsInstancedANGLE(gl.LINES, state.indicesBuf.numItems, state.indicesBuf.itemType, 0, state.numInstances);
instanceExt.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location, 0); // TODO: Is this needed
instanceExt.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location, 0);
instanceExt.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location, 0);
instanceExt.vertexAttribDivisorANGLE(this._aFlags.location, 0);
if (this._aFlags2) {
instanceExt.vertexAttribDivisorANGLE(this._aFlags2.location, 0);
}
if (this._aOffset) {
instanceExt.vertexAttribDivisorANGLE(this._aOffset.location, 0);
}
}
_allocate() {
const scene = this._scene;
const gl = scene.canvas.gl;
const sectionPlanesState = scene._sectionPlanesState;
this._program = new Program(gl, this._buildShader());
if (this._program.errors) {
this.errors = this._program.errors;
return;
}
this._instanceExt = gl.getExtension("ANGLE_instanced_arrays");
const program = this._program;
this._uRenderPass = program.getLocation("renderPass");
this._uPositionsDecodeMatrix = program.getLocation("positionsDecodeMatrix");
this._uWorldMatrix = program.getLocation("worldMatrix");
this._uViewMatrix = program.getLocation("viewMatrix");
this._uProjMatrix = program.getLocation("projMatrix");
this._uColor = program.getLocation("color");
this._uSectionPlanes = [];
const clips = sectionPlanesState.sectionPlanes;
for (let i = 0, len = clips.length; i < len; i++) {
this._uSectionPlanes.push({
active: program.getLocation("sectionPlaneActive" + i),
pos: program.getLocation("sectionPlanePos" + i),
dir: program.getLocation("sectionPlaneDir" + i)
});
}
this._aPosition = program.getAttribute("position");
this._aOffset = program.getAttribute("offset");
this._aFlags = program.getAttribute("flags");
this._aFlags2 = program.getAttribute("flags2");
this._aModelMatrixCol0 = program.getAttribute("modelMatrixCol0");
this._aModelMatrixCol1 = program.getAttribute("modelMatrixCol1");
this._aModelMatrixCol2 = program.getAttribute("modelMatrixCol2");
if ( scene.logarithmicDepthBufferEnabled) {
this._uLogDepthBufFC = program.getLocation("logDepthBufFC");
}
}
_bindProgram() {
const scene = this._scene;
const gl = scene.canvas.gl;
const project = scene.camera.project;
this._program.bind();
gl.uniformMatrix4fv(this._uProjMatrix, false, project.matrix);
if ( scene.logarithmicDepthBufferEnabled) {
const logDepthBufFC = 2.0 / (Math.log(project.far + 1.0) / Math.LN2);
gl.uniform1f(this._uLogDepthBufFC, logDepthBufFC);
}
}
_buildShader() {
return {
vertex: this._buildVertexShader(),
fragment: this._buildFragmentShader()
};
}
_buildVertexShader() {
const scene = this._scene;
const sectionPlanesState = scene._sectionPlanesState;
const clipping = sectionPlanesState.sectionPlanes.length > 0;
const src = [];
src.push("// Lines instancing silhouette vertex shader");
if (scene.logarithmicDepthBufferEnabled && WEBGL_INFO.SUPPORTED_EXTENSIONS["EXT_frag_depth"]) {
src.push("#extension GL_EXT_frag_depth : enable");
}
src.push("uniform int renderPass;");
src.push("attribute vec3 position;");
if (scene.entityOffsetsEnabled) {
src.push("attribute vec3 offset;");
}
src.push("attribute vec4 flags;");
src.push("attribute vec4 flags2;");
src.push("attribute vec4 modelMatrixCol0;"); // Modeling matrix
src.push("attribute vec4 modelMatrixCol1;");
src.push("attribute vec4 modelMatrixCol2;");
src.push("uniform mat4 worldMatrix;");
src.push("uniform mat4 viewMatrix;");
src.push("uniform mat4 projMatrix;");
src.push("uniform mat4 positionsDecodeMatrix;");
if (scene.logarithmicDepthBufferEnabled) {
src.push("uniform float logDepthBufFC;");
if (WEBGL_INFO.SUPPORTED_EXTENSIONS["EXT_frag_depth"]) {
src.push("varying float vFragDepth;");
}
}
src.push("uniform vec4 color;");
if (clipping) {
src.push("varying vec4 vWorldPosition;");
src.push("varying vec4 vFlags2;");
}
src.push("void main(void) {");
// flags.y = NOT_RENDERED | SILHOUETTE_HIGHLIGHTED | SILHOUETTE_SELECTED | | SILHOUETTE_XRAYED
// renderPass = SILHOUETTE_HIGHLIGHTED | SILHOUETTE_SELECTED | | SILHOUETTE_XRAYED
src.push(`if (int(flags.y) != renderPass) {`);
src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"); // Cull vertex
src.push("} else {");
src.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");
src.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");
if (scene.entityOffsetsEnabled) {
src.push(" worldPosition.xyz = worldPosition.xyz + offset;");
}
src.push("vec4 viewPosition = viewMatrix * worldPosition; ");
if (clipping) {
src.push("vWorldPosition = worldPosition;");
src.push("vFlags2 = flags2;");
}
src.push("vec4 clipPos = projMatrix * viewPosition;");
if (scene.logarithmicDepthBufferEnabled) {
if (WEBGL_INFO.SUPPORTED_EXTENSIONS["EXT_frag_depth"]) {
src.push("vFragDepth = 1.0 + clipPos.w;");
} else {
src.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;");
src.push("clipPos.z *= clipPos.w;");
}
}
src.push("gl_Position = clipPos;");
src.push("}");
src.push("}");
return src;
}
_buildFragmentShader() {
const scene = this._scene;
const sectionPlanesState = scene._sectionPlanesState;
const clipping = sectionPlanesState.sectionPlanes.length > 0;
const src = [];
src.push("// Lines instancing silhouette fragment shader");
if (scene.logarithmicDepthBufferEnabled && WEBGL_INFO.SUPPORTED_EXTENSIONS["EXT_frag_depth"]) {
src.push("#extension GL_EXT_frag_depth : enable");
}
src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");
src.push("precision highp float;");
src.push("precision highp int;");
src.push("#else");
src.push("precision mediump float;");
src.push("precision mediump int;");
src.push("#endif");
if (scene.logarithmicDepthBufferEnabled && WEBGL_INFO.SUPPORTED_EXTENSIONS["EXT_frag_depth"]) {
src.push("uniform float logDepthBufFC;");
src.push("varying float vFragDepth;");
}
if (clipping) {
src.push("varying vec4 vWorldPosition;");
src.push("varying vec4 vFlags2;");
for (let i = 0, len = sectionPlanesState.sectionPlanes.length; i < len; i++) {
src.push("uniform bool sectionPlaneActive" + i + ";");
src.push("uniform vec3 sectionPlanePos" + i + ";");
src.push("uniform vec3 sectionPlaneDir" + i + ";");
}
}
src.push("uniform vec4 color;");
src.push("void main(void) {");
if (clipping) {
src.push(" bool clippable = (float(vFlags2.x) > 0.0);");
src.push(" if (clippable) {");
src.push(" float dist = 0.0;");
for (let i = 0, len = sectionPlanesState.sectionPlanes.length; i < len; i++) {
src.push("if (sectionPlaneActive" + i + ") {");
src.push(" dist += clamp(dot(-sectionPlaneDir" + i + ".xyz, vWorldPosition.xyz - sectionPlanePos" + i + ".xyz), 0.0, 1000.0);");
src.push("}");
}
src.push("if (dist > 0.0) { discard; }");
src.push("}");
}
if (scene.logarithmicDepthBufferEnabled && WEBGL_INFO.SUPPORTED_EXTENSIONS["EXT_frag_depth"]) {
src.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;");
}
src.push("gl_FragColor = color;");
src.push("}");
return src;
}
webglContextRestored() {
this._program = null;
}
destroy() {
if (this._program) {
this._program.destroy();
}
this._program = null;
}
}
export {LinesInstancingSilhouetteRenderer};
|
$(document).ready(function() {
let id = $("#report-subscriber-history-table").attr('data-id');
$('#report-subscriber-history-table').DataTable( {
"bProcessing": true,
"sAjaxSource": '/report_subscriber/responseHistory/'+id,
"columnDefs": [
{
"targets": [ 2 ],
"visible": false,
"searchable": false
}
],
"orderable": false,
"aoColumns": [
{ mData : "id" },
{ mData : "subscriber" },
{ mData : "package" },
{ mData : "price" },
{ mData : "started" },
{ mData : "due_date" },
{ mData : "payment_status" },
{ mData : "status" }
],
"drawCallback": function ( settings ) {
var api = this.api();
var rows = api.rows( {page:'current'} ).nodes();
var last=null;
api.column(2, {page:'current'} ).data().each( function ( group, i ) {
if ( last !== group ) {
$(rows).eq( i ).before(
'<tr class="group" style="background:#506EFA;color:white"><td colspan="8">Package : '+group+'</td></tr>'
);
last = group;
}
} );
},
"order": [[4, 'desc']]
});
$('#report-subscriber-history-table').dataTable().api().on('order.dt search.dt', function (){
$('#report-subscriber-history-table').dataTable().api().column(0, {search: 'applied', order: 'applied'}).nodes().each(function (cell, i) {
cell.innerHTML = i + 1;
});
});
$("#frm-customer-retail").on('submit', function (e) {
e.preventDefault();
var df, dt;
df = $("#from_date").val();
dt = $("#to_date").val();
var url = '/report_subscriber/responseSearchHistory?' + 'df=' + df + '&dt=' + dt + '&id=' + id;
$.getJSON(url, null, function (json)
{
oSettings = $('#report-subscriber-history-table').dataTable().fnSettings();
$('#report-subscriber-history-table').dataTable().fnClearTable(this);
for (var i = 0; i < json.data.length; i++)
{
$('#report-subscriber-history-table').dataTable().oApi._fnAddData(oSettings, json.data[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
$('#report-subscriber-history-table').dataTable().fnDraw();
});
});
});
|
var fs = require('fs'),
path = require('path'),
uaparser = require('ua-parser'),
async = require('async'),
http = require('http'),
url = require('url'),
_ = require('underscore'),
abind = require('dandy/errors').abind,
ibind = require('dandy/errors').ibind,
transformjs = require('transformjs');
var browserscopeURL =
"http://www.browserscope.org/user/tests/table/agt1YS1wcm9maWxlcnINCxIEVGVzdBiG3-0GDA?v=3&o=json";
var featureCache;
var testsCache;
function FeatureDB() {}
FeatureDB.prototype = {
refresh: function(featureTests, cb) {
var db = this.db = {};
exports.readFeatures(abind(function(err, hasData) {
for (var browserId in hasData.results) {
var lastSpace = browserId.lastIndexOf(' ');
var name = browserId.substr(0, lastSpace);
var version = browserId.substr(lastSpace+1);
var v = version.split('.');
// XXXjoe Rather than just taking the first major/minor version
// we find, we should pick the lowest number we can find because
// it has the greatest chance of being true for all versions after it.
var majorVersion = name + ' ' + v[0] + '.0';
var minorVersion = name + ' ' + v[0] + '.' + (v[1] || 0);
var majorTests;
if (!(minorVersion in db)) {
majorTests = db[minorVersion] = {};
if (!(majorVersion in db)) {
db[majorVersion] = majorTests;
}
}
var allTests = hasData.results[browserId].results;
var minimumTests = db[browserId] = {};
if (featureTests && featureTests.length) {
for (var i = 0; i < featureTests.length; ++i) {
var feature = featureTests[i];
if (feature in allTests) {
storeFeature(feature, allTests[feature].result);
}
}
} else {
for (var feature in allTests) {
storeFeature(feature, allTests[feature].result);
}
}
function storeFeature(feature, pass) {
var has = pass == '1' ? true : false;
minimumTests[feature] = has;
if (majorTests) {
majorTests[feature] = has;
}
}
}
// console.log(require('util').inspect(db, null, 200));
cb(0, this);
}, cb, this))
},
/**
* Gets the features that the given user agent has.
*
* Uses the results of has.js tests posted to Browserscope.
*/
getFeatureMap: function(userAgent, backwardsCompatible) {
var parsed = uaparser.parse(userAgent);
var ua = parsed.toString();
if (ua in this.db) {
return this.db[ua];
} else {
var major = parseInt(parsed.major);
var minor = parseInt(parsed.minor) || 0;
while (major >= 0 && minor >= 0) {
var minorVersion = parsed.family + ' ' + major + '.' + minor;
if (minorVersion in this.db) {
return this.db[minorVersion];
}
if (!backwardsCompatible) {
break;
} else if (--minor < 0) {
minor = 0;
--major;
}
}
return null;
}
}
};
exports.readFeatures = function(cb) {
if (featureCache) {
return cb(0, featureCache);
}
var hasJsonPath = path.resolve(path.join(__dirname, '..', 'has.json'));
fs.readFile(hasJsonPath, abind(function(err, data) {
featureCache = JSON.parse(data);
cb(0, featureCache);
}));
}
/**
* Loads a feature database for the given set of feature tests.
*/
exports.getFeatureDB = function(featureTests, cb) {
if (typeof(featureTests) == 'function') { cb = featureTests; featureTests = null; }
var featureDB = new FeatureDB();
featureDB.refresh(featureTests, abind(function(err) {
cb(0, featureDB);
}, cb, this))
}
/**
* Gets a list of feature tests found in the source.
*
* Returns map of found features with the value true if they are required features.
*/
exports.findFeatureTests = function(source) {
var features = {};
transformjs.transform(source, [
function(node, next) {
if (node.TYPE == 'SimpleStatement') {
var feature = findSimpleFunctionCall(node.body, 'has');
if (feature) {
// true means that the feature is required, indicated when it is inside a statement
features[feature] = true;
}
} else {
var feature = findSimpleFunctionCall(node, 'has');
if (feature && !(feature in features)) {
// true means that the feature is not required
features[feature] = false;
}
}
return next();
}
]);
return features;
}
function findSimpleFunctionCall(node, callName) {
if (node.TYPE == 'Call') {
if (node.expression.TYPE == 'SymbolRef' && node.expression.name == callName) {
var args = node.args;
if (args.length >= 1) {
var arg1 = args[0];
if (arg1.TYPE == 'String') {
return arg1.value;
}
}
}
}
}
/**
* Builds has.js with only the specified tests.
*/
exports.buildHasWithTests = function(features, minify, cb) {
if (typeof(minify) == 'function') { cb = minify; minify = false; }
if (testsCache) {
return cb(0, testsCache);
}
var hasDirPath = path.resolve(path.join(__dirname, '..', 'external', 'has.js'));
var detectPath = path.join(hasDirPath, 'detect');
fs.readdir(detectPath, abind(function(err, fileNames) {
async.map(fileNames,
ibind(function(fileName, cb2) {
var filePath = path.join(detectPath, fileName);
fs.readFile(filePath, abind(function(err, source) {
source = scanHasScript(source+'', features);
cb2(0, source);
}, cb, this))
}, cb, this),
abind(function(err, detects) {
var hasjsPath = path.join(hasDirPath, 'has.js');
fs.readFile(hasjsPath, abind(function(err, source) {
testsCache = source + detects.join('');
if (minify) {
var ast = transformjs.transform(testsCache);
testsCache = transformjs.generate(ast, true);
}
cb(0, testsCache);
}, cb, this))
}, cb, this)
);
}, cb, this))
}
function scanHasScript(source, features) {
var testCount = 0;
var ast = transformjs.transform(source, [
function(node, next) {
// Look for statements containing addtest("feature")
if (node.TYPE == "SimpleStatement" && node.body.TYPE == "Call") {
var feature = findSimpleFunctionCall(node.body, 'addtest');
if (feature) {
// Check and see if we used the test anywhere
if (features.indexOf(feature) != -1) {
++testCount;
} else {
// Removes the test because it's not used
return next(transformjs.EmptyStatement());
}
}
}
return next();
}
]);
if (!testCount) {
// No tests were used, so we'll omit the entire module
return '';
} else {
// Return beautified version of transformed script (you can minify later if you'd like)
return transformjs.generate(ast, false, true);
}
}
/**
* Strips out all has('feature') tests that fail for the given features.
*/
exports.eliminateFeatureTests = function(source, featureMap, minify, beautify) {
var filters = featureMap ? [exports.getHasFilter(featureMap)] : [];
var ast = transformjs.transform(source, filters);
return transformjs.generate(ast, minify, beautify);
}
/**
* Filter you can use to insert has.js removals from your own transformjs pipeline.
*/
exports.getHasFilter = function(featureMap) {
return transformjs.branchRemover(function(node, next) {
if (node.TYPE == 'Call') {
var feature = findSimpleFunctionCall(node, 'has');
if (feature) {
return featureMap && featureMap[feature] ? 'pass' : 'fail';
}
}
});
};
exports.downloadTests = function(cb) {
var newBrowsers = [];
var URL = url.parse(browserscopeURL);
var options = {host: URL.host, port: URL.port, path: URL.pathname+URL.search};
http.get(options, function(res) {
var data = [];
res.on('data', function(chunk) {
data.push(chunk);
});
res.on('end', function() {
var output = data.join('');
var hasJsonPath = path.resolve(path.join(__dirname, '..', 'has.json'));
var previousData;
fs.readFile(hasJsonPath, function(err, data) {
previousData = data ? JSON.parse(data) : null;
if (previousData) {
var newData = JSON.parse(output);
for (var browserId in newData.results) {
if (!(browserId in previousData.results)) {
newBrowsers.push(browserId);
}
}
}
fs.writeFile(hasJsonPath, output, function(err) {
if (err) {
cb(err);
} else {
cb(0, newBrowsers);
}
});
});
});
}).on('error', function(err) {
console.error(err);
});
}
|
import { get, post } from './http'
let apiList = {
// 登录
apiLogin: p => post('index.php?c=Bizkey|BizkeyApi&m=login', p)
}
export default apiList
|
import queryString from "query-string";
export const CORE_STATIC_CONTENT = "/exports/core-static-content";
// Network URL's
export const MINE = "/mines";
export const MINE_LIST = "/mines";
export const SUBSCRIPTION = (mineGuid) => `/mines/${mineGuid}/subscribe`;
export const MINE_SUBSCRIPTION = "/mines/subscribe";
export const MINE_LIST_QUERY = (params) => `/mines${params}`;
export const PARTIES_LIST_QUERY = (params = {}) => `/parties?${queryString.stringify(params)}`;
export const MINE_MAP_LIST = "/mines/map-list";
export const MINE_BASIC_INFO_LIST = `/mines/basicinfo`;
export const PARTY = "/parties";
export const MANAGER = "/parties/managers";
export const PARTY_RELATIONSHIP = "/parties/mines";
export const PARTY_ORGBOOK_ENTITY = (partyGuid) => `/parties/${partyGuid}/orgbook-entity`;
export const MERGE_PARTIES = () => `/parties/merge`;
export const PERMITTEE = "/permits/permittees";
export const MINE_NAME_LIST = (params = {}) => `/mines/search?${queryString.stringify(params)}`;
export const MINE_STATUS = "/mines/status";
export const MINE_REGION = "/mines/region";
export const MINE_COMPLIANCE_SUMMARY = (mine_guid) => `/mines/${mine_guid}/compliance/summary`;
export const MINE_TSFS = (mine_guid) => `/mines/${mine_guid}/tailings`;
export const MINE_TSF = (mine_guid, mine_tailings_storage_facility_guid) =>
`/mines/${mine_guid}/tailings/${mine_tailings_storage_facility_guid}`;
export const DISTURBANCE_CODES = "/mines/disturbance-codes";
export const COMMODITY_CODES = "/mines/commodity-codes";
export const EDIT_TSF_REPORT = "";
export const MINE_DOCUMENTS = (mine_guid) => `/mines/${mine_guid}/documents`;
export const MINE_TSF_REQUIRED_DOCUMENTS = "/required-documents?category=TSF";
export const MINE_TENURE_TYPES = "/mines/mine-tenure-type-codes";
export const MINE_TYPES = (mineGuid) => `/mines/${mineGuid}/mine-types`;
export const MINE_TYPES_DETAILS = "/mines/mine-types/details";
export const DOCUMENT_MANAGER_FILE_GET_URL = (token = {}) =>
`/documents?${queryString.stringify(token)}`;
export const DOCUMENT_MANAGER_TOKEN_GET_URL = (documentManagerGuid) =>
`/download-token/${documentManagerGuid}`;
export const DOCUMENT_MANAGER_DOCUMENT = (documentManagerGuid) =>
`/documents/${documentManagerGuid}`;
export const MINESPACE_USER = "/users/minespace";
export const PROVINCE_CODES = "/parties/sub-division-codes";
// EMLI contacts
export const EMLI_CONTACTS = "/EMLI-contacts";
export const EMLI_CONTACTS_BY_REGION = (region, isMajorMine) =>
`/EMLI-contacts/${region}/contacts?is_major_mine=${isMajorMine}`;
export const EMLI_CONTACT = (guid) => `/EMLI-contacts/${guid}`;
export const MINE_VERIFIED_STATUSES = (params = {}) =>
`/mines/verified-status?${queryString.stringify(params)}`;
export const MINE_VERIFIED_STATUS = (mine_guid) => `/mines/${mine_guid}/verified-status`;
// Permits
export const PERMIT_STATUS_CODES = () => `/mines/permits/status-codes`;
export const PERMITS = (mineGuid) => `/mines/${mineGuid}/permits`;
export const PERMIT_AMENDMENTS = (mineGuid, permitGuid) =>
`/mines/${mineGuid}/permits/${permitGuid}/amendments`;
export const PERMIT_AMENDMENT = (mineGuid, permitGuid, permitAmendmentGuid) =>
`/mines/${mineGuid}/permits/${permitGuid}/amendments/${permitAmendmentGuid}`;
export const PERMIT_AMENDMENT_VC = (mineGuid, permitGuid, permitAmendmentGuid) =>
`/mines/${mineGuid}/permits/${permitGuid}/amendments/${permitAmendmentGuid}/verifiable-credential`;
export const PERMIT_AMENDMENT_DOCUMENT = (
mineGuid,
permitGuid,
permitAmendmentGuid,
documentGuid
) =>
`/mines/${mineGuid}/permits/${permitGuid}/amendments/${permitAmendmentGuid}/documents/${documentGuid}`;
export const PERMIT_DELETE = (mineGuid, permitGuid) => `/mines/${mineGuid}/permits/${permitGuid}`;
export const DRAFT_PERMITS = (mineGuid, nowApplicationGuid) =>
`/mines/${mineGuid}/permits?now_application_guid=${nowApplicationGuid}`;
export const PERMIT_CONDITIONS = (mineGuid, permitGuid, permitAmendmentGuid) =>
`/mines/${mineGuid}/permits/${permitGuid}/amendments/${permitAmendmentGuid}/conditions`;
export const PERMIT_CONDITION = (mineGuid, permitGuid, permitAmendmentGuid, permitConditionGuid) =>
`/mines/${mineGuid}/permits/${permitGuid}/amendments/${permitAmendmentGuid}/conditions/${permitConditionGuid}`;
export const STANDARD_PERMIT_CONDITIONS = (noticeOfWorkType) =>
`/mines/permits/standard-conditions/${noticeOfWorkType}`;
export const STANDARD_PERMIT_CONDITION = (permitConditionGuid) =>
`/mines/permits/standard-conditions/${permitConditionGuid}`;
// Explosive Storage & Use Permits
export const EXPLOSIVES_PERMITS = (mineGuid) => `/mines/${mineGuid}/explosives-permits`;
export const EXPLOSIVES_PERMIT = (mineGuid, explosivesPermitGuid) =>
`/mines/${mineGuid}/explosives-permits/${explosivesPermitGuid}`;
export const EXPLOSIVES_PERMIT_DOCUMENTS = (mineGuid, guid) =>
`/mines/${mineGuid}/explosives-permits/${guid}/documents`;
export const EXPLOSIVES_PERMIT_DOCUMENT_TYPE_OPTIONS = "/mines/explosives-permit-document-types";
// EPIC Mine Information
export const EPIC_INFO = (mineGuid) => `/mines/${mineGuid}/epic`;
// Search
export const SEARCH = (params) => (params ? `/search?${queryString.stringify(params)}` : "/search");
export const SEARCH_OPTIONS = "/search/options";
export const SIMPLE_SEARCH = "/search/simple";
// Reporting
export const DASHBOARD = (dashboardId) => `/reporting/dashboard/${dashboardId}`;
// Variances
export const COMPLIANCE_CODES = "/compliance/codes";
export const MINE_VARIANCES = (mineGuid) => `/mines/${mineGuid}/variances`;
export const VARIANCES = (params = {}) => `/variances?${queryString.stringify(params)}`;
export const VARIANCE = (mineGuid, varianceGuid) => `/mines/${mineGuid}/variances/${varianceGuid}`;
export const VARIANCE_DOCUMENTS = (mineGuid, varianceGuid) =>
`/mines/${mineGuid}/variances/${varianceGuid}/documents`;
export const VARIANCE_DOCUMENT = (mineGuid, varianceGuid, documentManagerGuid) =>
`/mines/${mineGuid}/variances/${varianceGuid}/documents/${documentManagerGuid}`;
export const VARIANCE_STATUS_CODES = "/variances/status-codes";
export const VARIANCE_DOCUMENT_CATEGORY_OPTIONS = "/variances/document-categories";
// Project Summaries
export const MINE_PROJECT_SUMMARIES = (mineGuid) => `/mines/${mineGuid}/project-summaries`;
export const PROJECT_SUMMARIES = () => "/project-summaries";
export const PROJECT_SUMMARY = (mineGuid, projectSummaryGuid) =>
`/mines/${mineGuid}/project-summaries/${projectSummaryGuid}`;
export const PROJECT_SUMMARY_DOCUMENTS = (mineGuid, projectSummaryGuid) =>
`/mines/${mineGuid}/project-summaries/${projectSummaryGuid}/documents`;
export const PROJECT_SUMMARY_DOCUMENT = (mineGuid, projectSummaryGuid, documentManagerGuid) =>
`/mines/${mineGuid}/project-summaries/${projectSummaryGuid}/documents/${documentManagerGuid}`;
// Users
export const CORE_USER = "/users/core";
// Incidents
export const MINE_INCIDENTS = (mine_guid) => `/mines/${mine_guid}/incidents`;
export const MINE_INCIDENT = (mineGuid, mine_incident_guid) =>
`/mines/${mineGuid}/incidents/${mine_incident_guid}`;
export const MINE_INCIDENT_DOCUMENT = (mineGuid) => `/mines/${mineGuid}/incidents/documents`;
export const INCIDENTS = (params = {}) => `/incidents?${queryString.stringify(params)}`;
export const INCIDENT_FOLLOWUP_ACTIONS = `/incidents/followup-types`;
export const INCIDENT_DETERMINATION_TYPES = `/incidents/determination-types`;
export const INCIDENT_STATUS_CODES = `/incidents/status-codes`;
export const INCIDENT_DOCUMENT_TYPE = `/incidents/document-types`;
export const INCIDENT_CATEGORY_CODES = `/incidents/category-codes`;
// Work Information
export const MINE_WORK_INFORMATIONS = (mineGuid) => `/mines/${mineGuid}/work-information`;
export const MINE_WORK_INFORMATION = (mineGuid, mineWorkInformationGuid) =>
`/mines/${mineGuid}/work-information/${mineWorkInformationGuid}`;
// Reports
export const REPORTS = (params = {}) => `/mines/reports?${queryString.stringify(params)}`;
export const MINE_REPORT_DEFINITIONS = () => `/mines/reports/definitions`;
export const MINE_REPORTS = (mineGuid, reportsType) =>
`/mines/${mineGuid}/reports?${queryString.stringify({
mine_reports_type: reportsType,
})}`;
export const MINE_REPORT = (mineGuid, mineReportGuid) =>
`/mines/${mineGuid}/reports/${mineReportGuid}`;
export const MINE_REPORT_DOCUMENT = (mineGuid) => `/mines/${mineGuid}/reports/documents`;
export const MINE_REPORT_COMMENTS = (mineGuid, reportGuid) =>
`/mines/${mineGuid}/reports/${reportGuid}/comments`;
export const MINE_REPORT_COMMENT = (mineGuid, reportGuid, commentGuid) =>
`/mines/${mineGuid}/reports/${reportGuid}/comments/${commentGuid}`;
export const MINE_REPORT_STATUS = "/mines/reports/status-codes";
export const MINE_REPORT_CATEGORY = "/mines/reports/category-codes";
// Notice Of Work
export const NOTICE_OF_WORK_APPLICATION_LIST = (params = {}) =>
`/now-applications?${queryString.stringify(params)}`;
export const ADMINISTRATIVE_AMENDMENT_APPLICATION = `/now-applications/administrative-amendments`;
export const NOTICE_OF_WORK_APPLICATION = (applicationGuid) =>
`/now-applications/${applicationGuid}`;
export const NOTICE_OF_WORK_APPLICATION_STATUS = (applicationGuid) =>
`${NOTICE_OF_WORK_APPLICATION(applicationGuid)}/status`;
export const NOTICE_OF_WORK_DOCUMENT_FILE_GET_URL = (id, applicationGuid, token = {}) =>
`/now-submissions/applications/${applicationGuid}/document/${id}?${queryString.stringify(token)}`;
export const NOTICE_OF_WORK_DOCUMENT_TOKEN_GET_URL = (id, applicationGuid) =>
`/now-submissions/applications/${applicationGuid}/document/${id}/token`;
export const NOTICE_OF_WORK_APPLICATION_IMPORT = (applicationGuid) =>
`/now-applications/${applicationGuid}/import`;
export const NOTICE_OF_WORK_IMPORT_SUBMISSION_DOCUMENTS_JOB = (applicationGuid) =>
`${NOTICE_OF_WORK_APPLICATION(applicationGuid)}/import-submission-documents-job`;
export const NOTICE_OF_WORK_ACTIVITY_TYPE_OPTIONS = "/now-applications/activity-types";
export const NOTICE_OF_WORK_UNIT_TYPE_OPTIONS = "/now-applications/unit-types";
export const NOTICE_OF_WORK_APPLICATION_TYPE_OPTIONS = "/now-applications/application-types";
export const NOTICE_OF_WORK_APPLICATION_STATUS_OPTIONS =
"/now-applications/application-status-codes";
export const NOW_APPLICATION_DOCUMENT_TYPE_OPTIONS = "/now-applications/application-document-types";
export const NOW_APPLICATION_EXPORT_DOCUMENT_TYPE_OPTIONS = "/now-applications/application-export";
export const NOW_UNDERGROUND_EXPLORATION_TYPE_OPTIONS =
"/now-applications/underground-exploration-types";
export const NOTICE_OF_WORK_APPLICATION_PROGRESS = (applicationGuid, progressCode) =>
`/now-applications/${applicationGuid}/progress/${progressCode}`;
export const NOTICE_OF_WORK_APPLICATION_REVIEW = (applicationGuid) =>
`/now-applications/${applicationGuid}/reviews`;
export const NOTICE_OF_WORK_APPLICATION_REVIEW_TYPES = `/now-applications/review-types`;
export const NOW_APPLICATION_PROGRESS_STATUS_CODES =
"/now-applications/application-progress-status-codes";
export const NOTICE_OF_WORK_DOCUMENT = (now_document_guid) =>
`/now-applications/${now_document_guid}/document`;
export const SORT_NOTICE_OF_WORK_DOCUMENTS = (now_document_guid) =>
`/now-applications/${now_document_guid}/sort-documents`;
export const NOW_APPLICATION_PERMIT_TYPES = "/now-applications/application-permit-types";
export const IMPORT_NOTICE_OF_WORK_SUBMISSION_DOCUMENTS_JOB = (applicationGuid) =>
`/import-now-submission-documents?now_application_guid=${applicationGuid}&most_recent_only=true`;
export const NOTICE_OF_WORK_APPLICATION_DELAY = (applicationGuid, delayGuid) =>
delayGuid
? `/now-applications/${applicationGuid}/delays/${delayGuid}`
: `/now-applications/${applicationGuid}/delays`;
// Mine Party Appointments
export const MINE_PARTY_APPOINTMENT_DOCUMENTS = (mineGuid, minePartyAppointmentGuid) =>
`/mines/${mineGuid}/party-appts/${minePartyAppointmentGuid}/documents`;
export const NRIS_DOCUMENT_TOKEN_GET_URL = (externalId, inspectionId, file_name) =>
`/compliance/inspection/${inspectionId}/document/${externalId}/token?${queryString.stringify({
file_name,
})}`;
export const NRIS_DOCUMENT_FILE_GET_URL = (externalId, inspectionId, token) =>
`/compliance/inspection/${inspectionId}/document/${externalId}?${queryString.stringify(token)}`;
export const MINE_BONDS = (mineGuid) => `/securities/bonds?mine_guid=${mineGuid}`;
export const BOND = (bondGuid) =>
bondGuid ? `/securities/bonds/${bondGuid}` : "/securities/bonds";
export const BOND_TRANSFER = (bondGuid) => `/securities/bonds/${bondGuid}/transfer`;
export const BOND_DOCUMENTS = (mineGuid) => `/securities/${mineGuid}/bonds/documents`;
export const MINE_RECLAMATION_INVOICES = (mineGuid) =>
`/securities/reclamation-invoices?mine_guid=${mineGuid}`;
export const RECLAMATION_INVOICE = (invoiceGuid) =>
invoiceGuid
? `/securities/reclamation-invoices/${invoiceGuid}`
: "/securities/reclamation-invoices";
export const RECLAMATION_INVOICE_DOCUMENTS = (mineGuid) =>
`/securities/${mineGuid}/reclamation-invoices/documents`;
export const MINE_COMMENTS = (mineGuid) => `/mines/${mineGuid}/comments`;
export const MINE_COMMENT = (mineGuid, commentGuid) => `/mines/${mineGuid}/comments/${commentGuid}`;
// OrgBook
export const ORGBOOK_SEARCH = (search) => `/orgbook/search?${queryString.stringify({ search })}`;
export const ORGBOOK_CREDENTIAL = (credentialId) => `/orgbook/credential/${credentialId}`;
|
/** @jsx jsx */
import { jsx, Themed } from 'theme-ui';
import { Box, Flex } from '@theme-ui/components';
import kebabCase from 'lodash.kebabcase';
import { Link } from 'gatsby';
import Layout from './layout';
import useMinimalBlogConfig from '../hooks/use-minimal-blog-config';
import SEO from './seo';
import replaceSlashes from '../utils/replaceSlashes';
const Tags = ({ list }) => {
const { tagsPath, basePath } = useMinimalBlogConfig();
return (
<Layout>
<SEO title="Tags" />
<Themed.h2>Tags</Themed.h2>
<Flex
mt={[4, 5]}
sx={{
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'space-evenly',
}}
>
{list.map((listItem) => (
<Flex key={listItem.fieldValue} mb={[1, 1, 2]} sx={{ alignItems: `center` }}>
<Themed.a
as={Link}
sx={{ variant: 'links.tagCloud' }}
to={replaceSlashes(`/${basePath}/${tagsPath}/${kebabCase(listItem.fieldValue)}`)}
>
{listItem.fieldValue} <span sx={{ color: `secondary` }}>({listItem.totalCount})</span>
</Themed.a>
</Flex>
))}
</Flex>
</Layout>
);
};
export default Tags;
|
/* eslint-disable no-use-before-define */
const proto = exports;
const { isObject } = require('../utils/isObject');
const { isArray } = require('../utils/isArray');
proto.getBucketVersions = getBucketVersions;
proto.listObjectVersions = getBucketVersions;
async function getBucketVersions(query = {}, options = {}) {
// prefix, key-marker, max-keys, delimiter, encoding-type, version-id-marker
if (query.versionIdMarker && query.keyMarker === undefined) {
throw new Error('A version-id marker cannot be specified without a key marker');
}
options.subres = Object.assign({ versions: '' }, options.subres);
if (options.versionId) {
options.subres.versionId = options.versionId;
}
const params = this._objectRequestParams('GET', '', options);
params.xmlResponse = true;
params.successStatuses = [200];
params.query = formatQuery(query);
const result = await this.request(params);
let objects = result.data.Version || [];
let deleteMarker = result.data.DeleteMarker || [];
const that = this;
if (objects) {
if (!Array.isArray(objects)) {
objects = [objects];
}
objects = objects.map(obj => ({
name: obj.Key,
url: that._objectUrl(obj.Key),
lastModified: obj.LastModified,
isLatest: obj.IsLatest === 'true',
versionId: obj.VersionId,
etag: obj.ETag,
type: obj.Type,
size: Number(obj.Size),
storageClass: obj.StorageClass,
owner: {
id: obj.Owner.ID,
displayName: obj.Owner.DisplayName
}
}));
}
if (deleteMarker) {
if (!isArray(deleteMarker)) {
deleteMarker = [deleteMarker];
}
deleteMarker = deleteMarker.map(obj => ({
name: obj.Key,
lastModified: obj.LastModified,
versionId: obj.VersionId,
owner: {
id: obj.Owner.ID,
displayName: obj.Owner.DisplayName
}
}));
}
let prefixes = result.data.CommonPrefixes || null;
if (prefixes) {
if (!isArray(prefixes)) {
prefixes = [prefixes];
}
prefixes = prefixes.map(item => item.Prefix);
}
return {
res: result.res,
objects,
deleteMarker,
prefixes,
nextMarker: result.data.NextMarker || null,
NextVersionIdMarker: result.data.NextVersionIdMarker || null,
isTruncated: result.data.IsTruncated === 'true'
};
}
function camel2Line(name) {
return name.replace(/([A-Z])/g, '-$1').toLowerCase();
}
function formatQuery(query = {}) {
const obj = {};
if (isObject(query)) {
Object.keys(query).forEach((key) => {
obj[camel2Line(key)] = query[key];
});
}
return obj;
}
|
croc.Class.define('test.cmp.Test2', {
extend: croc.cmp.Widget,
members: {
click: function() {
console.log('clicked');
},
/**
* Инициализация модели виджета
* @protected
*/
_initModel: function() {
test.cmp.Test2.superclass._initModel.apply(this, arguments);
this.getParent()._model.set('some', 'ololo');
}
}
});
|
/* globals Stats, dat*/
// import AMI.TrackballControl from 'base/controls/controls.trackball';
// import AMI.StackHelper from 'base/helpers/helpers.stack';
// import AMI.VolumeLoader from 'base/loaders/loaders.volume';
// standard global letiables
let controls;
let renderer;
let stats;
let scene;
let camera;
let stackHelper;
let particleLight;
let line;
let threeD;
/**
* Convert number to hex
*
* @param {Number} c
*
* @return {*}
*/
function componentToHex(c) {
let hex = c.toString(16);
return hex.length === 1 ? '0' + hex : hex;
}
/**
* Convert RGB to HEX
* @param {*} r
* @param {*} g
* @param {*} b
*
* @return {*}
*/
function rgbToHex(r, g, b) {
return '#' + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
/**
* Update geometries
*/
function updateGeometries() {
if (stackHelper) {
// move the "light"
// update light position
let timer = Date.now() * 0.00025;
particleLight.position.x = Math.sin(timer * 7) * 70;
particleLight.position.y = Math.cos(timer * 5) * 80;
particleLight.position.z = Math.cos(timer * 3) * 90;
// re-draw the line
line.geometry.vertices[0] = stackHelper.slice.planePosition;
line.geometry.vertices[1] = particleLight.position;
line.geometry.verticesNeedUpdate = true;
// update plane direction...
let dirLPS = new THREE.Vector3(
particleLight.position.x - stackHelper.slice.planePosition.x,
particleLight.position.y - stackHelper.slice.planePosition.y,
particleLight.position.z - stackHelper.slice.planePosition.z
).normalize();
// update slice and THEN its border
stackHelper.slice.planeDirection = dirLPS;
// update border with new slice
stackHelper.border.helpersSlice = stackHelper.slice;
// update colors based on planeDirection
let color = rgbToHex(
Math.round(Math.abs(255 * dirLPS.x)),
Math.round(Math.abs(255 * dirLPS.y)),
Math.round(Math.abs(255 * dirLPS.z))
);
stackHelper.bbox.color = color;
stackHelper.border.color = color;
particleLight.material.color.set(color);
line.material.color.set(color);
}
}
function render() {
controls.update();
renderer.render(scene, camera);
stats.update();
}
/**
* Initialize the scene
*/
function init() {
/**
* Animation loop
*/
function animate() {
updateGeometries();
render();
// request new frame
requestAnimationFrame(function() {
animate();
});
}
// renderer
threeD = document.getElementById('r3d');
renderer = new THREE.WebGLRenderer({
antialias: true,
});
renderer.setSize(threeD.offsetWidth, threeD.offsetHeight);
renderer.setClearColor(0x353535, 1);
renderer.setPixelRatio(window.devicePixelRatio);
threeD.appendChild(renderer.domElement);
// stats
stats = new Stats();
threeD.appendChild(stats.domElement);
// scene
scene = new THREE.Scene();
// camera
camera = new THREE.PerspectiveCamera(
45,
threeD.offsetWidth / threeD.offsetHeight,
0.01,
10000000
);
camera.position.x = 150;
camera.position.y = 150;
camera.position.z = 100;
// controls
controls = new AMI.TrackballControl(camera, threeD);
controls.rotateSpeed = 1.4;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.dynamicDampingFactor = 0.3;
particleLight = new THREE.Mesh(
new THREE.SphereGeometry(2, 8, 8),
new THREE.MeshBasicMaterial({ color: 0xfff336 })
);
scene.add(particleLight);
animate();
}
window.onload = function() {
// init threeJS...
init();
// instantiate the loader
// it loads and parses the dicom image
let loader = new AMI.VolumeLoader(threeD);
let t2 = [
'36444280',
'36444294',
'36444308',
'36444322',
'36444336',
'36444350',
'36444364',
'36444378',
'36444392',
'36444406',
'36748256',
'36444434',
'36444448',
'36444462',
'36444476',
'36444490',
'36444504',
'36444518',
'36444532',
'36746856',
'36746870',
'36746884',
'36746898',
'36746912',
'36746926',
'36746940',
'36746954',
'36746968',
'36746982',
'36746996',
'36747010',
'36747024',
'36748200',
'36748214',
'36748228',
'36748270',
'36748284',
'36748298',
'36748312',
'36748326',
'36748340',
'36748354',
'36748368',
'36748382',
'36748396',
'36748410',
'36748424',
'36748438',
'36748452',
'36748466',
'36748480',
'36748494',
'36748508',
'36748522',
'36748242',
];
let files = t2.map(function(v) {
return '../data-master/dicom/adi_brain/' + v;
});
loader
.load(files)
.then(function() {
const series = loader.data[0].mergeSeries(loader.data)[0];
const stack = series.stack[0];
stackHelper = new AMI.StackHelper(stack);
const centerLPS = stackHelper.stack.worldCenter();
stackHelper.slice.aabbSpace = 'LPS';
stackHelper.slice.planePosition.x = centerLPS.x;
stackHelper.slice.planePosition.y = centerLPS.y;
stackHelper.slice.planePosition.z = centerLPS.z;
stackHelper.slice.thickness = 0;
stackHelper.slice.spacing = 1;
scene.add(stackHelper);
// LINE STUFF
const materialLine = new THREE.LineBasicMaterial();
const geometryLine = new THREE.Geometry();
stackHelper.slice.updateMatrixWorld();
geometryLine.vertices.push(stackHelper.slice.position);
geometryLine.vertices.push(particleLight.position);
geometryLine.verticesNeedUpdate = true;
line = new THREE.Line(geometryLine, materialLine);
scene.add(line);
// update camrea's and control's target
camera.lookAt(centerLPS.x, centerLPS.y, centerLPS.z);
camera.updateProjectionMatrix();
controls.target.set(centerLPS.x, centerLPS.y, centerLPS.z);
// create GUI
let gui = new dat.GUI({
autoPlace: false,
});
let customContainer = document.getElementById('my-gui-container');
customContainer.appendChild(gui.domElement);
customContainer = null;
let positionFolder = gui.addFolder('Plane position');
let worldBBox = stackHelper.stack.worldBoundingBox();
let frameIndexControllerOriginI = positionFolder
.add(stackHelper.slice.planePosition, 'x', worldBBox[0], worldBBox[1])
.step(0.01)
.listen();
let frameIndexControllerOriginJ = positionFolder
.add(stackHelper.slice.planePosition, 'y', worldBBox[2], worldBBox[3])
.step(0.01)
.listen();
let frameIndexControllerOriginK = positionFolder
.add(stackHelper.slice.planePosition, 'z', worldBBox[4], worldBBox[5])
.step(0.01)
.listen();
positionFolder
.add(stackHelper.slice, 'interpolation', 0, 1)
.step(1)
.listen();
positionFolder
.add(stackHelper.slice, 'thickness', 0, 20)
.step(1)
.listen();
positionFolder
.add(stackHelper.slice, 'spacing', 0, 2)
.step(0.2)
.listen();
positionFolder.open();
frameIndexControllerOriginI.onChange(updateGeometries);
frameIndexControllerOriginJ.onChange(updateGeometries);
frameIndexControllerOriginK.onChange(updateGeometries);
loader.free();
loader = null;
/**
* onWindowResize callback
*/
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener('resize', onWindowResize, false);
// force 1st render
render();
// notify puppeteer to take screenshot
const puppetDiv = document.createElement('div');
puppetDiv.setAttribute('id', 'puppeteer');
document.body.appendChild(puppetDiv);
})
.catch(function(error) {
window.console.log('oops... something went wrong...');
window.console.log(error);
});
};
|
//////////////////////////////////////////////////////////////////////////////////////////
// ___ _ ___ //
// | | \/ | ) | | This software may be modified and distri- //
// O- |- | | - | | |- -O buted under the terms of the MIT license. //
// | |_ | | | |_ See the LICENSE file for details. //
// //
//////////////////////////////////////////////////////////////////////////////////////////
'use strict';
const Gio = imports.gi.Gio;
const _ = imports.gettext.domain('flypie').gettext;
const Me = imports.misc.extensionUtils.getCurrentExtension();
const utils = Me.imports.src.common.utils;
const ItemRegistry = Me.imports.src.common.ItemRegistry;
const ConfigWidgetFactory = Me.imports.src.common.ConfigWidgetFactory.ConfigWidgetFactory;
//////////////////////////////////////////////////////////////////////////////////////////
// The file action is very similar to the Url action, but only works for files. //
// But it's a bit more intuitive as the leading file:// is not required. //
// See common/ItemRegistry.js for a description of the action's format. //
//////////////////////////////////////////////////////////////////////////////////////////
var action = {
// There are two fundamental item types in Fly-Pie: Actions and Menus. Actions have an
// onSelect() method which is called when the user selects the item, Menus can have
// child Actions or Menus.
class: ItemRegistry.ItemClass.ACTION,
// This will be shown in the add-new-item-popover of the settings dialog.
name: _('Open File'),
// This is also used in the add-new-item-popover.
icon: 'flypie-action-file-symbolic-#8a3',
// Translators: Please keep this short.
// This is the (short) description shown in the add-new-item-popover.
subtitle: _('Opens a file with the default application.'),
// This is the (long) description shown when an item of this type is selected.
description: _(
'The <b>Open File</b> action will open the file specified above with your system\'s default application.'),
// Items of this type have an additional text configuration parameter which represents
// the file path to open.
config: {
// This is used as data for newly created items of this type.
defaultData: {file: ''},
// This is called whenever an item of this type is selected in the menu editor. It
// returns a Gtk.Widget which will be shown in the sidebar of the menu editor. The
// currently configured data object will be passed as first parameter and *should* be
// an object containing a single "file" property. To stay backwards compatible with
// Fly-Pie 4, we have to also handle the case where the file is given as a simple
// string value. The second parameter is a callback which is fired whenever the user
// changes something in the widgets.
getWidget(data, updateCallback) {
let file = '';
if (typeof data === 'string') {
file = data;
} else if (data.file != undefined) {
file = data.file;
}
return ConfigWidgetFactory.createFileWidget(
_('File'), _('It will be opened with the default app.'), file,
(file, name, icon) => {
updateCallback({file: file}, name, icon);
});
}
},
// This will be called whenever a menu is opened containing an item of this kind.
// The data parameter *should* be an object containing a single "file" property.
// To stay backwards compatible with Fly-Pie 4, we have to also handle the case
// where the file is given as a simple string value.
createItem: (data) => {
let file = '';
if (typeof data === 'string') {
file = data;
} else if (data.file != undefined) {
file = data.file;
}
// The onSelect() function will be called when the user selects this action.
return {
onSelect: () => {
try {
Gio.AppInfo.launch_default_for_uri('file://' + file, null);
} catch (error) {
utils.debug('Failed to open file: ' + error);
}
}
};
}
};
|
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
//Allow using this built library as an AMD module
//in another project. That other project will only
//see this AMD call, not the internal modules in
//the closure below.
define('escher', factory);
} else {
//Browser globals case. Just assign the
//result to a property on the global.
root.escher = factory();
}
}(this, function () {
//almond, and your modules will be inlined here
/**
* almond 0.2.6 Copyright (c) 2011-2012, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/almond for details
*/
//Going sloppy to avoid 'use strict' string cost, but strict practices should
//be followed.
/*jslint sloppy: true */
/*global setTimeout: false */
var requirejs, require, define;
(function (undef) {
var main, req, makeMap, handlers,
defined = {},
waiting = {},
config = {},
defining = {},
hasOwn = Object.prototype.hasOwnProperty,
aps = [].slice;
function hasProp(obj, prop) {
return hasOwn.call(obj, prop);
}
/**
* Given a relative module name, like ./something, normalize it to
* a real name that can be mapped to a path.
* @param {String} name the relative name
* @param {String} baseName a real name that the name arg is relative
* to.
* @returns {String} normalized name
*/
function normalize(name, baseName) {
var nameParts, nameSegment, mapValue, foundMap,
foundI, foundStarMap, starI, i, j, part,
baseParts = baseName && baseName.split("/"),
map = config.map,
starMap = (map && map['*']) || {};
//Adjust any relative paths.
if (name && name.charAt(0) === ".") {
//If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end.
if (baseName) {
//Convert baseName to array, and lop off the last part,
//so that . matches that "directory" and not name of the baseName's
//module. For instance, baseName of "one/two/three", maps to
//"one/two/three.js", but we want the directory, "one/two" for
//this normalization.
baseParts = baseParts.slice(0, baseParts.length - 1);
name = baseParts.concat(name.split("/"));
//start trimDots
for (i = 0; i < name.length; i += 1) {
part = name[i];
if (part === ".") {
name.splice(i, 1);
i -= 1;
} else if (part === "..") {
if (i === 1 && (name[2] === '..' || name[0] === '..')) {
//End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
break;
} else if (i > 0) {
name.splice(i - 1, 2);
i -= 2;
}
}
}
//end trimDots
name = name.join("/");
} else if (name.indexOf('./') === 0) {
// No baseName, so this is ID is resolved relative
// to baseUrl, pull off the leading dot.
name = name.substring(2);
}
}
//Apply map config if available.
if ((baseParts || starMap) && map) {
nameParts = name.split('/');
for (i = nameParts.length; i > 0; i -= 1) {
nameSegment = nameParts.slice(0, i).join("/");
if (baseParts) {
//Find the longest baseName segment match in the config.
//So, do joins on the biggest to smallest lengths of baseParts.
for (j = baseParts.length; j > 0; j -= 1) {
mapValue = map[baseParts.slice(0, j).join('/')];
//baseName segment has config, find if it has one for
//this name.
if (mapValue) {
mapValue = mapValue[nameSegment];
if (mapValue) {
//Match, update name to the new value.
foundMap = mapValue;
foundI = i;
break;
}
}
}
}
if (foundMap) {
break;
}
//Check for a star map match, but just hold on to it,
//if there is a shorter segment match later in a matching
//config, then favor over this star map.
if (!foundStarMap && starMap && starMap[nameSegment]) {
foundStarMap = starMap[nameSegment];
starI = i;
}
}
if (!foundMap && foundStarMap) {
foundMap = foundStarMap;
foundI = starI;
}
if (foundMap) {
nameParts.splice(0, foundI, foundMap);
name = nameParts.join('/');
}
}
return name;
}
function makeRequire(relName, forceSync) {
return function () {
//A version of a require function that passes a moduleName
//value for items that may need to
//look up paths relative to the moduleName
return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync]));
};
}
function makeNormalize(relName) {
return function (name) {
return normalize(name, relName);
};
}
function makeLoad(depName) {
return function (value) {
defined[depName] = value;
};
}
function callDep(name) {
if (hasProp(waiting, name)) {
var args = waiting[name];
delete waiting[name];
defining[name] = true;
main.apply(undef, args);
}
if (!hasProp(defined, name) && !hasProp(defining, name)) {
throw new Error('No ' + name);
}
return defined[name];
}
//Turns a plugin!resource to [plugin, resource]
//with the plugin being undefined if the name
//did not have a plugin prefix.
function splitPrefix(name) {
var prefix,
index = name ? name.indexOf('!') : -1;
if (index > -1) {
prefix = name.substring(0, index);
name = name.substring(index + 1, name.length);
}
return [prefix, name];
}
/**
* Makes a name map, normalizing the name, and using a plugin
* for normalization if necessary. Grabs a ref to plugin
* too, as an optimization.
*/
makeMap = function (name, relName) {
var plugin,
parts = splitPrefix(name),
prefix = parts[0];
name = parts[1];
if (prefix) {
prefix = normalize(prefix, relName);
plugin = callDep(prefix);
}
//Normalize according
if (prefix) {
if (plugin && plugin.normalize) {
name = plugin.normalize(name, makeNormalize(relName));
} else {
name = normalize(name, relName);
}
} else {
name = normalize(name, relName);
parts = splitPrefix(name);
prefix = parts[0];
name = parts[1];
if (prefix) {
plugin = callDep(prefix);
}
}
//Using ridiculous property names for space reasons
return {
f: prefix ? prefix + '!' + name : name, //fullName
n: name,
pr: prefix,
p: plugin
};
};
function makeConfig(name) {
return function () {
return (config && config.config && config.config[name]) || {};
};
}
handlers = {
require: function (name) {
return makeRequire(name);
},
exports: function (name) {
var e = defined[name];
if (typeof e !== 'undefined') {
return e;
} else {
return (defined[name] = {});
}
},
module: function (name) {
return {
id: name,
uri: '',
exports: defined[name],
config: makeConfig(name)
};
}
};
main = function (name, deps, callback, relName) {
var cjsModule, depName, ret, map, i,
args = [],
usingExports;
//Use name if no relName
relName = relName || name;
//Call the callback to define the module, if necessary.
if (typeof callback === 'function') {
//Pull out the defined dependencies and pass the ordered
//values to the callback.
//Default to [require, exports, module] if no deps
deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps;
for (i = 0; i < deps.length; i += 1) {
map = makeMap(deps[i], relName);
depName = map.f;
//Fast path CommonJS standard dependencies.
if (depName === "require") {
args[i] = handlers.require(name);
} else if (depName === "exports") {
//CommonJS module spec 1.1
args[i] = handlers.exports(name);
usingExports = true;
} else if (depName === "module") {
//CommonJS module spec 1.1
cjsModule = args[i] = handlers.module(name);
} else if (hasProp(defined, depName) ||
hasProp(waiting, depName) ||
hasProp(defining, depName)) {
args[i] = callDep(depName);
} else if (map.p) {
map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
args[i] = defined[depName];
} else {
throw new Error(name + ' missing ' + depName);
}
}
ret = callback.apply(defined[name], args);
if (name) {
//If setting exports via "module" is in play,
//favor that over return value and exports. After that,
//favor a non-undefined return value over exports use.
if (cjsModule && cjsModule.exports !== undef &&
cjsModule.exports !== defined[name]) {
defined[name] = cjsModule.exports;
} else if (ret !== undef || !usingExports) {
//Use the return value from the function.
defined[name] = ret;
}
}
} else if (name) {
//May just be an object definition for the module. Only
//worry about defining if have a module name.
defined[name] = callback;
}
};
requirejs = require = req = function (deps, callback, relName, forceSync, alt) {
if (typeof deps === "string") {
if (handlers[deps]) {
//callback in this case is really relName
return handlers[deps](callback);
}
//Just return the module wanted. In this scenario, the
//deps arg is the module name, and second arg (if passed)
//is just the relName.
//Normalize module name, if it contains . or ..
return callDep(makeMap(deps, callback).f);
} else if (!deps.splice) {
//deps is a config object, not an array.
config = deps;
if (callback.splice) {
//callback is an array, which means it is a dependency list.
//Adjust args if there are dependencies
deps = callback;
callback = relName;
relName = null;
} else {
deps = undef;
}
}
//Support require(['a'])
callback = callback || function () {};
//If relName is a function, it is an errback handler,
//so remove it.
if (typeof relName === 'function') {
relName = forceSync;
forceSync = alt;
}
//Simulate async callback;
if (forceSync) {
main(undef, deps, callback, relName);
} else {
//Using a non-zero value because of concern for what old browsers
//do, and latest browsers "upgrade" to 4 if lower value is used:
//http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout:
//If want a value immediately, use require('id') instead -- something
//that works in almond on the global level, but not guaranteed and
//unlikely to work in other AMD implementations.
setTimeout(function () {
main(undef, deps, callback, relName);
}, 4);
}
return req;
};
/**
* Just drops the config on the floor, but returns req in case
* the config return value is used.
*/
req.config = function (cfg) {
config = cfg;
if (config.deps) {
req(config.deps, config.callback);
}
return req;
};
/**
* Expose module registry for debugging and tooling
*/
requirejs._defined = defined;
define = function (name, deps, callback) {
//This module may not have dependencies
if (!deps.splice) {
//deps is not an array, so probably means
//an object literal or factory function for
//the value. Adjust args.
callback = deps;
deps = [];
}
if (!hasProp(defined, name) && !hasProp(waiting, name)) {
waiting[name] = [name, deps, callback];
}
};
define.amd = {
jQuery: true
};
}());
define("../build/almond", function(){});
/**
* vkBeautify - javascript plugin to pretty-print or minify text in XML, JSON, CSS and SQL formats.
*
* Version - 0.99.00.beta
* Copyright (c) 2012 Vadim Kiryukhin
* vkiryukhin @ gmail.com
* http://www.eslinstructor.net/vkbeautify/
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Pretty print
*
* vkbeautify.xml(text [,indent_pattern]);
* vkbeautify.json(text [,indent_pattern]);
* vkbeautify.css(text [,indent_pattern]);
* vkbeautify.sql(text [,indent_pattern]);
*
* @text - String; text to beatufy;
* @indent_pattern - Integer | String;
* Integer: number of white spaces;
* String: character string to visualize indentation ( can also be a set of white spaces )
* Minify
*
* vkbeautify.xmlmin(text [,preserve_comments]);
* vkbeautify.jsonmin(text);
* vkbeautify.cssmin(text [,preserve_comments]);
* vkbeautify.sqlmin(text);
*
* @text - String; text to minify;
* @preserve_comments - Bool; [optional];
* Set this flag to true to prevent removing comments from @text ( minxml and mincss functions only. )
*
* Examples:
* vkbeautify.xml(text); // pretty print XML
* vkbeautify.json(text, 4 ); // pretty print JSON
* vkbeautify.css(text, '. . . .'); // pretty print CSS
* vkbeautify.sql(text, '----'); // pretty print SQL
*
* vkbeautify.xmlmin(text, true);// minify XML, preserve comments
* vkbeautify.jsonmin(text);// minify JSON
* vkbeautify.cssmin(text);// minify CSS, remove comments ( default )
* vkbeautify.sqlmin(text);// minify SQL
*
*/
define('lib/vkbeautify',[],function() {
function createShiftArr(step) {
var space = ' ';
if ( isNaN(parseInt(step)) ) { // argument is string
space = step;
} else { // argument is integer
switch(step) {
case 1: space = ' '; break;
case 2: space = ' '; break;
case 3: space = ' '; break;
case 4: space = ' '; break;
case 5: space = ' '; break;
case 6: space = ' '; break;
case 7: space = ' '; break;
case 8: space = ' '; break;
case 9: space = ' '; break;
case 10: space = ' '; break;
case 11: space = ' '; break;
case 12: space = ' '; break;
}
}
var shift = ['\n']; // array of shifts
for(ix=0;ix<100;ix++){
shift.push(shift[ix]+space);
}
return shift;
}
function vkbeautify(){
this.step = ' '; // 4 spaces
this.shift = createShiftArr(this.step);
};
vkbeautify.prototype.xml = function(text,step) {
var ar = text.replace(/>\s{0,}</g,"><")
.replace(/</g,"~::~<")
.replace(/\s*xmlns\:/g,"~::~xmlns:")
.replace(/\s*xmlns\=/g,"~::~xmlns=")
.split('~::~'),
len = ar.length,
inComment = false,
deep = 0,
str = '',
ix = 0,
shift = step ? createShiftArr(step) : this.shift;
for(ix=0;ix<len;ix++) {
// start comment or <![CDATA[...]]> or <!DOCTYPE //
if(ar[ix].search(/<!/) > -1) {
str += shift[deep]+ar[ix];
inComment = true;
// end comment or <![CDATA[...]]> //
if(ar[ix].search(/-->/) > -1 || ar[ix].search(/\]>/) > -1 || ar[ix].search(/!DOCTYPE/) > -1 ) {
inComment = false;
}
} else
// end comment or <![CDATA[...]]> //
if(ar[ix].search(/-->/) > -1 || ar[ix].search(/\]>/) > -1) {
str += ar[ix];
inComment = false;
} else
// <elm></elm> //
if( /^<\w/.exec(ar[ix-1]) && /^<\/\w/.exec(ar[ix]) &&
/^<[\w:\-\.\,]+/.exec(ar[ix-1]) == /^<\/[\w:\-\.\,]+/.exec(ar[ix])[0].replace('/','')) {
str += ar[ix];
if(!inComment) deep--;
} else
// <elm> //
if(ar[ix].search(/<\w/) > -1 && ar[ix].search(/<\//) == -1 && ar[ix].search(/\/>/) == -1 ) {
str = !inComment ? str += shift[deep++]+ar[ix] : str += ar[ix];
} else
// <elm>...</elm> //
if(ar[ix].search(/<\w/) > -1 && ar[ix].search(/<\//) > -1) {
str = !inComment ? str += shift[deep]+ar[ix] : str += ar[ix];
} else
// </elm> //
if(ar[ix].search(/<\//) > -1) {
str = !inComment ? str += shift[--deep]+ar[ix] : str += ar[ix];
} else
// <elm/> //
if(ar[ix].search(/\/>/) > -1 ) {
str = !inComment ? str += shift[deep]+ar[ix] : str += ar[ix];
} else
// <? xml ... ?> //
if(ar[ix].search(/<\?/) > -1) {
str += shift[deep]+ar[ix];
} else
// xmlns //
if( ar[ix].search(/xmlns\:/) > -1 || ar[ix].search(/xmlns\=/) > -1) {
str += shift[deep]+ar[ix];
}
else {
str += ar[ix];
}
}
return (str[0] == '\n') ? str.slice(1) : str;
}
vkbeautify.prototype.json = function(text,step) {
var step = step ? step : this.step;
if (typeof JSON === 'undefined' ) return text;
if ( typeof text === "string" ) return JSON.stringify(JSON.parse(text), null, step);
if ( typeof text === "object" ) return JSON.stringify(text, null, step);
return text; // text is not string nor object
}
vkbeautify.prototype.css = function(text, step) {
var ar = text.replace(/\s{1,}/g,' ')
.replace(/\{/g,"{~::~")
.replace(/\}/g,"~::~}~::~")
.replace(/\;/g,";~::~")
.replace(/\/\*/g,"~::~/*")
.replace(/\*\//g,"*/~::~")
.replace(/~::~\s{0,}~::~/g,"~::~")
.split('~::~'),
len = ar.length,
deep = 0,
str = '',
ix = 0,
shift = step ? createShiftArr(step) : this.shift;
for(ix=0;ix<len;ix++) {
if( /\{/.exec(ar[ix])) {
str += shift[deep++]+ar[ix];
} else
if( /\}/.exec(ar[ix])) {
str += shift[--deep]+ar[ix];
} else
if( /\*\\/.exec(ar[ix])) {
str += shift[deep]+ar[ix];
}
else {
str += shift[deep]+ar[ix];
}
}
return str.replace(/^\n{1,}/,'');
}
//----------------------------------------------------------------------------
function isSubquery(str, parenthesisLevel) {
return parenthesisLevel - (str.replace(/\(/g,'').length - str.replace(/\)/g,'').length )
}
function split_sql(str, tab) {
return str.replace(/\s{1,}/g," ")
.replace(/ AND /ig,"~::~"+tab+tab+"AND ")
.replace(/ BETWEEN /ig,"~::~"+tab+"BETWEEN ")
.replace(/ CASE /ig,"~::~"+tab+"CASE ")
.replace(/ ELSE /ig,"~::~"+tab+"ELSE ")
.replace(/ END /ig,"~::~"+tab+"END ")
.replace(/ FROM /ig,"~::~FROM ")
.replace(/ GROUP\s{1,}BY/ig,"~::~GROUP BY ")
.replace(/ HAVING /ig,"~::~HAVING ")
//.replace(/ SET /ig," SET~::~")
.replace(/ IN /ig," IN ")
.replace(/ JOIN /ig,"~::~JOIN ")
.replace(/ CROSS~::~{1,}JOIN /ig,"~::~CROSS JOIN ")
.replace(/ INNER~::~{1,}JOIN /ig,"~::~INNER JOIN ")
.replace(/ LEFT~::~{1,}JOIN /ig,"~::~LEFT JOIN ")
.replace(/ RIGHT~::~{1,}JOIN /ig,"~::~RIGHT JOIN ")
.replace(/ ON /ig,"~::~"+tab+"ON ")
.replace(/ OR /ig,"~::~"+tab+tab+"OR ")
.replace(/ ORDER\s{1,}BY/ig,"~::~ORDER BY ")
.replace(/ OVER /ig,"~::~"+tab+"OVER ")
.replace(/\(\s{0,}SELECT /ig,"~::~(SELECT ")
.replace(/\)\s{0,}SELECT /ig,")~::~SELECT ")
.replace(/ THEN /ig," THEN~::~"+tab+"")
.replace(/ UNION /ig,"~::~UNION~::~")
.replace(/ USING /ig,"~::~USING ")
.replace(/ WHEN /ig,"~::~"+tab+"WHEN ")
.replace(/ WHERE /ig,"~::~WHERE ")
.replace(/ WITH /ig,"~::~WITH ")
//.replace(/\,\s{0,}\(/ig,",~::~( ")
//.replace(/\,/ig,",~::~"+tab+tab+"")
.replace(/ ALL /ig," ALL ")
.replace(/ AS /ig," AS ")
.replace(/ ASC /ig," ASC ")
.replace(/ DESC /ig," DESC ")
.replace(/ DISTINCT /ig," DISTINCT ")
.replace(/ EXISTS /ig," EXISTS ")
.replace(/ NOT /ig," NOT ")
.replace(/ NULL /ig," NULL ")
.replace(/ LIKE /ig," LIKE ")
.replace(/\s{0,}SELECT /ig,"SELECT ")
.replace(/\s{0,}UPDATE /ig,"UPDATE ")
.replace(/ SET /ig," SET ")
.replace(/~::~{1,}/g,"~::~")
.split('~::~');
}
vkbeautify.prototype.sql = function(text,step) {
var ar_by_quote = text.replace(/\s{1,}/g," ")
.replace(/\'/ig,"~::~\'")
.split('~::~'),
len = ar_by_quote.length,
ar = [],
deep = 0,
tab = this.step,//+this.step,
inComment = true,
inQuote = false,
parenthesisLevel = 0,
str = '',
ix = 0,
shift = step ? createShiftArr(step) : this.shift;;
for(ix=0;ix<len;ix++) {
if(ix%2) {
ar = ar.concat(ar_by_quote[ix]);
} else {
ar = ar.concat(split_sql(ar_by_quote[ix], tab) );
}
}
len = ar.length;
for(ix=0;ix<len;ix++) {
parenthesisLevel = isSubquery(ar[ix], parenthesisLevel);
if( /\s{0,}\s{0,}SELECT\s{0,}/.exec(ar[ix])) {
ar[ix] = ar[ix].replace(/\,/g,",\n"+tab+tab+"")
}
if( /\s{0,}\s{0,}SET\s{0,}/.exec(ar[ix])) {
ar[ix] = ar[ix].replace(/\,/g,",\n"+tab+tab+"")
}
if( /\s{0,}\(\s{0,}SELECT\s{0,}/.exec(ar[ix])) {
deep++;
str += shift[deep]+ar[ix];
} else
if( /\'/.exec(ar[ix]) ) {
if(parenthesisLevel<1 && deep) {
deep--;
}
str += ar[ix];
}
else {
str += shift[deep]+ar[ix];
if(parenthesisLevel<1 && deep) {
deep--;
}
}
var junk = 0;
}
str = str.replace(/^\n{1,}/,'').replace(/\n{1,}/g,"\n");
return str;
}
vkbeautify.prototype.xmlmin = function(text, preserveComments) {
var str = preserveComments ? text
: text.replace(/\<![ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\>/g,"")
.replace(/[ \r\n\t]{1,}xmlns/g, ' xmlns');
return str.replace(/>\s{0,}</g,"><");
}
vkbeautify.prototype.jsonmin = function(text) {
if (typeof JSON === 'undefined' ) return text;
return JSON.stringify(JSON.parse(text), null, 0);
}
vkbeautify.prototype.cssmin = function(text, preserveComments) {
var str = preserveComments ? text
: text.replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\//g,"") ;
return str.replace(/\s{1,}/g,' ')
.replace(/\{\s{1,}/g,"{")
.replace(/\}\s{1,}/g,"}")
.replace(/\;\s{1,}/g,";")
.replace(/\/\*\s{1,}/g,"/*")
.replace(/\*\/\s{1,}/g,"*/");
}
vkbeautify.prototype.sqlmin = function(text) {
return text.replace(/\s{1,}/g," ").replace(/\s{1,}\(/,"(").replace(/\s{1,}\)/,")");
}
return new vkbeautify();
});
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
var saveAs=saveAs||"undefined"!==typeof navigator&&navigator.msSaveOrOpenBlob&&navigator.msSaveOrOpenBlob.bind(navigator)||function(a){if("undefined"===typeof navigator||!/MSIE [1-9]\./.test(navigator.userAgent)){var k=a.document,n=k.createElementNS("http://www.w3.org/1999/xhtml","a"),w="download"in n,x=function(c){var e=k.createEvent("MouseEvents");e.initMouseEvent("click",!0,!1,a,0,0,0,0,0,!1,!1,!1,!1,0,null);c.dispatchEvent(e)},q=a.webkitRequestFileSystem,u=a.requestFileSystem||q||a.mozRequestFileSystem,
y=function(c){(a.setImmediate||a.setTimeout)(function(){throw c;},0)},r=0,s=function(c){var e=function(){"string"===typeof c?(a.URL||a.webkitURL||a).revokeObjectURL(c):c.remove()};a.chrome?e():setTimeout(e,10)},t=function(c,a,d){a=[].concat(a);for(var b=a.length;b--;){var l=c["on"+a[b]];if("function"===typeof l)try{l.call(c,d||c)}catch(f){y(f)}}},m=function(c,e){var d=this,b=c.type,l=!1,f,p,k=function(){t(d,["writestart","progress","write","writeend"])},g=function(){if(l||!f)f=(a.URL||a.webkitURL||
a).createObjectURL(c);p?p.location.href=f:void 0==a.open(f,"_blank")&&"undefined"!==typeof safari&&(a.location.href=f);d.readyState=d.DONE;k();s(f)},h=function(a){return function(){if(d.readyState!==d.DONE)return a.apply(this,arguments)}},m={create:!0,exclusive:!1},v;d.readyState=d.INIT;e||(e="download");if(w)f=(a.URL||a.webkitURL||a).createObjectURL(c),n.href=f,n.download=e,x(n),d.readyState=d.DONE,k(),s(f);else{a.chrome&&b&&"application/octet-stream"!==b&&(v=c.slice||c.webkitSlice,c=v.call(c,0,
c.size,"application/octet-stream"),l=!0);q&&"download"!==e&&(e+=".download");if("application/octet-stream"===b||q)p=a;u?(r+=c.size,u(a.TEMPORARY,r,h(function(a){a.root.getDirectory("saved",m,h(function(a){var b=function(){a.getFile(e,m,h(function(a){a.createWriter(h(function(b){b.onwriteend=function(b){p.location.href=a.toURL();d.readyState=d.DONE;t(d,"writeend",b);s(a)};b.onerror=function(){var a=b.error;a.code!==a.ABORT_ERR&&g()};["writestart","progress","write","abort"].forEach(function(a){b["on"+
a]=d["on"+a]});b.write(c);d.abort=function(){b.abort();d.readyState=d.DONE};d.readyState=d.WRITING}),g)}),g)};a.getFile(e,{create:!1},h(function(a){a.remove();b()}),h(function(a){a.code===a.NOT_FOUND_ERR?b():g()}))}),g)}),g)):g()}},b=m.prototype;b.abort=function(){this.readyState=this.DONE;t(this,"abort")};b.readyState=b.INIT=0;b.WRITING=1;b.DONE=2;b.error=b.onwritestart=b.onprogress=b.onwrite=b.onabort=b.onerror=b.onwriteend=null;return function(a,b){return new m(a,b)}}}("undefined"!==typeof self&&
self||"undefined"!==typeof window&&window||this.content);"undefined"!==typeof module&&null!==module?module.exports=saveAs:"undefined"!==typeof define&&null!==define&&null!=define.amd&&define('lib/FileSaver',[],function(){return saveAs});
define('utils',["lib/vkbeautify", "lib/FileSaver"], function(vkbeautify, FileSaver) {
return { set_options: set_options,
setup_svg: setup_svg,
remove_child_nodes: remove_child_nodes,
load_css: load_css,
load_files: load_files,
load_the_file: load_the_file,
make_class: make_class,
setup_defs: setup_defs,
draw_an_object: draw_an_object,
draw_a_nested_object: draw_a_nested_object,
make_array: make_array,
make_array_ref: make_array_ref,
compare_arrays: compare_arrays,
array_to_object: array_to_object,
clone: clone,
extend: extend,
unique_concat: unique_concat,
unique_strings_array: unique_strings_array,
debounce: debounce,
object_slice_for_ids: object_slice_for_ids,
object_slice_for_ids_ref: object_slice_for_ids_ref,
c_plus_c: c_plus_c,
c_minus_c: c_minus_c,
c_times_scalar: c_times_scalar,
download_json: download_json,
load_json: load_json,
load_json_or_csv: load_json_or_csv,
export_svg: export_svg,
rotate_coords_recursive: rotate_coords_recursive,
rotate_coords: rotate_coords,
get_angle: get_angle,
to_degrees: to_degrees,
angle_for_event: angle_for_event,
distance: distance,
check_undefined: check_undefined,
compartmentalize: compartmentalize,
decompartmentalize: decompartmentalize,
mean: mean,
median: median,
quartiles: quartiles,
random_characters: random_characters,
generate_map_id: generate_map_id,
check_for_parent_tag: check_for_parent_tag,
name_to_url: name_to_url,
parse_url_components: parse_url_components };
// definitions
function set_options(options, defaults, must_be_float) {
if (options === undefined || options === null)
return defaults;
var i = -1,
out = {};
for (var key in defaults) {
var has_key = ((key in options) &&
(options[key] !== null) &&
(options[key] !== undefined));
var val = (has_key ? options[key] : defaults[key]);
if (must_be_float && key in must_be_float) {
val = parseFloat(val);
if (isNaN(val)) {
if (has_key) {
console.warn('Bad float for option ' + key);
val = parseFloat(defaults[key]);
if (isNaN(val)) {
console.warn('Bad float for default ' + key);
val = null;
}
} else {
console.warn('Bad float for default ' + key);
val = null;
}
}
}
out[key] = val;
}
return out;
}
function setup_svg(selection, selection_is_svg, fill_screen) {
// sub selection places the graph in an existing svg environment
var add_svg = function(f, s) {
if (f) {
d3.select("body").classed('fill-screen-body', true);
s.classed('fill-screen-div', true);
}
var svg = s.append('svg')
.attr("class", "escher-svg")
.attr('xmlns', "http://www.w3.org/2000/svg");
return svg;
};
// run
var out;
// set the selection class
selection.classed('escher-container', true);
// make the svg
if (selection_is_svg) {
return selection;
} else if (selection) {
return add_svg(fill_screen, selection);
} else {
throw new Error('No selection');
}
}
function remove_child_nodes(selection) {
/** Removes all child nodes from a d3 selection
*/
var node = selection.node();
while (node.hasChildNodes()) {
node.removeChild(node.lastChild);
}
}
function load_css(css_path, callback) {
var css = "";
if (css_path) {
d3.text(css_path, function(error, text) {
if (error) {
console.warn(error);
}
css = text;
callback(css);
});
}
return false;
};
function update() {
return 'omg yes';
};
function load_the_file(t, file, callback, value) {
// if the value is specified, don't even need to do the ajax query
if (value) {
if (file) console.warn('File ' + file + ' overridden by value.');
callback.call(t, null, value, file);
return;
}
if (!file) {
callback.call(t, "No filename", null, file);
return;
}
if (ends_with(file, 'json'))
d3.json(file, function(e, d) { callback(e, d, file); });
else if (ends_with(file, 'css'))
d3.text(file, function(e, d) { callback(e, d, file); });
else
callback.call(t, "Unrecognized file type", null, file);
return;
// definitions
function ends_with(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
}
function load_files(t, files_to_load, final_callback) {
// load multiple files asynchronously
// Takes a list of objects: { file: a_filename.json, callback: a_callback_fn }
var i = -1, remaining = files_to_load.length, callbacks = {};
while (++i < files_to_load.length) {
var this_file = files_to_load[i].file;
callbacks[this_file] = files_to_load[i].callback;
load_the_file(t,
this_file,
function(e, d, file) {
callbacks[file].call(t, e, d);
if (!--remaining) final_callback.call(t);
},
files_to_load[i].value);
}
}
// makeClass - By Hubert Kauker (MIT Licensed)
// original by John Resig (MIT Licensed).
// http://stackoverflow.com/questions/7892884/simple-class-instantiation
function make_class(){
var isInternal;
var constructor = function(args){
if ( this instanceof constructor ) {
if ( typeof this.init == "function" ) {
this.init.apply( this, isInternal ? args : arguments );
}
} else {
isInternal = true;
var instance = new constructor( arguments );
isInternal = false;
return instance;
}
};
return constructor;
}
function setup_defs(svg, style) {
// add stylesheet
svg.select("defs").remove();
var defs = svg.append("defs");
// make sure the defs is the first node
var node = defs.node();
node.parentNode.insertBefore(node, node.parentNode.firstChild);
defs.append("style")
.attr("type", "text/css")
.text(style);
return defs;
}
function draw_an_object(container_sel, parent_node_selector, children_selector,
object, id_key, create_function, update_function,
exit_function) {
/** Run through the d3 data binding steps for an object. Also checks to
make sure none of the values in the *object* are undefined, and
ignores those.
The create_function, update_function, and exit_function CAN modify the
input data object.
Arguments
---------
container_sel: A d3 selection containing all objects.
parent_node_selector: A selector string for a subselection of
container_sel.
children_selector: A selector string for each DOM element to bind.
object: An object to bind to the selection.
id_key: The key that will be used to store object IDs in the bound data
points.
create_function: A function for enter selection.
update_function: A function for update selection.
exit_function: A function for exit selection.
*/
var draw_object = {};
for (var id in object) {
if (object[id] === undefined) {
console.warn('Undefined value for id ' + id + ' in object. Ignoring.');
} else {
draw_object[id] = object[id];
}
}
var sel = container_sel.select(parent_node_selector)
.selectAll(children_selector)
.data(make_array_ref(draw_object, id_key),
function(d) { return d[id_key]; });
// enter: generate and place reaction
if (create_function)
sel.enter().call(create_function);
// update: update when necessary
if (update_function)
sel.call(update_function);
// exit
if (exit_function)
sel.exit().call(exit_function);
}
function draw_a_nested_object(container_sel, children_selector, object_data_key,
id_key, create_function, update_function,
exit_function) {
/** Run through the d3 data binding steps for an object that is nested
within another element with d3 data.
The create_function, update_function, and exit_function CAN modify the
input data object.
Arguments
---------
container_sel: A d3 selection containing all objects.
children_selector: A selector string for each DOM element to bind.
object_data_key: A key for the parent object containing data for the
new selection.
id_key: The key that will be used to store object IDs in the bound data
points.
create_function: A function for enter selection.
update_function: A function for update selection.
exit_function: A function for exit selection.
*/
var sel = container_sel.selectAll(children_selector)
.data(function(d) {
return make_array_ref(d[object_data_key], id_key);
}, function(d) { return d[id_key]; });
// enter: generate and place reaction
if (create_function)
sel.enter().call(create_function);
// update: update when necessary
if (update_function)
sel.call(update_function);
// exit
if (exit_function)
sel.exit().call(exit_function);
}
function make_array(obj, id_key) { // is this super slow?
var array = [];
for (var key in obj) {
// copy object
var it = clone(obj[key]);
// add key as 'id'
it[id_key] = key;
// add object to array
array.push(it);
}
return array;
}
function make_array_ref(obj, id_key) {
/** Turn the object into an array, but only by reference. Faster than
make_array.
*/
var array = [];
for (var key in obj) {
// copy object
var it = obj[key];
// add key as 'id'
it[id_key] = key;
// add object to array
array.push(it);
}
return array;
}
function compare_arrays(a1, a2) {
/** Compares two simple (not-nested) arrays.
*/
if (!a1 || !a2) return false;
if (a1.length != a2.length) return false;
for (var i = 0, l=a1.length; i < l; i++) {
if (a1[i] != a2[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
}
function array_to_object(arr) {
/** Convert an array of objects to an object with all keys and values
that are arrays of the same length as arr. Fills in spaces with null.
For example, [ { a: 1 }, { b: 2 }] becomes { a: [1, null], b: [null, 2] }.
*/
// new object
var obj = {};
// for each element of the array
for (var i = 0, l = arr.length; i < l; i++) {
var column = arr[i],
keys = Object.keys(column);
for (var k = 0, nk = keys.length; k < nk; k++) {
var id = keys[k];
if (!(id in obj)) {
var n = [];
// fill spaces with null
for (var j = 0; j < l; j++) {
n[j] = null;
}
n[i] = column[id];
obj[id] = n;
} else {
obj[id][i] = column[id];
}
}
}
return obj;
}
function clone(obj) {
// Handles the array and object types, and null or undefined
if (null == obj || "object" != typeof obj) return obj;
// Handle Array
if (obj instanceof Array) {
var copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = clone(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
var copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
}
return copy;
}
throw new Error("Unable to copy obj! Its type isn't supported.");
}
function extend(obj1, obj2, overwrite) {
/** Extends obj1 with keys/values from obj2. Performs the extension
cautiously, and does not override attributes, unless the overwrite
argument is true.
Arguments
---------
obj1: Object to extend
obj2: Object with which to extend.
overwrite: (Optional, Default false) Overwrite attributes in obj1.
*/
if (overwrite === undefined)
overwrite = false;
for (var attrname in obj2) {
if (!(attrname in obj1) || overwrite) // UNIT TEST This
obj1[attrname] = obj2[attrname];
else
throw new Error('Attribute ' + attrname + ' already in object.');
}
}
function unique_concat(arrays) {
var new_array = [];
arrays.forEach(function (a) {
a.forEach(function(x) {
if (new_array.indexOf(x) < 0)
new_array.push(x);
});
});
return new_array;
}
function unique_strings_array(arr) {
/** Return unique values in array of strings.
http://stackoverflow.com/questions/1960473/unique-values-in-an-array
*/
var a = [];
for (var i = 0, l = arr.length; i < l; i++)
if (a.indexOf(arr[i]) === -1)
a.push(arr[i]);
return a;
}
function debounce(func, wait, immediate) {
/** Returns a function, that, as long as it continues to be invoked, will
not be triggered.
The function will be called after it stops being called for N
milliseconds. If `immediate` is passed, trigger the function on the leading
edge, instead of the trailing.
*/
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
window.clearTimeout(timeout);
timeout = window.setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
function object_slice_for_ids(obj, ids) {
/** Return a copy of the object with just the given ids.
Arguments
---------
obj: An object.
ids: An array of id strings.
*/
var subset = {}, i = -1;
while (++i<ids.length) {
subset[ids[i]] = clone(obj[ids[i]]);
}
if (ids.length != Object.keys(subset).length) {
console.warn('did not find correct reaction subset');
}
return subset;
}
function object_slice_for_ids_ref(obj, ids) {
/** Return a reference of the object with just the given ids. Faster
than object_slice_for_ids.
Arguments
---------
obj: An object.
ids: An array of id strings.
*/
var subset = {}, i = -1;
while (++i<ids.length) {
subset[ids[i]] = obj[ids[i]];
}
if (ids.length != Object.keys(subset).length) {
console.warn('did not find correct reaction subset');
}
return subset;
}
function c_plus_c(coords1, coords2) {
if (coords1 === null || coords2 === null ||
coords1 === undefined || coords2 === undefined)
return null;
return { "x": coords1.x + coords2.x,
"y": coords1.y + coords2.y };
}
function c_minus_c(coords1, coords2) {
if (coords1 === null || coords2 === null ||
coords1 === undefined || coords2 === undefined)
return null;
return { "x": coords1.x - coords2.x,
"y": coords1.y - coords2.y };
}
function c_times_scalar(coords, scalar) {
return { "x": coords.x * scalar,
"y": coords.y * scalar };
}
function download_json(json, name) {
/** Download json file in a blob.
*/
var j = JSON.stringify(json),
blob = new Blob([j], {type: "octet/stream"});
FileSaver(blob, name + '.json');
}
function load_json(f, callback, pre_fn, failure_fn) {
/** Try to load the file as JSON.
Arguments
---------
f: The file path
callback: A callback function that accepts arguments: error, data.
pre_fn: (optional) A function to call before loading the data.
failure_fn: (optional) A function to call if the load fails or is aborted.
*/
// Check for the various File API support.
if (!(window.File && window.FileReader && window.FileList && window.Blob))
callback("The File APIs are not fully supported in this browser.", null);
var reader = new window.FileReader();
// Closure to capture the file information.
reader.onload = function(event) {
var result = event.target.result,
data;
// try JSON
try {
data = JSON.parse(result);
} catch (e) {
// if it failed, return the error
callback(e, null);
return;
}
// if successful, return the data
callback(null, data);
};
if (pre_fn !== undefined && pre_fn !== null) {
try { pre_fn(); }
catch (e) { console.warn(e); }
}
reader.onabort = function(event) {
try { failure_fn(); }
catch (e) { console.warn(e); }
}
reader.onerror = function(event) {
try { failure_fn(); }
catch (e) { console.warn(e); }
}
// Read in the image file as a data URL.
reader.readAsText(f);
}
function load_json_or_csv(f, csv_converter, callback, pre_fn, failure_fn,
debug_event) {
/** Try to load the file as JSON or CSV (JSON first).
Arguments
---------
f: The file path
csv_converter: A function to convert the CSV output to equivalent JSON.
callback: A callback function that accepts arguments: error, data.
pre_fn: (optional) A function to call before loading the data.
failure_fn: (optional) A function to call if the load fails or is aborted.
debug_event: (optional) An event, with a string at
event.target.result, to load as though it was the contents of a
loaded file.
*/
// Check for the various File API support.
if (!(window.File && window.FileReader && window.FileList && window.Blob))
callback("The File APIs are not fully supported in this browser.", null);
var reader = new window.FileReader(),
// Closure to capture the file information.
onload_function = function(event) {
var result = event.target.result,
data, errors;
// try JSON
try {
data = JSON.parse(result);
} catch (e) {
errors = 'JSON error: ' + e;
// try csv
try {
data = csv_converter(d3.csv.parseRows(result));
} catch (e) {
// if both failed, return the errors
callback(errors + '\nCSV error: ' + e, null);
return;
}
}
// if successful, return the data
callback(null, data);
};
if (debug_event !== undefined && debug_event !== null) {
console.warn('Debugging load_json_or_csv');
return onload_function(debug_event);
}
if (pre_fn !== undefined && pre_fn !== null) {
try { pre_fn(); }
catch (e) { console.warn(e); }
}
reader.onabort = function(event) {
try { failure_fn(); }
catch (e) { console.warn(e); }
}
reader.onerror = function(event) {
try { failure_fn(); }
catch (e) { console.warn(e); }
}
// Read in the image file as a data URL.
reader.onload = onload_function;
reader.readAsText(f);
}
function export_svg(name, svg_sel, do_beautify) {
var a = document.createElement('a'), xml, ev;
a.download = name + '.svg'; // file name
// convert node to xml string
xml = (new XMLSerializer()).serializeToString(svg_sel.node());
if (do_beautify) xml = vkbeautify.xml(xml);
xml = '<?xml version="1.0" encoding="utf-8"?>\n \
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"\n \
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' + xml;
a.setAttribute("href-lang", "image/svg+xml");
a.href = 'data:image/svg+xml;base64,' + utf8_to_b64(xml); // create data uri
// <a> constructed, simulate mouse click on it
ev = document.createEvent("MouseEvents");
ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(ev);
// definitions
function utf8_to_b64(str) {
return window.btoa(unescape(encodeURIComponent( str )));
}
};
function rotate_coords_recursive(coords_array, angle, center) {
var rot = function(c) { return rotate_coords(c, angle, center); };
return coords_array.map(rot);
}
function rotate_coords(c, angle, center) {
/** Calculates displacement { x: dx, y: dy } based on rotating point c around
center with angle.
*/
var dx = Math.cos(-angle) * (c.x - center.x) +
Math.sin(-angle) * (c.y - center.y)
+ center.x - c.x,
dy = - Math.sin(-angle) * (c.x - center.x) +
Math.cos(-angle) * (c.y - center.y)
+ center.y - c.y;
return { x: dx, y: dy };
}
function get_angle(coords) {
/* Takes an array of 2 coordinate objects {"x": 1, "y": 1}
*
* Returns angle between 0 and 2PI.
*/
var denominator = coords[1].x - coords[0].x,
numerator = coords[1].y - coords[0].y;
if (denominator==0 && numerator >= 0) return Math.PI/2;
else if (denominator==0 && numerator < 0) return 3*Math.PI/2;
else if (denominator >= 0 && numerator >= 0) return Math.atan(numerator/denominator);
else if (denominator >= 0) return (Math.atan(numerator/denominator) + 2*Math.PI);
else return (Math.atan(numerator/denominator) + Math.PI);
}
function to_degrees(radians) { return radians*180/Math.PI; }
function angle_for_event(displacement, point, center) {
var gamma = Math.atan2((point.x - center.x), (center.y - point.y)),
beta = Math.atan2((point.x - center.x + displacement.x),
(center.y - point.y - displacement.y)),
angle = beta - gamma;
return angle;
}
function distance(start, end) { return Math.sqrt(Math.pow(end.y-start.y, 2) + Math.pow(end.x-start.x, 2)); }
function check_undefined(args, names) {
/** Report an error if any of the arguments are undefined.
Call by passing in *arguments* from any function and an array of
argument names.
*/
names.map(function(name, i) {
if (args[i]===undefined) {
console.error('Argument is undefined: '+String(names[i]));
}
});
}
function compartmentalize(bigg_id, compartment_id) {
return bigg_id + '_' + compartment_id;
}
// definitions
function decompartmentalize(id) {
/** Convert ids to bigg_id and compartment_id.
*/
var out = no_compartment(id);
if (out===null) out = [id, null];
return out;
// definitions
function no_compartment(id) {
/** Returns an array of [bigg_id, compartment id].
Matches compartment ids with length 1 or 2.
Return null if no match is found.
*/
var reg = /(.*)_([a-z0-9]{1,2})$/,
result = reg.exec(id);
if (result===null) return null;
return result.slice(1,3);
}
}
function mean(array) {
var sum = array.reduce(function(a, b) { return a + b; });
var avg = sum / array.length;
return avg;
}
function median(array) {
array.sort(function(a, b) { return a - b; });
var half = Math.floor(array.length / 2);
if(array.length % 2 == 1)
return array[half];
else
return (array[half-1] + array[half]) / 2.0;
}
function quartiles(array) {
array.sort(function(a, b) { return a - b; });
var half = Math.floor(array.length / 2);
if (array.length == 1)
return [ array[0], array[0], array[0] ];
else if (array.length % 2 == 1)
return [ median(array.slice(0, half)),
array[half],
median(array.slice(half + 1)) ];
else
return [ median(array.slice(0, half)),
(array[half-1] + array[half]) / 2.0,
median(array.slice(half)) ];
}
function random_characters(num) {
// Thanks to @csharptest.net
// http://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript
var text = '',
possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < num; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function generate_map_id() {
return random_characters(12);
}
function check_for_parent_tag(el, tag) {
/** Check that the selection has the given parent tag.
el: A d3 selection or node.
tag: A tag name (case insensitive)
*/
// make sure it is a node
if (el instanceof Array)
el = el.node();
while (el.parentNode !== null) {
el = el.parentNode;
if (el.tagName === undefined) continue;
if (el.tagName.toLowerCase() === tag.toLowerCase())
return true;
}
return false;
}
function name_to_url(name, download_url) {
/** Convert model or map name to url.
Arguments
---------
name: The short name, e.g. e_coli.iJO1366.central_metabolism.
download_url: The url to prepend (optional).
*/
if (download_url !== undefined && download_url !== null) {
// strip download_url
download_url = download_url.replace(/^\/|\/$/g, '');
name = [download_url, name].join('/');
}
// strip final path
return name.replace(/^\/|\/$/g, '') + '.json';
}
function parse_url_components(the_window, options) {
/** Parse the URL and return options based on the URL arguments.
Arguments
---------
the_window: A reference to the global window.
options: (optional) an existing options object to which new options
will be added. Overwrites existing arguments in options.
Adapted from http://stackoverflow.com/questions/979975/how-to-get-the-value-from-url-parameter
*/
if (options===undefined) options = {};
var query = the_window.location.search.substring(1),
vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("="),
val = decodeURIComponent(pair[1]);
// deal with array options
if (pair[0].indexOf('[]') == pair[0].length - 2) {
var o = pair[0].replace('[]', '');
if (!(o in options))
options[o] = [];
options[o].push(val);
} else {
options[pair[0]] = val;
}
}
return options;
}
});
define('PlacedDiv',['utils'], function(utils) {
/** A container to position an html div to match the coordinates of a SVG element.
*/
var PlacedDiv = utils.make_class();
// instance methods
PlacedDiv.prototype = { init: init,
is_visible: is_visible,
place: place,
hide: hide };
return PlacedDiv;
// definitions
function init(div, map, displacement) {
// make the input box
this.div = div;
if (displacement===undefined)
displacement = {x: 0, y: 0};
this.displacement = displacement;
this.map = map;
}
function is_visible() {
return this.div.style('display') != 'none';
}
function place(coords) {
/** Position the html div to match the given SVG coordinates.
*/
// show the input
this.div.style('display', null);
// move the new input
var window_translate = this.map.zoom_container.window_translate,
window_scale = this.map.zoom_container.window_scale,
map_size = this.map.get_size(),
left = Math.max(20,
Math.min(map_size.width - 270,
(window_scale * coords.x + window_translate.x - this.displacement.x))),
top = Math.max(20,
Math.min(map_size.height - 40,
(window_scale * coords.y + window_translate.y - this.displacement.y)));
this.div.style('position', 'absolute')
.style('display', 'block')
.style('left', left+'px')
.style('top', top+'px');
}
function hide() {
this.div.style('display', 'none');
}
});
/**
* complete.ly 1.0.0
* MIT Licensing
* Copyright (c) 2013 Lorenzo Puccetti
*
* This Software shall be used for doing good things, not bad things.
*
* Liberally modified by Zachary King (c) 2014.
*
**/
define('lib/complete.ly',[],function() {
return function(container, config) {
config = config || {};
config.fontSize = config.fontSize || '13px';
config.fontFamily = config.fontFamily || 'sans-serif';
config.promptInnerHTML = config.promptInnerHTML || '';
config.color = config.color || '#333';
config.hintColor = config.hintColor || '#aaa';
config.backgroundColor = config.backgroundColor || '#fff';
config.dropDownBorderColor = config.dropDownBorderColor || '#aaa';
config.dropDownZIndex = config.dropDownZIndex || '100'; // to ensure we are in front of everybody
config.dropDownOnHoverBackgroundColor = config.dropDownOnHoverBackgroundColor || '#ddd';
var txtInput = document.createElement('input');
txtInput.type ='text';
txtInput.spellcheck = false;
txtInput.style.fontSize = config.fontSize;
txtInput.style.fontFamily = config.fontFamily;
txtInput.style.color = config.color;
txtInput.style.backgroundColor = config.backgroundColor;
txtInput.style.width = '100%';
txtInput.style.outline = '0';
txtInput.style.border = '0';
txtInput.style.margin = '0';
txtInput.style.padding = '0';
var txtHint = txtInput.cloneNode();
txtHint.disabled='';
txtHint.style.position = 'absolute';
txtHint.style.top = '0';
txtHint.style.left = '0';
txtHint.style.borderColor = 'transparent';
txtHint.style.boxShadow = 'none';
txtHint.style.color = config.hintColor;
txtInput.style.backgroundColor ='transparent';
txtInput.style.verticalAlign = 'top';
txtInput.style.position = 'relative';
var wrapper = document.createElement('div');
wrapper.style.position = 'relative';
wrapper.style.outline = '0';
wrapper.style.border = '0';
wrapper.style.margin = '0';
wrapper.style.padding = '0';
var prompt = document.createElement('div');
prompt.style.position = 'absolute';
prompt.style.outline = '0';
prompt.style.margin = '0';
prompt.style.padding = '0';
prompt.style.border = '0';
prompt.style.fontSize = config.fontSize;
prompt.style.fontFamily = config.fontFamily;
prompt.style.color = config.color;
prompt.style.backgroundColor = config.backgroundColor;
prompt.style.top = '0';
prompt.style.left = '0';
prompt.style.overflow = 'hidden';
prompt.innerHTML = config.promptInnerHTML;
prompt.style.background = 'transparent';
if (document.body === undefined) {
throw 'document.body is undefined. The library was wired up incorrectly.';
}
document.body.appendChild(prompt);
var w = prompt.getBoundingClientRect().right; // works out the width of the prompt.
wrapper.appendChild(prompt);
prompt.style.visibility = 'visible';
prompt.style.left = '-'+w+'px';
wrapper.style.marginLeft= w+'px';
wrapper.appendChild(txtHint);
wrapper.appendChild(txtInput);
var dropDown = document.createElement('div');
dropDown.style.position = 'absolute';
dropDown.style.visibility = 'hidden';
dropDown.style.outline = '0';
dropDown.style.margin = '0';
dropDown.style.padding = '0';
dropDown.style.textAlign = 'left';
dropDown.style.fontSize = config.fontSize;
dropDown.style.fontFamily = config.fontFamily;
dropDown.style.backgroundColor = config.backgroundColor;
dropDown.style.zIndex = config.dropDownZIndex;
dropDown.style.cursor = 'default';
dropDown.style.borderStyle = 'solid';
dropDown.style.borderWidth = '1px';
dropDown.style.borderColor = config.dropDownBorderColor;
dropDown.style.overflowX= 'hidden';
dropDown.style.whiteSpace = 'pre';
dropDown.style.overflowY = 'scroll';
var createDropDownController = function(elem) {
var rows = [];
var ix = 0;
var oldIndex = -1;
var current_row = null;
var onMouseOver = function() { this.style.outline = '1px solid #ddd'; }
var onMouseOut = function() { this.style.outline = '0'; }
var onDblClick = function(e) {
e.preventDefault();
p.onmouseselection(this.id);
}
var p = {
hide : function() { elem.style.visibility = 'hidden'; },
refresh : function(token, options) {
elem.style.visibility = 'hidden';
ix = 0;
elem.innerHTML ='';
var vph = (window.innerHeight || document.documentElement.clientHeight);
var rect = elem.parentNode.getBoundingClientRect();
var distanceToTop = rect.top - 6; // heuristic give 6px
var distanceToBottom = vph - rect.bottom -6; // distance from the browser border.
rows = [];
for (var i = 0; i < options.length; i++) {
// ignore case
var found = options[i].matches.filter(function(match) {
return match.toLowerCase().indexOf(token.toLowerCase()) == 0;
});
if (found.length == 0)
continue;
var divRow = document.createElement('div');
divRow.style.color = config.color;
divRow.onmouseover = onMouseOver;
divRow.onmouseout = onMouseOut;
// prevent selection for double click
divRow.onmousedown = function(e) { e.preventDefault(); };
divRow.ondblclick = onDblClick;
divRow.__hint = found[0];
divRow.id = options[i].id;
divRow.innerHTML = options[i].html;
rows.push(divRow);
elem.appendChild(divRow);
if (rows.length >= rs.display_limit)
break;
}
if (rows.length===0) {
return; // nothing to show.
}
p.highlight(0);
// Heuristic (only when the distance to the to top is 4
// times more than distance to the bottom
if (distanceToTop > distanceToBottom*3) {
// we display the dropDown on the top of the input text
elem.style.maxHeight = distanceToTop+'px';
elem.style.top ='';
elem.style.bottom ='100%';
} else {
elem.style.top = '100%';
elem.style.bottom = '';
elem.style.maxHeight = distanceToBottom+'px';
}
elem.style.visibility = 'visible';
},
highlight : function(index) {
if (oldIndex !=-1 && rows[oldIndex]) {
rows[oldIndex].style.backgroundColor = config.backgroundColor;
}
rows[index].style.backgroundColor = config.dropDownOnHoverBackgroundColor; // <-- should be config
oldIndex = index;
current_row = rows[index];
},
// moves the selection either up or down (unless it's not
// possible) step is either +1 or -1.
move : function(step) {
// nothing to move if there is no dropDown. (this happens if
// the user hits escape and then down or up)
if (elem.style.visibility === 'hidden')
return '';
// No circular scrolling
if (ix+step === -1 || ix+step === rows.length)
return rows[ix].__hint;
ix+=step;
p.highlight(ix);
return rows[ix].__hint;
},
onmouseselection : function() {},
get_current_row: function () {
return current_row;
}
};
return p;
}
var dropDownController = createDropDownController(dropDown);
dropDownController.onmouseselection = function(id) {
rs.onEnter(id)
rs.input.focus();
}
wrapper.appendChild(dropDown);
container.appendChild(wrapper);
var spacer,
// This will contain the leftSide part of the textfield (the bit that
// was already autocompleted)
leftSide;
function calculateWidthForText(text) {
if (spacer === undefined) { // on first call only.
spacer = document.createElement('span');
spacer.style.visibility = 'hidden';
spacer.style.position = 'fixed';
spacer.style.outline = '0';
spacer.style.margin = '0';
spacer.style.padding = '0';
spacer.style.border = '0';
spacer.style.left = '0';
spacer.style.whiteSpace = 'pre';
spacer.style.fontSize = config.fontSize;
spacer.style.fontFamily = config.fontFamily;
spacer.style.fontWeight = 'normal';
document.body.appendChild(spacer);
}
// Used to encode an HTML string into a plain text.
// taken from http://stackoverflow.com/questions/1219860/javascript-jquery-html-encoding
spacer.innerHTML = String(text).replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
return spacer.getBoundingClientRect().right;
}
var rs = {
get_hint : function(x) { return x; },
display_limit: 100,
onArrowDown : function() {}, // defaults to no action.
onArrowUp : function() {}, // defaults to no action.
onEnter : function() {}, // defaults to no action.
onTab : function() {}, // defaults to no action.
onChange: function() { rs.repaint() }, // defaults to repainting.
startFrom: 0,
options: [],
// Only to allow easy access to the HTML elements to the final user
// (possibly for minor customizations)
wrapper : wrapper,
input : txtInput,
hint : txtHint,
dropDown : dropDown,
prompt : prompt,
setText : function(text) {
txtHint.value = text;
txtInput.value = text;
},
getText : function() {
return txtInput.value;
},
hideDropDown : function() {
dropDownController.hide();
},
repaint : function() {
var text = txtInput.value;
var startFrom = rs.startFrom;
var options = rs.options;
var optionsLength = options.length;
// breaking text in leftSide and token.
var token = text.substring(startFrom);
leftSide = text.substring(0,startFrom);
// updating the hint.
txtHint.value ='';
for (var i = 0; i < optionsLength; i++) {
var found = options[i].matches.filter(function(match) {
return match.toLowerCase().indexOf(token.toLowerCase()) == 0;
});
if (found.length == 0)
continue;
txtHint.value = rs.get_hint(found[0]);
break;
}
// moving the dropDown and refreshing it.
dropDown.style.left = calculateWidthForText(leftSide)+'px';
dropDownController.refresh(token, rs.options);
}
};
var registerOnTextChangeOldValue;
// Register a callback function to detect changes to the content of the
// input-type-text. Those changes are typically followed by user's
// action: a key-stroke event but sometimes it might be a mouse click.
var registerOnTextChange = function(txt, callback) {
registerOnTextChangeOldValue = txt.value;
var handler = function() {
var value = txt.value;
if (registerOnTextChangeOldValue !== value) {
registerOnTextChangeOldValue = value;
callback(value);
}
};
// For user's actions, we listen to both input events and key up events
// It appears that input events are not enough so we defensively listen to key up events too.
// source: http://help.dottoro.com/ljhxklln.php
//
// The cost of listening to three sources should be negligible as the handler will invoke callback function
// only if the text.value was effectively changed.
txt.addEventListener("input", handler, false);
txt.addEventListener('keyup', handler, false);
txt.addEventListener('change', handler, false);
};
registerOnTextChange(txtInput,function(text) { // note the function needs to be wrapped as API-users will define their onChange
rs.onChange(text);
rs.repaint();
});
var keyDownHandler = function(e) {
e = e || window.event;
var keyCode = e.keyCode;
if (keyCode == 33) { return; } // page up (do nothing)
if (keyCode == 34) { return; } // page down (do nothing);
// right, end, tab (autocomplete triggered)
if (keyCode == 39 || keyCode == 35 || keyCode == 9) {
// for tabs we need to ensure that we override the default
// behaviour: move to the next focusable HTML-element
if (keyCode == 9) {
e.preventDefault();
e.stopPropagation();
if (txtHint.value.length == 0) {
// tab was called with no action.
rs.onTab();
}
}
// if there is a hint
if (txtHint.value.length > 0) {
txtInput.value = txtHint.value;
var hasTextChanged = registerOnTextChangeOldValue != txtInput.value
// avoid dropDown to appear again
registerOnTextChangeOldValue = txtInput.value;
// for example imagine the array contains the following
// words: bee, beef, beetroot. User has hit enter to get
// 'bee' it would be prompted with the dropDown again (as
// beef and beetroot also match)
if (hasTextChanged) {
// force it.
rs.onChange(txtInput.value);
}
}
return;
}
if (keyCode == 13) { // enter
// get current
var id = dropDownController.get_current_row().id;
rs.onEnter(id);
return;
}
if (keyCode == 40) { // down
var m = dropDownController.move(+1);
if (m == '') { rs.onArrowDown(); }
txtHint.value = rs.get_hint(m);
return;
}
if (keyCode == 38 ) { // up
var m = dropDownController.move(-1);
if (m == '') { rs.onArrowUp(); }
txtHint.value = rs.get_hint(m);
e.preventDefault();
e.stopPropagation();
return;
}
// it's important to reset the txtHint on key down. Think: user
// presses a letter (e.g. 'x') and never releases. You get
// (xxxxxxxxxxxxxxxxx) and you would see still the hint. Reset the
// txtHint. (it might be updated onKeyUp).
txtHint.value ='';
};
txtInput.addEventListener("keydown", keyDownHandler, false);
return rs;
}
});
define('DirectionArrow',["utils"], function(utils) {
/** DirectionArrow returns a constructor for an arrow that can be rotated
and dragged, and supplies its direction.
*/
var DirectionArrow = utils.make_class();
DirectionArrow.prototype = { init: init,
set_location: set_location,
set_rotation: set_rotation,
displace_rotation: displace_rotation,
get_rotation: get_rotation,
toggle: toggle,
show: show,
hide: hide,
right: right,
left: left,
up: up,
down: down,
_setup_drag: _setup_drag };
return DirectionArrow;
// definitions
function init(sel) {
this.arrow_container = sel.append('g')
.attr('id', 'direction-arrow-container')
.attr('transform', 'translate(0,0)rotate(0)');
this.arrow = this.arrow_container.append('path')
.classed('direction-arrow', true)
.attr('d', path_for_arrow())
.style('visibility', 'hidden')
.attr('transform', 'translate(30,0)scale(2.5)');
this.sel = sel;
this.center = { x: 0, y: 0 };
this._setup_drag();
this.dragging = false;
this.is_visible = false;
this.show();
// definitions
function path_for_arrow() {
return "M0 -5 L0 5 L20 5 L20 10 L30 0 L20 -10 L20 -5 Z";
}
}
function set_location(coords) {
/** Move the arrow to coords.
*/
this.center = coords;
var transform = d3.transform(this.arrow_container.attr('transform'));
this.arrow_container.attr('transform',
'translate('+coords.x+','+coords.y+')rotate('+transform.rotate+')');
}
function set_rotation(rotation) {
/** Rotate the arrow to rotation.
*/
var transform = d3.transform(this.arrow_container.attr('transform'));
this.arrow_container.attr('transform',
'translate('+transform.translate+')rotate('+rotation+')');
}
function displace_rotation(d_rotation) {
/** Displace the arrow rotation by a set amount.
*/
var transform = d3.transform(this.arrow_container.attr('transform'));
this.arrow_container.attr('transform',
'translate('+transform.translate+')'+
'rotate('+(transform.rotate+d_rotation)+')');
}
function get_rotation() {
/** Returns the arrow rotation.
*/
return d3.transform(this.arrow_container.attr('transform')).rotate;
}
function toggle(on_off) {
if (on_off===undefined) this.is_visible = !this.is_visible;
else this.is_visible = on_off;
this.arrow.style('visibility', this.is_visible ? 'visible' : 'hidden');
}
function show() {
this.toggle(true);
}
function hide() {
this.toggle(false);
}
function right() {
this.set_rotation(0);
}
function down() {
this.set_rotation(90);
}
function left() {
this.set_rotation(180);
}
function up() {
this.set_rotation(270);
}
function _setup_drag() {
var b = d3.behavior.drag()
.on("dragstart", function(d) {
// silence other listeners
d3.event.sourceEvent.stopPropagation();
this.dragging = true;
}.bind(this))
.on("drag.direction_arrow", function(d) {
var displacement = { x: d3.event.dx,
y: d3.event.dy },
location = { x: d3.mouse(this.sel.node())[0],
y: d3.mouse(this.sel.node())[1] },
d_angle = utils.angle_for_event(displacement,
location,
this.center);
this.displace_rotation(utils.to_degrees(d_angle));
}.bind(this))
.on("dragend", function(d) {
window.setTimeout(function() {
this.dragging = false;
}.bind(this), 200);
}.bind(this));
this.arrow_container.call(b);
}
});
define('data_styles',['utils'], function(utils) {
// globals
var RETURN_ARG = function(x) { return x; },
ESCAPE_REG = /([.*+?^=!:${}()|\[\]\/\\])/g,
EMPTY_LINES = /\n\s*\n/g,
TRAILING_NEWLINE = /\n\s*(\)*)\s*$/,
AND_OR = /([\(\) ])(?:and|or)([\)\( ])/ig,
ALL_PARENS = /[\(\)]/g,
// capture an expression surrounded by whitespace and a set of parentheses
EXCESS_PARENS = /\(\s*(\S+)\s*\)/g,
OR = /\s+or\s+/i,
AND = /\s+and\s+/i,
// find ORs
OR_EXPRESSION = /(^|\()(\s*-?[0-9.]+\s+(?:or\s+-?[0-9.]+\s*)+)(\)|$)/ig,
// find ANDS, respecting order of operations (and before or)
AND_EXPRESSION = /(^|\(|or\s)(\s*-?[0-9.]+\s+(?:and\s+-?[0-9.]+\s*)+)(\sor|\)|$)/ig;
return { import_and_check: import_and_check,
text_for_data: text_for_data,
float_for_data: float_for_data,
reverse_flux_for_data: reverse_flux_for_data,
gene_string_for_data: gene_string_for_data,
csv_converter: csv_converter,
genes_for_gene_reaction_rule: genes_for_gene_reaction_rule,
evaluate_gene_reaction_rule: evaluate_gene_reaction_rule,
replace_gene_in_rule: replace_gene_in_rule,
apply_reaction_data_to_reactions: apply_reaction_data_to_reactions,
apply_metabolite_data_to_nodes: apply_metabolite_data_to_nodes,
apply_gene_data_to_reactions: apply_gene_data_to_reactions
};
function import_and_check(data, name, all_reactions) {
/** Convert imported data to a style that can be applied to reactions
and nodes.
Arguments
---------
data: The data object.
name: Either 'reaction_data', 'metabolite_data', or 'gene_data'
all_reactions: Required for name == 'gene_data'. Must include all
GPRs for the map and model.
*/
// check arguments
if (data===null)
return null;
if (['reaction_data', 'metabolite_data', 'gene_data'].indexOf(name) == -1)
throw new Error('Invalid name argument: ' + name);
// make array
if (!(data instanceof Array)) {
data = [data];
}
// check data
var check = function() {
if (data===null)
return null;
if (data.length==1)
return null;
if (data.length==2)
return null;
return console.warn('Bad data style: ' + name);
};
check();
data = utils.array_to_object(data);
if (name == 'gene_data') {
if (all_reactions === undefined)
throw new Error('Must pass all_reactions argument for gene_data');
data = align_gene_data_to_reactions(data, all_reactions);
}
return data;
// definitions
function align_gene_data_to_reactions(data, reactions) {
var aligned = {},
null_val = [null];
// make an array of nulls as the default
for (var gene_id in data) {
null_val = data[gene_id].map(function() { return null; });
break;
}
for (var reaction_id in reactions) {
var reaction = reactions[reaction_id],
bigg_id = reaction.bigg_id,
this_gene_data = {};
// save to aligned
// get the genes if they aren't already there
var g = reaction.genes,
genes;
if (typeof g === 'undefined')
genes = genes_for_gene_reaction_rule(reaction.gene_reaction_rule);
else
genes = g.map(function(x) { return x.bigg_id; });
genes.forEach(function(gene_id) {
var d = data[gene_id];
if (typeof d === 'undefined')
d = null_val;
this_gene_data[gene_id] = d;
});
aligned[bigg_id] = this_gene_data;
}
return aligned;
}
}
function float_for_data(d, styles, compare_style) {
// all null
if (d === null)
return null;
// absolute value
var take_abs = (styles.indexOf('abs') != -1);
if (d.length==1) { // 1 set
// 1 null
var f = _parse_float_or_null(d[0]);
if (f === null)
return null;
return abs(f, take_abs);
} else if (d.length==2) { // 2 sets
// 2 null
var fs = d.map(_parse_float_or_null);
if (fs[0] === null || fs[1] === null)
return null;
if (compare_style == 'diff') {
return diff(fs[0], fs[1], take_abs);
} else if (compare_style == 'fold') {
return check_finite(fold(fs[0], fs[1], take_abs));
}
else if (compare_style == 'log2_fold') {
return check_finite(log2_fold(fs[0], fs[1], take_abs));
}
} else {
throw new Error('Data array must be of length 1 or 2');
}
throw new Error('Bad data compare_style: ' + compare_style);
// definitions
function check_finite(x) {
return isFinite(x) ? x : null;
}
function abs(x, take_abs) {
return take_abs ? Math.abs(x) : x;
}
function diff(x, y, take_abs) {
if (take_abs) return Math.abs(y - x);
else return y - x;
}
function fold(x, y, take_abs) {
if (x == 0 || y == 0) return null;
var fold = (y >= x ? y / x : - x / y);
return take_abs ? Math.abs(fold) : fold;
}
function log2_fold(x, y, take_abs) {
if (x == 0) return null;
if (y / x < 0) return null;
var log = Math.log(y / x) / Math.log(2);
return take_abs ? Math.abs(log) : log;
}
}
function reverse_flux_for_data(d) {
if (d === null || d[0] === null)
return false;
return (d[0] < 0);
}
function gene_string_for_data(rule, gene_values, genes, styles,
identifiers_on_map, compare_style) {
/** Add gene values to the gene_reaction_rule string.
Arguments
---------
rule: (string) The gene reaction rule.
gene_values: The values.
genes: An array of objects specifying the gene bigg_id and name.
styles: The reaction styles.
identifiers_on_map: The type of identifiers ('bigg_id' or 'name').
compare_style: The comparison style.
Returns
-------
The new string with formatted data values.
*/
var out = rule,
no_data = (gene_values === null),
// keep track of bigg_id's or names to remove repeats
genes_found = {};
genes.forEach(function(g_obj) {
// get id or name
var name = g_obj[identifiers_on_map];
if (typeof name === 'undefined')
throw new Error('Bad value for identifiers_on_map: ' + identifiers_on_map);
// remove repeats that may have found their way into genes object
if (typeof genes_found[name] !== 'undefined')
return;
genes_found[name] = true;
// generate the string
if (no_data) {
out = replace_gene_in_rule(out, g_obj.bigg_id, (name + '\n'));
} else {
var d = gene_values[g_obj.bigg_id];
if (typeof d === 'undefined') d = null;
var f = float_for_data(d, styles, compare_style),
format = (f === null ? RETURN_ARG : d3.format('.3g'));
if (d.length==1) {
out = replace_gene_in_rule(out, g_obj.bigg_id, (name + ' (' + null_or_d(d[0], format) + ')\n'));
}
else if (d.length==2) {
// check if they are all text
var new_str,
any_num = d.reduce(function(c, x) {
return c || _parse_float_or_null(x) !== null;
}, false);
if (any_num) {
new_str = (name + ' (' +
null_or_d(d[0], format) + ', ' +
null_or_d(d[1], format) + ': ' +
null_or_d(f, format) +
')\n');
} else {
new_str = (name + ' (' +
null_or_d(d[0], format) + ', ' +
null_or_d(d[1], format) + ')\n');
}
out = replace_gene_in_rule(out, g_obj.bigg_id, new_str);
}
}
});
// remove emtpy lines
out = out.replace(EMPTY_LINES, '\n')
// remove trailing newline (with or without parens)
.replace(TRAILING_NEWLINE, '$1');
return out;
// definitions
function null_or_d(d, format) {
return d === null ? 'nd' : format(d);
}
}
function text_for_data(d, f) {
if (d === null)
return null_or_d(null);
if (d.length == 1) {
var format = (f === null ? RETURN_ARG : d3.format('.3g'));
return null_or_d(d[0], format);
}
if (d.length == 2) {
var format = (f === null ? RETURN_ARG : d3.format('.3g')),
t = null_or_d(d[0], format);
t += ', ' + null_or_d(d[1], format);
t += ': ' + null_or_d(f, format);
return t;
}
return '';
// definitions
function null_or_d(d, format) {
return d === null ? '(nd)' : format(d);
}
}
function csv_converter(csv_rows) {
/** Convert data from a csv file to json-style data.
File must include a header row.
*/
// count rows
var c = csv_rows[0].length,
converted = [];
if (c < 2 || c > 3)
throw new Error('CSV file must have 2 or 3 columns');
// set up rows
for (var i = 1; i < c; i++) {
converted[i - 1] = {};
}
// fill
csv_rows.slice(1).forEach(function(row) {
for (var i = 1, l = row.length; i < l; i++) {
converted[i - 1][row[0]] = row[i];
}
});
return converted;
}
function genes_for_gene_reaction_rule(rule) {
/** Find unique genes in gene_reaction_rule string.
Arguments
---------
rule: A boolean string containing gene names, parentheses, AND's and
OR's.
Returns
-------
An array of gene strings.
*/
var genes = rule
// remove ANDs and ORs, surrounded by space or parentheses
.replace(AND_OR, '$1$2')
// remove parentheses
.replace(ALL_PARENS, '')
// split on whitespace
.split(' ')
.filter(function(x) { return x != ''; });
// unique strings
return utils.unique_strings_array(genes);
}
function evaluate_gene_reaction_rule(rule, gene_values, and_method_in_gene_reaction_rule) {
/** Return a value given the rule and gene_values object.
Arguments
---------
rule: A boolean string containing gene names, parentheses, AND's and
OR's.
gene_values: Object with gene_ids for keys and numbers for values.
and_method_in_gene_reaction_rule: Either 'mean' or 'min'.
*/
var null_val = [null],
l = 1;
// make an array of nulls as the default
for (var gene_id in gene_values) {
null_val = gene_values[gene_id].map(function() { return null; });
l = null_val.length;
break;
}
if (rule == '') return null_val;
// for each element in the arrays
var out = [];
for (var i = 0; i < l; i++) {
// get the rule
var curr_val = rule;
// put all the numbers into the expression
var all_null = true;
for (var gene_id in gene_values) {
var f = _parse_float_or_null(gene_values[gene_id][i]);
if (f === null) {
f = 0;
} else {
all_null = false;
}
curr_val = replace_gene_in_rule(curr_val, gene_id, f);
}
if (all_null) {
out.push(null);
continue;
}
// recursively evaluate
while (true) {
// arithemtic expressions
var new_curr_val = curr_val;
// take out excessive parentheses
new_curr_val = new_curr_val.replace(EXCESS_PARENS, ' $1 ');
// or's
new_curr_val = new_curr_val.replace(OR_EXPRESSION, function(match, p1, p2, p3) {
// sum
var nums = p2.split(OR).map(parseFloat),
sum = nums.reduce(function(a, b) { return a + b;});
return p1 + sum + p3;
});
// and's
new_curr_val = new_curr_val.replace(AND_EXPRESSION, function(match, p1, p2, p3) {
// find min
var nums = p2.split(AND).map(parseFloat),
val = (and_method_in_gene_reaction_rule == 'min' ?
Math.min.apply(null, nums) :
nums.reduce(function(a, b) { return a + b; }) / nums.length);
return p1 + val + p3;
});
// break if there is no change
if (new_curr_val == curr_val)
break;
curr_val = new_curr_val;
}
// strict test for number
var num = Number(curr_val);
if (isNaN(num)) {
console.warn('Could not evaluate ' + rule);
out.push(null);
} else {
out.push(num);
}
}
return out;
}
function replace_gene_in_rule(rule, gene_id, val) {
// get the escaped string, with surrounding space or parentheses
var space_or_par_start = '(^|[\\\s\\\(\\\)])',
space_or_par_finish = '([\\\s\\\(\\\)]|$)',
escaped = space_or_par_start + escape_reg_exp(gene_id) + space_or_par_finish;
return rule.replace(new RegExp(escaped, 'g'), '$1' + val + '$2');
// definitions
function escape_reg_exp(string) {
return string.replace(ESCAPE_REG, "\\$1");
}
}
function apply_reaction_data_to_reactions(reactions, data, styles, compare_style) {
/** Returns True if the scale has changed.
*/
if (data === null) {
for (var reaction_id in reactions) {
var reaction = reactions[reaction_id];
reaction.data = null;
reaction.data_string = '';
for (var segment_id in reaction.segments) {
var segment = reaction.segments[segment_id];
segment.data = null;
}
reaction.gene_string = null;
}
return false;
}
// apply the datasets to the reactions
for (var reaction_id in reactions) {
var reaction = reactions[reaction_id],
d = (reaction.bigg_id in data ? data[reaction.bigg_id] : null),
f = float_for_data(d, styles, compare_style),
r = reverse_flux_for_data(d),
s = text_for_data(d, f);
reaction.data = f;
reaction.data_string = s;
reaction.reverse_flux = r;
reaction.gene_string = null;
// apply to the segments
for (var segment_id in reaction.segments) {
var segment = reaction.segments[segment_id];
segment.data = reaction.data;
segment.reverse_flux = reaction.reverse_flux;
}
}
return true;
}
function apply_metabolite_data_to_nodes(nodes, data, styles, compare_style) {
/** Returns True if the scale has changed.
*/
if (data === null) {
for (var node_id in nodes) {
nodes[node_id].data = null;
nodes[node_id].data_string = '';
}
return false;
}
// grab the data
for (var node_id in nodes) {
var node = nodes[node_id],
d = (node.bigg_id in data ? data[node.bigg_id] : null),
f = float_for_data(d, styles, compare_style),
s = text_for_data(d, f);
node.data = f;
node.data_string = s;
}
return true;
}
function apply_gene_data_to_reactions(reactions, gene_data_obj, styles, identifiers_on_map,
compare_style, and_method_in_gene_reaction_rule) {
/** Returns true if data is present
Arguments
---------
reactions: The reactions to update.
gene_data_obj: The gene data object, with the following style:
{ reaction_id: { gene_id: value } }
styles: Gene styles array.
identifiers_on_map:
compare_style:
and_method_in_gene_reaction_rule:
*/
if (gene_data_obj === null) {
for (var reaction_id in reactions) {
var reaction = reactions[reaction_id];
reaction.data = null;
reaction.data_string = '';
reaction.reverse_flux = false;
for (var segment_id in reaction.segments) {
var segment = reaction.segments[segment_id];
segment.data = null;
}
reaction.gene_string = null;
}
return false;
}
// get the null val
var null_val = [null];
// make an array of nulls as the default
for (var reaction_id in gene_data_obj) {
for (var gene_id in gene_data_obj[reaction_id]) {
null_val = gene_data_obj[reaction_id][gene_id]
.map(function() { return null; });
break;
}
break;
}
// apply the datasets to the reactions
for (var reaction_id in reactions) {
var reaction = reactions[reaction_id],
rule = reaction.gene_reaction_rule;
// find the data
var d, gene_values,
r_data = gene_data_obj[reaction.bigg_id];
if (typeof r_data !== 'undefined') {
gene_values = r_data;
d = evaluate_gene_reaction_rule(rule, gene_values,
and_method_in_gene_reaction_rule);
} else {
gene_values = {};
d = null_val;
}
var f = float_for_data(d, styles, compare_style),
r = reverse_flux_for_data(d),
s = text_for_data(d, f);
reaction.data = f;
reaction.data_string = s;
reaction.reverse_flux = r;
// apply to the segments
for (var segment_id in reaction.segments) {
var segment = reaction.segments[segment_id];
segment.data = reaction.data;
segment.reverse_flux = reaction.reverse_flux;
}
// always update the gene string
reaction.gene_string = gene_string_for_data(rule,
gene_values,
reaction.genes,
styles,
identifiers_on_map,
compare_style);
}
return true;
}
function _parse_float_or_null(x) {
// strict number casting
var f = Number(x);
// check for null and '', which haven't been caught yet
return (isNaN(f) || parseFloat(x) != f) ? null : f;
}
});
define('CobraModel',['utils', 'data_styles'], function(utils, data_styles) {
/**
*/
var CobraModel = utils.make_class();
// class methods
CobraModel.from_exported_data = from_exported_data;
CobraModel.from_cobra_json = from_cobra_json;
CobraModel.build_reaction_string = build_reaction_string;
// instance methods
CobraModel.prototype = { init: init,
apply_reaction_data: apply_reaction_data,
apply_metabolite_data: apply_metabolite_data,
apply_gene_data: apply_gene_data,
model_for_export: model_for_export };
return CobraModel;
// class methods
function build_reaction_string(stoichiometries, is_reversible) {
/** Return a reaction string for the given stoichiometries.
Adapted from cobra.core.Reaction.build_reaction_string().
Arguments
---------
stoichiometries: An object with metabolites as keys and
stoichiometries as values.
is_reversible: Boolean. Whether the reaction is reversible.
*/
var format = function(number) {
if (number == 1)
return "";
return String(number) + " ";
};
var reactant_dict = {},
product_dict = {},
reactant_bits = [],
product_bits = [];
for (var the_metabolite in stoichiometries) {
var coefficient = stoichiometries[the_metabolite];
if (coefficient > 0)
product_bits.push(format(coefficient) + the_metabolite);
else
reactant_bits.push(format(Math.abs(coefficient)) + the_metabolite);
}
var reaction_string = reactant_bits.join(' + ');
if (is_reversible) {
reaction_string += ' ↔ ';
} else {
reaction_string += ' → ';
}
reaction_string += product_bits.join(' + ');
return reaction_string;
}
function from_exported_data(data) {
/** Use data generated by CobraModel.model_for_export() to make a new
CobraModel object.
*/
if (!(data.reactions && data.metabolites))
throw new Error('Bad model data.');
var model = new CobraModel();
model.reactions = data.reactions;
model.metabolites = data.metabolites;
return model;
}
function from_cobra_json(model_data) {
/** Use a JSON Cobra model exported by COBRApy to make a new CobraModel
object.
*/
// reactions and metabolites
if (!(model_data.reactions && model_data.metabolites))
throw new Error('Bad model data.');
// make a gene dictionary
var genes = {};
for (var i = 0, l = model_data.genes.length; i < l; i++) {
var r = model_data.genes[i],
the_id = r.id;
genes[the_id] = r;
}
var model = new CobraModel();
model.reactions = {};
for (var i = 0, l = model_data.reactions.length; i<l; i++) {
var r = model_data.reactions[i],
the_id = r.id,
reaction = utils.clone(r);
delete reaction.id;
reaction.bigg_id = the_id;
// add the appropriate genes
reaction.genes = [];
// set reversibility
reaction.reversibility = (reaction.lower_bound < 0 && reaction.upper_bound > 0);
if (reaction.upper_bound <= 0 && reaction.lower_bound < 0) {
// reverse stoichiometries
for (var met_id in reaction.metabolites) {
reaction.metabolites[met_id] = -reaction.metabolites[met_id];
}
}
delete reaction.lower_bound;
delete reaction.upper_bound;
if ('gene_reaction_rule' in reaction) {
var gene_ids = data_styles.genes_for_gene_reaction_rule(reaction.gene_reaction_rule);
gene_ids.forEach(function(gene_id) {
if (gene_id in genes) {
var gene = utils.clone(genes[gene_id]);
// rename id to bigg_id
gene.bigg_id = gene.id;
delete gene.id;
reaction.genes.push(gene);
} else {
console.warn('Could not find gene for gene_id ' + gene_id);
}
});
}
model.reactions[the_id] = reaction;
}
model.metabolites = {};
for (var i=0, l=model_data.metabolites.length; i<l; i++) {
var r = model_data.metabolites[i],
the_id = r.id,
met = utils.clone(r);
delete met.id;
met.bigg_id = the_id;
model.metabolites[the_id] = met;
}
return model;
}
// instance methods
function init() {
this.reactions = {};
this.metabolites = {};
this.cofactors = ['atp', 'adp', 'nad', 'nadh', 'nadp', 'nadph', 'gtp',
'gdp', 'h', 'coa'];
}
function apply_reaction_data(reaction_data, styles, compare_style) {
/** Apply data to model. This is only used to display options in
BuildInput.
apply_reaction_data overrides apply_gene_data.
*/
data_styles.apply_reaction_data_to_reactions(this.reactions, reaction_data,
styles, compare_style);
}
function apply_metabolite_data(metabolite_data, styles, compare_style) {
/** Apply data to model. This is only used to display options in
BuildInput.
*/
data_styles.apply_metabolite_data_to_nodes(this.metabolites, metabolite_data,
styles, compare_style);
}
function apply_gene_data(gene_data_obj, styles, identifiers_on_map,
compare_style, and_method_in_gene_reaction_rule) {
/** Apply data to model. This is only used to display options in
BuildInput.
apply_gene_data overrides apply_reaction_data.
*/
data_styles.apply_gene_data_to_reactions(this.reactions, gene_data_obj,
styles, identifiers_on_map,
compare_style,
and_method_in_gene_reaction_rule);
}
function model_for_export() {
/** Export a CobraModel object for reloading later.
This object is not for loading into COBRApy! Export to COBRApy is not
currently supported.
*/
return { reactions: this.reactions,
metabolites: this.metabolites };
}
});
define('BuildInput',['utils', 'PlacedDiv', 'lib/complete.ly', 'DirectionArrow', 'CobraModel'], function(utils, PlacedDiv, completely, DirectionArrow, CobraModel) {
/**
*/
var BuildInput = utils.make_class();
// instance methods
BuildInput.prototype = { init: init,
setup_map_callbacks: setup_map_callbacks,
setup_zoom_callbacks: setup_zoom_callbacks,
is_visible: is_visible,
toggle: toggle,
show_dropdown: show_dropdown,
hide_dropdown: hide_dropdown,
place_at_selected: place_at_selected,
place: place,
reload_at_selected: reload_at_selected,
reload: reload,
toggle_start_reaction_listener: toggle_start_reaction_listener,
hide_target: hide_target,
show_target: show_target };
return BuildInput;
// definitions
function init(selection, map, zoom_container, settings) {
// set up container
var new_sel = selection.append('div').attr('id', 'rxn-input');
this.placed_div = PlacedDiv(new_sel, map, {x: 240, y: 0});
this.placed_div.hide();
// set up complete.ly
var c = completely(new_sel.node(), { backgroundColor: '#eee' });
d3.select(c.input);
this.completely = c;
// close button
new_sel.append('button').attr('class', "button input-close-button")
.text("×")
.on('mousedown', function() { this.hide_dropdown(); }.bind(this));
// map
this.map = map;
// set up the reaction direction arrow
var default_angle = 90; // degrees
this.direction_arrow = new DirectionArrow(map.sel);
this.direction_arrow.set_rotation(default_angle);
this.setup_map_callbacks(map);
// zoom container
this.zoom_container = zoom_container;
this.setup_zoom_callbacks(zoom_container);
// settings
this.settings = settings;
// toggle off
this.toggle(false);
this.target_coords = null;
}
function setup_map_callbacks(map) {
// input
map.callback_manager.set('select_metabolite_with_id.input', function(selected_node, coords) {
if (this.is_active) this.reload(selected_node, coords, false);
this.hide_target();
}.bind(this));
map.callback_manager.set('select_selectable.input', function(count, selected_node, coords) {
this.hide_target();
if (count == 1 && this.is_active && coords) {
this.reload(selected_node, coords, false);
} else {
this.toggle(false);
}
}.bind(this));
map.callback_manager.set('deselect_nodes', function() {
this.direction_arrow.hide();
this.hide_dropdown();
}.bind(this));
// svg export
map.callback_manager.set('before_svg_export', function() {
this.direction_arrow.hide();
this.hide_target();
}.bind(this));
}
function setup_zoom_callbacks(zoom_container) {
zoom_container.callback_manager.set('zoom.input', function() {
if (this.is_active) {
this.place_at_selected();
}
}.bind(this));
}
function is_visible() {
return this.placed_div.is_visible();
}
function toggle(on_off) {
if (on_off===undefined) this.is_active = !this.is_active;
else this.is_active = on_off;
if (this.is_active) {
this.toggle_start_reaction_listener(true);
if (this.target_coords !== null)
this.show_dropdown(this.target_coords);
else this.reload_at_selected();
this.map.set_status('Click on the canvas or an existing metabolite');
this.direction_arrow.show();
// escape key
this.escape = this.map.key_manager
.add_escape_listener(function() {
this.hide_dropdown();
}.bind(this), 'build_input');
} else {
this.toggle_start_reaction_listener(false);
this.placed_div.hide();
this.completely.input.blur();
this.completely.hideDropDown();
this.map.set_status(null);
this.direction_arrow.hide();
if (this.escape) this.escape.clear();
this.escape = null;
}
}
function show_dropdown(coords) {
this.placed_div.place(coords);
this.completely.input.blur();
this.completely.repaint();
this.completely.setText("");
this.completely.input.focus();
}
function hide_dropdown() {
this.placed_div.hide();
this.completely.hideDropDown();
}
function place_at_selected() {
/** Place autocomplete box at the first selected node.
*/
// get the selected node
this.map.deselect_text_labels();
var selected_node = this.map.select_single_node();
if (selected_node==null) return;
var coords = { x: selected_node.x, y: selected_node.y };
this.place(coords);
}
function place(coords) {
this.placed_div.place(coords);
this.direction_arrow.set_location(coords);
this.direction_arrow.show();
}
function reload_at_selected() {
/** Reload data for autocomplete box and redraw box at the first
selected node.
*/
// get the selected node
this.map.deselect_text_labels();
var selected_node = this.map.select_single_node();
if (selected_node==null) return false;
var coords = { x: selected_node.x, y: selected_node.y };
// reload the reaction input
this.reload(selected_node, coords, false);
return true;
}
function reload(selected_node, coords, starting_from_scratch) {
/** Reload data for autocomplete box and redraw box at the new
coordinates.
*/
// try finding the selected node
if (!starting_from_scratch && !selected_node) {
console.error('No selected node, and not starting from scratch');
return;
}
this.place(coords);
// blur
this.completely.input.blur();
this.completely.repaint(); // put in place()?
if (this.map.cobra_model===null) {
this.completely.setText('Cannot add: No model.');
return;
}
// settings
var show_names = this.settings.get_option('identifiers_on_map') == 'name',
allow_duplicates = this.settings.get_option('allow_building_duplicate_reactions');
// Find selected
var options = [],
cobra_reactions = this.map.cobra_model.reactions,
cobra_metabolites = this.map.cobra_model.metabolites,
reactions = this.map.reactions,
has_data_on_reactions = this.map.has_data_on_reactions,
reaction_data = this.map.reaction_data,
reaction_data_styles = this.map.reaction_data_styles,
selected_m_name = (selected_node ? (show_names ? selected_node.name : selected_node.bigg_id) : ''),
bold_mets_in_str = function(str, mets) {
return str.replace(new RegExp('(^| )(' + mets.join('|') + ')($| )', 'g'),
'$1<b>$2</b>$3');
};
// for reactions
var reaction_suggestions = {};
for (var bigg_id in cobra_reactions) {
var reaction = cobra_reactions[bigg_id],
reaction_name = reaction.name,
show_r_name = (show_names ? reaction_name : bigg_id);
// ignore drawn reactions
if ((!allow_duplicates) && already_drawn(bigg_id, reactions))
continue;
// check segments for match to selected metabolite
for (var met_bigg_id in reaction.metabolites) {
// if starting with a selected metabolite, check for that id
if (starting_from_scratch || met_bigg_id == selected_node.bigg_id) {
// don't add suggestions twice
if (bigg_id in reaction_suggestions) continue;
var met_name = cobra_metabolites[met_bigg_id].name;
if (has_data_on_reactions) {
options.push({ reaction_data: reaction.data,
html: ('<b>' + show_r_name + '</b>' +
': ' +
reaction.data_string),
matches: [show_r_name],
id: bigg_id });
reaction_suggestions[bigg_id] = true;
} else {
// get the metabolite names or IDs
var mets = {},
show_met_names = [];
if (show_names) {
for (var met_id in reaction.metabolites) {
var name = cobra_metabolites[met_id].name;
mets[name] = reaction.metabolites[met_id];
show_met_names.push(name);
}
} else {
mets = utils.clone(reaction.metabolites);
for (var met_id in reaction.metabolites) {
show_met_names.push(met_id);
}
}
var key = show_names ? 'name' : 'bigg_id',
show_gene_names = reaction.genes.map(function(g_obj) {
return g_obj[key];
});
// get the reaction string
var reaction_string = CobraModel.build_reaction_string(mets,
reaction.reversibility,
reaction.lower_bound,
reaction.upper_bound);
options.push({ html: ('<b>' + show_r_name + '</b>' +
'\t' +
bold_mets_in_str(reaction_string, [selected_m_name])),
matches: [show_r_name].concat(show_met_names).concat(show_gene_names),
id: bigg_id });
reaction_suggestions[bigg_id] = true;
}
}
}
}
// Generate the array of reactions to suggest and sort it
var sort_fn;
if (has_data_on_reactions) {
sort_fn = function(x, y) {
return Math.abs(y.reaction_data) - Math.abs(x.reaction_data);
};
} else {
sort_fn = function(x, y) {
return (x.html.toLowerCase() < y.html.toLowerCase() ? -1 : 1);
};
}
options = options.sort(sort_fn);
// set up the box with data, searching for first num results
var num = 20,
complete = this.completely;
complete.options = options;
// TODO test this behavior
// if (strings_to_display.length==1) complete.setText(strings_to_display[0]);
// else complete.setText("");
complete.setText("");
var direction_arrow = this.direction_arrow,
check_and_build = function(id) {
if (id !== null) {
// make sure the selected node exists, in case changes were made in the meantime
if (starting_from_scratch) {
this.map.new_reaction_from_scratch(id,
coords,
direction_arrow.get_rotation());
} else {
if (!(selected_node.node_id in this.map.nodes)) {
console.error('Selected node no longer exists');
this.hide_dropdown();
return;
}
this.map.new_reaction_for_metabolite(id,
selected_node.node_id,
direction_arrow.get_rotation());
}
}
}.bind(this);
complete.onEnter = function(id) {
this.setText("");
this.onChange("");
check_and_build(id);
};
complete.repaint();
this.completely.input.focus();
//definitions
function already_drawn(bigg_id, reactions) {
for (var drawn_id in reactions) {
if (reactions[drawn_id].bigg_id==bigg_id)
return true;
}
return false;
};
}
function toggle_start_reaction_listener(on_off) {
/** Toggle listening for a click to place a new reaction on the canvas.
*/
if (on_off===undefined)
this.start_reaction_listener = !this.start_reaction_listener;
else if (this.start_reaction_listener==on_off)
return;
else
this.start_reaction_listener = on_off;
if (this.start_reaction_listener) {
this.map.sel.on('click.start_reaction', function(node) {
// TODO fix this hack
if (this.direction_arrow.dragging) return;
// reload the reaction input
var coords = { x: d3.mouse(node)[0],
y: d3.mouse(node)[1] };
// unselect metabolites
this.map.deselect_nodes();
this.map.deselect_text_labels();
// reload the reaction input
this.reload(null, coords, true);
// generate the target symbol
this.show_target(this.map, coords);
}.bind(this, this.map.sel.node()));
this.map.sel.classed('start-reaction-cursor', true);
} else {
this.map.sel.on('click.start_reaction', null);
this.map.sel.classed('start-reaction-cursor', false);
this.hide_target();
}
}
function hide_target() {
if (this.target_coords)
this.map.sel.selectAll('.start-reaction-target').remove();
this.target_coords = null;
}
function show_target(map, coords) {
var s = map.sel.selectAll('.start-reaction-target').data([12, 5]);
s.enter().append('circle')
.classed('start-reaction-target', true)
.attr('r', function(d) { return d; })
.style('stroke-width', 4);
s.style('visibility', 'visible')
.attr('transform', 'translate('+coords.x+','+coords.y+')');
this.target_coords = coords;
}
});
define('CallbackManager',["utils"], function(utils) {
/** CallbackManager()
*/
var CallbackManager = utils.make_class();
CallbackManager.prototype = { init: init,
set: set,
remove: remove,
run: run };
return CallbackManager;
function init() {
}
function set(name, fn) {
/** As in d3 callbacks, you can namespace your callbacks after a period:
select_metabolite.direction_arrow
select_metabolite.input
Both are called by select_metabolite
*/
if (this.callbacks===undefined) this.callbacks = {};
if (this.callbacks[name]===undefined) this.callbacks[name] = [];
this.callbacks[name].push(fn);
return this;
}
function remove(name) {
/** Remove a callback by name
*/
if (this.callbacks===undefined || Object.keys(this.callbacks).length==0) {
console.warn('No callbacks to remove');
}
delete this.callbacks[name];
return this;
}
function run(name, this_arg) {
/** Run all callbacks that match the portion of name before the period ('.').
Arguments
---------
name: The callback name, which can include a tag after a '.' to
specificy a particular callback.
this_arg: (Optional, Default: null) The object assigned to `this` in
the callback.
*/
if (this.callbacks===undefined) return this;
if (this_arg===undefined) this_arg = null;
// pass all but the first (name) argument to the callback
var pass_args = Array.prototype.slice.call(arguments, 2);
// look for matching callback names
for (var a_name in this.callbacks) {
var split_name = a_name.split('.')[0];
if (split_name==name) {
this.callbacks[a_name].forEach(function(fn) {
fn.apply(this_arg, pass_args);
});
}
}
return this;
}
});
define('ZoomContainer',["utils", "CallbackManager"], function(utils, CallbackManager) {
/** ZoomContainer
The zoom behavior is based on this SO question:
http://stackoverflow.com/questions/18788188/how-to-temporarily-disable-the-zooming-in-d3-js
*/
var ZoomContainer = utils.make_class();
ZoomContainer.prototype = { init: init,
update_scroll_behavior: update_scroll_behavior,
toggle_zoom: toggle_zoom,
go_to: go_to,
zoom_by: zoom_by,
zoom_in: zoom_in,
zoom_out: zoom_out,
get_size: get_size,
translate_off_screen: translate_off_screen,
reset: reset };
return ZoomContainer;
// definitions
function init(selection, size_container, scroll_behavior) {
/** Make a container that will manage panning and zooming.
selection: A d3 selection of an 'svg' or 'g' node to put the zoom
container in.
size_container: A d3 selection of a 'div' node that has defined width
and height.
*/
this.zoom_on = true;
this.initial_zoom = 1.0;
this.window_translate = {x: 0, y: 0};
this.window_scale = 1.0;
// set up the callbacks
this.callback_manager = new CallbackManager();
// save the size_container
this.size_container = size_container;
// set up the container
selection.select("#zoom-container").remove();
var container = selection.append("g")
.attr("id", "zoom-container");
this.container = container;
this.zoomed_sel = container.append("g");
// update the scroll behavior
this.update_scroll_behavior(scroll_behavior);
// initialize vars
this.saved_scale = null;
this.saved_translate = null;
}
function update_scroll_behavior(scroll_behavior) {
// the zoom function and behavior
var zoom = function(zoom_container, event) {
if (zoom_container.zoom_on) {
zoom_container.zoomed_sel.attr("transform", "translate(" + event.translate + ")" +
"scale(" + event.scale + ")");
zoom_container.window_translate = {'x': event.translate[0],
'y': event.translate[1]};
zoom_container.window_scale = event.scale;
zoom_container.callback_manager.run('zoom');
}
};
// clear all behaviors
this.container.on("mousewheel.zoom", null)
.on("DOMMouseScroll.zoom", null) // disables older versions of Firefox
.on("wheel.zoom", null) // disables newer versions of Firefox
.on('dblclick.zoom', null)
.on('mousewheel.escher', wheel_fn)
.on('DOMMouseScroll.escher', wheel_fn)
.on('wheel.escher', wheel_fn);
// new zoom
this.zoom_behavior = d3.behavior.zoom()
.on("zoom", function() {
zoom(this, d3.event);
}.bind(this));
this.container.call(this.zoom_behavior);
// options
if (scroll_behavior=='none' || scroll_behavior=='pan') {
this.container.on("mousewheel.zoom", null)
.on("DOMMouseScroll.zoom", null) // disables older versions of Firefox
.on("wheel.zoom", null) // disables newer versions of Firefox
.on('dblclick.zoom', null);
}
if (scroll_behavior == 'pan') {
// Add the wheel listener
var wheel_fn = function() {
var ev = d3.event,
sensitivity = 0.5;
// stop scroll in parent elements
ev.stopPropagation();
ev.preventDefault();
ev.returnValue = false;
// change the location
this.go_to(this.window_scale,
{ x: this.window_translate.x -
(ev.wheelDeltaX!==undefined ? -ev.wheelDeltaX/1.5 : ev.deltaX) * sensitivity,
y: this.window_translate.y -
(ev.wheelDeltaY!==undefined ? -ev.wheelDeltaY/1.5 : ev.deltaY) * sensitivity },
false);
}.bind(this);
this.container.on('mousewheel.escher', wheel_fn);
this.container.on('DOMMouseScroll.escher', wheel_fn);
this.container.on('wheel.escher', wheel_fn);
}
}
function toggle_zoom(on_off) {
/** Toggle the zoom state, and remember zoom when the behavior is off.
*/
if (on_off===undefined) {
this.zoom_on = !this.zoom_on;
} else {
this.zoom_on = on_off;
}
if (this.zoom_on) {
if (this.saved_scale !== null){
this.zoom_behavior.scale(this.saved_scale);
this.saved_scale = null;
}
if (this.saved_translate !== null){
this.zoom_behavior.translate(this.saved_translate);
this.saved_translate = null;
}
// turn on the hand
this.zoomed_sel
.classed('cursor-grab', true).classed('cursor-grabbing', false);
this.zoomed_sel
.on('mousedown.cursor', function(sel) {
sel.classed('cursor-grab', false).classed('cursor-grabbing', true);
}.bind(null, this.zoomed_sel))
.on('mouseup.cursor', function(sel) {
sel.classed('cursor-grab', true).classed('cursor-grabbing', false);
}.bind(null, this.zoomed_sel));
} else {
if (this.saved_scale === null){
this.saved_scale = utils.clone(this.zoom_behavior.scale());
}
if (this.saved_translate === null){
this.saved_translate = utils.clone(this.zoom_behavior.translate());
}
// turn off the hand
this.zoomed_sel.style('cursor', null)
.classed('cursor-grab', false)
.classed('cursor-grabbing', false);
this.zoomed_sel.on('mousedown.cursor', null);
this.zoomed_sel.on('mouseup.cursor', null);
}
}
// functions to scale and translate
function go_to(scale, translate, show_transition) {
utils.check_undefined(arguments, ['scale', 'translate']);
if (show_transition===undefined) show_transition = true;
if (!scale) throw new Error('Bad scale value');
if (!translate || !('x' in translate) || !('y' in translate) ||
isNaN(translate.x) || isNaN(translate.y))
return console.error('Bad translate value');
this.zoom_behavior.scale(scale);
this.window_scale = scale;
if (this.saved_scale !== null) this.saved_scale = scale;
var translate_array = [translate.x, translate.y];
this.zoom_behavior.translate(translate_array);
this.window_translate = translate;
if (this.saved_translate !== null) this.saved_translate = translate_array;
var move_this = (show_transition ?
this.zoomed_sel.transition() :
this.zoomed_sel);
move_this.attr('transform',
'translate('+this.window_translate.x+','+this.window_translate.y+')'+
'scale('+this.window_scale+')');
this.callback_manager.run('go_to');
return null;
}
function zoom_by(amount) {
var size = this.get_size(),
shift = { x: size.width/2 - ((size.width/2 - this.window_translate.x) * amount +
this.window_translate.x),
y: size.height/2 - ((size.height/2 - this.window_translate.y) * amount +
this.window_translate.y) };
this.go_to(this.window_scale*amount,
utils.c_plus_c(this.window_translate, shift),
true);
}
function zoom_in() {
this.zoom_by(1.5);
}
function zoom_out() {
this.zoom_by(0.667);
}
function get_size() {
return { width: parseInt(this.size_container.style('width'), 10),
height: parseInt(this.size_container.style('height'), 10) };
}
function translate_off_screen(coords) {
// shift window if new reaction will draw off the screen
// TODO BUG not accounting for scale correctly
var margin = 120, // pixels
size = this.get_size(),
current = {'x': {'min': - this.window_translate.x / this.window_scale +
margin / this.window_scale,
'max': - this.window_translate.x / this.window_scale +
(size.width-margin) / this.window_scale },
'y': {'min': - this.window_translate.y / this.window_scale +
margin / this.window_scale,
'max': - this.window_translate.y / this.window_scale +
(size.height-margin) / this.window_scale } };
if (coords.x < current.x.min) {
this.window_translate.x = this.window_translate.x -
(coords.x - current.x.min) * this.window_scale;
this.go_to(this.window_scale, this.window_translate);
} else if (coords.x > current.x.max) {
this.window_translate.x = this.window_translate.x -
(coords.x - current.x.max) * this.window_scale;
this.go_to(this.window_scale, this.window_translate);
}
if (coords.y < current.y.min) {
this.window_translate.y = this.window_translate.y -
(coords.y - current.y.min) * this.window_scale;
this.go_to(this.window_scale, this.window_translate);
} else if (coords.y > current.y.max) {
this.window_translate.y = this.window_translate.y -
(coords.y - current.y.max) * this.window_scale;
this.go_to(this.window_scale, this.window_translate);
}
}
function reset() {
this.go_to(1.0, {x: 0.0, y: 0.0});
}
});
define('Draw',['utils', 'data_styles', 'CallbackManager'], function(utils, data_styles, CallbackManager) {
/** Manages creating, updating, and removing objects during d3 data binding.
Arguments
---------
behavior: An escher.Behavior object.
settings: An escher.Settings object.
Callbacks
---------
draw.callback_manager.run('create_membrane', draw, enter_selection);
draw.callback_manager.run('update_membrane', draw, update_selection);
draw.callback_manager.run('create_reaction', draw, enter_selection);
draw.callback_manager.run('update_reaction', draw, update_selection);
draw.callback_manager.run('create_reaction_label', draw, enter_selection);
draw.callback_manager.run('update_reaction_label', draw, update_selection);
draw.callback_manager.run('create_segment', draw, enter_selection);
draw.callback_manager.run('update_segment', draw, update_selection);
draw.callback_manager.run('create_bezier', draw, enter_selection);
draw.callback_manager.run('update_bezier', draw, update_selection);
draw.callback_manager.run('create_node', draw, enter_selection);
draw.callback_manager.run('update_node', draw, update_selection);
draw.callback_manager.run('create_text_label', draw, enter_selection);
draw.callback_manager.run('update_text_label', draw, update_selection);
*/
var Draw = utils.make_class();
// instance methods
Draw.prototype = { init: init,
create_reaction: create_reaction,
update_reaction: update_reaction,
create_bezier: create_bezier,
update_bezier: update_bezier,
create_node: create_node,
update_node: update_node,
create_text_label: create_text_label,
update_text_label: update_text_label,
create_membrane: create_membrane,
update_membrane: update_membrane,
create_reaction_label: create_reaction_label,
update_reaction_label: update_reaction_label,
create_segment: create_segment,
update_segment: update_segment
};
return Draw;
// definitions
function init(behavior, settings) {
this.behavior = behavior;
this.settings = settings;
this.callback_manager = new CallbackManager();
}
function create_membrane(enter_selection) {
enter_selection.append('rect')
.attr('class', 'membrane');
this.callback_manager.run('create_membrane', this, enter_selection);
}
function update_membrane(update_selection) {
update_selection
.attr('width', function(d){ return d.width; })
.attr('height', function(d){ return d.height; })
.attr('transform', function(d){return 'translate('+d.x+','+d.y+')';})
.style('stroke-width', function(d) { return 10; })
.attr('rx', function(d){ return 20; })
.attr('ry', function(d){ return 20; });
this.callback_manager.run('update_membrane', this, update_selection);
}
function create_reaction(enter_selection) {
// attributes for new reaction group
enter_selection.append('g')
.attr('id', function(d) { return 'r'+d.reaction_id; })
.attr('class', 'reaction')
.call(this.create_reaction_label.bind(this));
this.callback_manager.run('create_reaction', this, enter_selection);
return;
}
function update_reaction(update_selection, scale, cobra_model, drawn_nodes,
defs, has_data_on_reactions) {
// update reaction label
update_selection.select('.reaction-label-group')
.call(function(sel) {
return this.update_reaction_label(sel, has_data_on_reactions);
}.bind(this));
// draw segments
utils.draw_a_nested_object(update_selection, '.segment-group', 'segments', 'segment_id',
this.create_segment.bind(this),
function(sel) {
return this.update_segment(sel, scale, cobra_model,
drawn_nodes, defs,
has_data_on_reactions);
}.bind(this),
function(sel) {
sel.remove();
});
this.callback_manager.run('update_reaction', this, update_selection);
}
function create_reaction_label(enter_selection) {
/** Draw reaction label for selection.
*/
var group = enter_selection.append('g')
.attr('class', 'reaction-label-group');
group.append('text')
.attr('class', 'reaction-label label');
group.append('g')
.attr('class', 'gene-label-group');
this.callback_manager.run('create_reaction_label', this, enter_selection);
}
function update_reaction_label(update_selection, has_data_on_reactions) {
var decimal_format = d3.format('.4g'),
identifiers_on_map = this.settings.get_option('identifiers_on_map'),
reaction_data_styles = this.settings.get_option('reaction_styles'),
show_gene_reaction_rules = this.settings.get_option('show_gene_reaction_rules'),
hide_all_labels = this.settings.get_option('hide_all_labels'),
gene_font_size = this.settings.get_option('gene_font_size'),
label_mousedown_fn = this.behavior.label_mousedown,
label_mouseover_fn = this.behavior.label_mouseover,
label_mouseout_fn = this.behavior.label_mouseout;
update_selection.attr('transform', function(d) {
return 'translate('+d.label_x+','+d.label_y+')';
})
.call(this.behavior.turn_off_drag)
.call(this.behavior.reaction_label_drag);
var s = update_selection.select('.reaction-label')
.attr('visibility', hide_all_labels ? 'hidden' : 'visible');
if (!hide_all_labels) {
s.text(function(d) {
var t = d[identifiers_on_map];
if (has_data_on_reactions && reaction_data_styles.indexOf('text') != -1)
t += ' ' + d.data_string;
return t;
})
.on('mousedown', label_mousedown_fn)
.on('mouseover', label_mouseover_fn)
.on('mouseout', label_mouseout_fn);
}
// gene label
var gene_g = update_selection.select('.gene-label-group')
.selectAll('text')
.data(function(d) {
var show_gene_string = ('gene_string' in d &&
d.gene_string !== null &&
show_gene_reaction_rules &&
(!hide_all_labels) &&
reaction_data_styles.indexOf('text') !== -1),
show_gene_reaction_rule = ('gene_reaction_rule' in d &&
d.gene_reaction_rule !== null &&
show_gene_reaction_rules &&
(!hide_all_labels) );
if (show_gene_string) {
return d.gene_string.split('\n');
} else if (show_gene_reaction_rule) {
var rule = data_styles.gene_string_for_data(d.gene_reaction_rule, null,
d.genes, null, identifiers_on_map,
null);
return rule.split('\n');
} else {
return [];
}
});
gene_g.enter()
.append('text')
.attr('class', 'gene-label')
.style('font-size', gene_font_size + 'px');
gene_g.attr('transform', function(d, i) {
return 'translate(0, ' + (gene_font_size * 1.5 * (i + 1)) + ')';
})
.text(function(d) { return d; });
gene_g.exit()
.remove();
this.callback_manager.run('update_reaction_label', this, update_selection);
}
function create_segment(enter_selection) {
// create segments
var g = enter_selection
.append('g')
.attr('class', 'segment-group')
.attr('id', function(d) { return 's'+d.segment_id; });
// create reaction arrow
g.append('path')
.attr('class', 'segment');
g.append('g')
.attr('class', 'arrowheads');
g.append('g')
.attr('class', 'stoichiometry-labels');
this.callback_manager.run('create_segment', this, enter_selection);
}
function update_segment(update_selection, scale, cobra_model,
drawn_nodes, defs, has_data_on_reactions) {
var reaction_data_styles = this.settings.get_option('reaction_styles'),
should_size = (has_data_on_reactions && reaction_data_styles.indexOf('size') != -1),
should_color = (has_data_on_reactions && reaction_data_styles.indexOf('color') != -1),
no_data_size = this.settings.get_option('reaction_no_data_size'),
no_data_color = this.settings.get_option('reaction_no_data_color');
// update segment attributes
var highlight_missing = this.settings.get_option('highlight_missing'),
hide_secondary_metabolites = this.settings.get_option('hide_secondary_metabolites'),
primary_r = this.settings.get_option('primary_metabolite_radius'),
secondary_r = this.settings.get_option('secondary_metabolite_radius'),
get_arrow_size = function(data, should_size) {
var width = 20,
height = 13;
if (should_size) {
height = (data === null ? no_data_size : scale.reaction_size(data));
// check for nan
if (isNaN(height))
height = no_data_size;
width = height * 2;
}
return { width: width, height: height };
},
get_disp = function(arrow_size, reversibility, coefficient, node_is_primary) {
var arrow_height = ((reversibility || coefficient > 0) ?
arrow_size.height :
0),
r = node_is_primary ? primary_r : secondary_r;
return r + arrow_height + 10;
};
// update arrows
update_selection
.selectAll('.segment')
.datum(function() {
return this.parentNode.__data__;
})
.style('visibility', function(d) {
var start = drawn_nodes[d.from_node_id],
end = drawn_nodes[d.to_node_id];
if (hide_secondary_metabolites &&
((end['node_type']=='metabolite' && !end.node_is_primary) ||
(start['node_type']=='metabolite' && !start.node_is_primary)))
return 'hidden';
return null;
})
.attr('d', function(d) {
if (d.from_node_id === null || d.to_node_id === null)
return null;
var start = drawn_nodes[d.from_node_id],
end = drawn_nodes[d.to_node_id],
b1 = d.b1,
b2 = d.b2;
// if metabolite, then displace the arrow
if (start['node_type'] == 'metabolite') {
var arrow_size = get_arrow_size(d.data, should_size),
disp = get_disp(arrow_size, d.reversibility,
d.from_node_coefficient,
start.node_is_primary);
var direction = (b1 === null) ? end : b1;
start = displaced_coords(disp, start, direction, 'start');
}
if (end['node_type'] == 'metabolite') {
var arrow_size = get_arrow_size(d.data, should_size),
disp = get_disp(arrow_size, d.reversibility,
d.to_node_coefficient,
end.node_is_primary);
var direction = (b2 === null) ? start : b2;
end = displaced_coords(disp, direction, end, 'end');
}
var curve = ('M' + start.x + ',' + start.y + ' ');
if (b1 !== null && b2 !== null) {
curve += ('C' + b1.x + ',' + b1.y + ' ' +
b2.x + ',' + b2.y + ' ');
}
curve += (end.x + ',' + end.y);
return curve;
})
.style('stroke', function(d) {
var reaction_id = this.parentNode.parentNode.__data__.bigg_id,
show_missing = (highlight_missing &&
cobra_model !== null &&
!(reaction_id in cobra_model.reactions));
if (show_missing) {
return 'red';
}
if (should_color) {
var f = d.data;
return f === null ? no_data_color : scale.reaction_color(f);
}
return null;
})
.style('stroke-width', function(d) {
if (should_size) {
var f = d.data;
return f === null ? no_data_size : scale.reaction_size(f);
} else {
return null;
}
});
// new arrowheads
var arrowheads = update_selection.select('.arrowheads')
.selectAll('.arrowhead')
.data(function (d) {
var arrowheads = [],
start = drawn_nodes[d.from_node_id],
b1 = d.b1,
end = drawn_nodes[d.to_node_id],
b2 = d.b2;
// hide_secondary_metabolites option
if (hide_secondary_metabolites &&
((end['node_type']=='metabolite' && !end.node_is_primary) ||
(start['node_type']=='metabolite' && !start.node_is_primary)))
return arrowheads;
if (start.node_type == 'metabolite' && (d.reversibility || d.from_node_coefficient > 0)) {
var arrow_size = get_arrow_size(d.data, should_size),
disp = get_disp(arrow_size, d.reversibility,
d.from_node_coefficient,
start.node_is_primary),
direction = (b1 === null) ? end : b1,
rotation = utils.to_degrees(utils.get_angle([start, direction])) + 90,
loc = displaced_coords(disp, start, direction, 'start');
arrowheads.push({ data: d.data,
x: loc.x,
y: loc.y,
size: arrow_size,
rotation: rotation,
show_arrowhead_flux: (((d.from_node_coefficient < 0)==(d.reverse_flux))
|| d.data==0)
});
}
if (end.node_type == 'metabolite' && (d.reversibility || d.to_node_coefficient > 0)) {
var arrow_size = get_arrow_size(d.data, should_size),
disp = get_disp(arrow_size, d.reversibility,
d.to_node_coefficient,
end.node_is_primary),
direction = (b2 === null) ? start : b2,
rotation = utils.to_degrees(utils.get_angle([end, direction])) + 90,
loc = displaced_coords(disp, direction, end, 'end');
arrowheads.push({ data: d.data,
x: loc.x,
y: loc.y,
size: arrow_size,
rotation: rotation,
show_arrowhead_flux: (((d.to_node_coefficient < 0)==(d.reverse_flux))
|| d.data==0)
});
}
return arrowheads;
});
arrowheads.enter().append('path')
.classed('arrowhead', true);
// update arrowheads
arrowheads.attr('d', function(d) {
return ('M' + [-d.size.width / 2, 0] +
' L' + [0, d.size.height] +
' L' + [d.size.width / 2, 0] + ' Z');
}).attr('transform', function(d) {
return 'translate(' + d.x + ',' + d.y + ')rotate(' + d.rotation + ')';
}).style('fill', function(d) {
if (should_color) {
if (d.show_arrowhead_flux) {
// show the flux
var f = d.data;
return f===null ? no_data_color : scale.reaction_color(f);
} else {
// if the arrowhead is not filled because it is reversed
return '#FFFFFF';
}
}
// default fill color
return null;
}).style('stroke', function(d) {
if (should_color) {
// show the flux color in the stroke whether or not the fill is present
var f = d.data;
return f===null ? no_data_color : scale.reaction_color(f);
}
// default stroke color
return null;
});
// remove
arrowheads.exit().remove();
// new stoichiometry labels
var stoichiometry_labels = update_selection.select('.stoichiometry-labels')
.selectAll('.stoichiometry-label')
.data(function (d) {
var labels = [],
start = drawn_nodes[d.from_node_id],
b1 = d.b1,
end = drawn_nodes[d.to_node_id],
b2 = d.b2,
disp_factor = 1.5;
// hide_secondary_metabolites option
if (hide_secondary_metabolites &&
((end['node_type']=='metabolite' && !end.node_is_primary) ||
(start['node_type']=='metabolite' && !start.node_is_primary)))
return labels;
if (start.node_type=='metabolite' && (Math.abs(d.from_node_coefficient) != 1)) {
var arrow_size = get_arrow_size(d.data, should_size),
disp = disp_factor * get_disp(arrow_size, false, 0, end.node_is_primary),
direction = (b1 === null) ? end : b1;
direction = utils.c_plus_c(direction, utils.rotate_coords(direction, 0.5, start));
var loc = displaced_coords(disp, start, direction, 'start');
loc = utils.c_plus_c(loc, {x:0, y:7});
labels.push({ coefficient: Math.abs(d.from_node_coefficient),
x: loc.x,
y: loc.y,
data: d.data });
}
if (end.node_type=='metabolite' && (Math.abs(d.to_node_coefficient) != 1)) {
var arrow_size = get_arrow_size(d.data, should_size),
disp = disp_factor * get_disp(arrow_size, false, 0, end.node_is_primary),
direction = (b2 === null) ? start : b2;
direction = utils.c_plus_c(direction, utils.rotate_coords(direction, 0.5, end));
var loc = displaced_coords(disp, direction, end, 'end');
loc = utils.c_plus_c(loc, {x:0, y:7});
labels.push({ coefficient: Math.abs(d.to_node_coefficient),
x: loc.x,
y: loc.y,
data: d.data });
}
return labels;
});
// add labels
stoichiometry_labels.enter()
.append('text')
.attr('class', 'stoichiometry-label')
.attr('text-anchor', 'middle');
// update stoichiometry_labels
stoichiometry_labels
.attr('transform', function(d) {
return 'translate(' + d.x + ',' + d.y + ')';
})
.text(function(d) {
return d.coefficient;
})
.style('fill', function (d) {
if (should_color) {
// show the flux color
var f = d.data;
return f === null ? no_data_color : scale.reaction_color(f);
}
// default segment color
return null;
});
// remove
stoichiometry_labels.exit().remove();
this.callback_manager.run('update_segment', this, update_selection);
}
function create_bezier(enter_selection) {
var g = enter_selection.append('g')
.attr('id', function(d) { return d.bezier_id; })
.attr('class', function(d) { return 'bezier'; });
g.append('path')
.attr('class', 'connect-line');
g.append('circle')
.attr('class', function(d) { return 'bezier-circle '+d.bezier; })
.style('stroke-width', String(1)+'px')
.attr('r', String(7)+'px');
this.callback_manager.run('create_bezier', this, enter_selection);
}
function update_bezier(update_selection, show_beziers, drag_behavior,
mouseover, mouseout, drawn_nodes, drawn_reactions) {
var hide_secondary_metabolites = this.settings.get_option('hide_secondary_metabolites');
if (!show_beziers) {
update_selection.attr('visibility', 'hidden');
return;
} else {
update_selection.attr('visibility', 'visible');
}
// hide secondary
update_selection
.style('visibility', function(d) {
var seg_data = drawn_reactions[d.reaction_id].segments[d.segment_id],
start = drawn_nodes[seg_data.from_node_id],
end = drawn_nodes[seg_data.to_node_id];
if (hide_secondary_metabolites &&
((end['node_type']=='metabolite' && !end.node_is_primary) ||
(start['node_type']=='metabolite' && !start.node_is_primary)))
return 'hidden';
return null;
});
// draw bezier points
update_selection.select('.bezier-circle')
.call(this.behavior.turn_off_drag)
.call(drag_behavior)
.on('mouseover', mouseover)
.on('mouseout', mouseout)
.attr('transform', function(d) {
if (d.x==null || d.y==null) return '';
return 'translate('+d.x+','+d.y+')';
});
// update bezier line
update_selection
.select('.connect-line')
.attr('d', function(d) {
var node,
segment_d = drawn_reactions[d.reaction_id].segments[d.segment_id];
node = (d.bezier=='b1' ?
drawn_nodes[segment_d.from_node_id] :
drawn_nodes[segment_d.to_node_id]);
if (d.x==null || d.y==null || node.x==null || node.y==null)
return '';
return 'M'+d.x+', '+d.y+' '+(node.x)+','+(node.y);
});
this.callback_manager.run('update_bezier', this, update_selection);
}
function create_node(enter_selection, drawn_nodes, drawn_reactions) {
// create nodes
var g = enter_selection
.append('g')
.attr('class', 'node')
.attr('id', function(d) { return 'n'+d.node_id; });
// create metabolite circle and label
g.append('circle')
.attr('class', function(d) {
var c = 'node-circle';
if (d.node_type!==null)
c += (' ' + d.node_type + '-circle');
return c;
});
g.filter(function(d) { return d.node_type=='metabolite'; })
.append('text')
.attr('class', 'node-label label');
this.callback_manager.run('create_node', this, enter_selection);
}
function update_node(update_selection, scale, has_data_on_nodes,
identifiers_on_map, metabolite_data_styles, no_data_style,
mousedown_fn, click_fn, mouseover_fn, mouseout_fn,
drag_behavior, label_drag_behavior) {
// update circle and label location
var hide_secondary_metabolites = this.settings.get_option('hide_secondary_metabolites'),
primary_r = this.settings.get_option('primary_metabolite_radius'),
secondary_r = this.settings.get_option('secondary_metabolite_radius'),
marker_r = this.settings.get_option('marker_radius'),
hide_all_labels = this.settings.get_option('hide_all_labels');
var mg = update_selection
.select('.node-circle')
.attr('transform', function(d) {
return 'translate('+d.x+','+d.y+')';
})
.style('visibility', function(d) {
return (hide_secondary_metabolites && !d.node_is_primary) ? 'hidden' : null;
})
.attr('r', function(d) {
if (d.node_type == 'metabolite') {
var should_scale = (has_data_on_nodes &&
metabolite_data_styles.indexOf('size') != -1);
if (should_scale) {
var f = d.data;
return f===null ? no_data_style['size'] : scale.metabolite_size(f);
} else {
return d.node_is_primary ? primary_r : secondary_r;
}
}
// midmarkers and multimarkers
return marker_r;
})
.style('fill', function(d) {
if (d.node_type=='metabolite') {
var should_color_data = (has_data_on_nodes &&
metabolite_data_styles.indexOf('color') != -1);
if (should_color_data) {
var f = d.data;
return f===null ? no_data_style['color'] : scale.metabolite_color(f);
} else {
return null;
}
}
// midmarkers and multimarkers
return null;
})
.call(this.behavior.turn_off_drag)
.call(drag_behavior)
.on('mousedown', mousedown_fn)
.on('click', click_fn)
.on('mouseover', mouseover_fn)
.on('mouseout', mouseout_fn);
var s = update_selection
.select('.node-label')
.attr('visibility', hide_all_labels ? 'hidden' : 'visible');
if (!hide_all_labels) {
s.style('visibility', function(d) {
return (hide_secondary_metabolites && !d.node_is_primary) ? 'hidden' : null;
})
.attr('transform', function(d) {
return 'translate('+d.label_x+','+d.label_y+')';
})
.text(function(d) {
var t = d[identifiers_on_map];
if (has_data_on_nodes && metabolite_data_styles.indexOf('text') != -1)
t += ' ' + d.data_string;
return t;
})
.call(this.behavior.turn_off_drag)
.call(label_drag_behavior);
}
this.callback_manager.run('update_node', this, update_selection);
}
function create_text_label(enter_selection) {
enter_selection.append('g')
.attr('id', function(d) { return 'l'+d.text_label_id; })
.attr('class', 'text-label')
.append('text')
.attr('class', 'label');
this.callback_manager.run('create_text_label', this, enter_selection);
}
function update_text_label(update_selection) {
var mousedown_fn = this.behavior.text_label_mousedown,
click_fn = this.behavior.text_label_click,
drag_behavior = this.behavior.selectable_drag,
turn_off_drag = this.behavior.turn_off_drag;
update_selection
.select('.label')
.text(function(d) { return d.text; })
.attr('transform', function(d) { return 'translate('+d.x+','+d.y+')';})
.on('mousedown', mousedown_fn)
.on('click', click_fn)
.call(turn_off_drag)
.call(drag_behavior);
this.callback_manager.run('update_text_label', this, update_selection);
}
function displaced_coords(reaction_arrow_displacement, start, end, displace) {
utils.check_undefined(arguments, ['reaction_arrow_displacement', 'start', 'end', 'displace']);
var length = reaction_arrow_displacement,
hyp = utils.distance(start, end),
new_x, new_y;
if (!length || !hyp) console.error('Bad value');
if (displace=='start') {
new_x = start.x + length * (end.x - start.x) / hyp,
new_y = start.y + length * (end.y - start.y) / hyp;
} else if (displace=='end') {
new_x = end.x - length * (end.x - start.x) / hyp,
new_y = end.y - length * (end.y - start.y) / hyp;
} else { console.error('bad displace value: ' + displace); }
return {x: new_x, y: new_y};
}
});
define('build',["utils"], function(utils) {
return { new_reaction: new_reaction,
rotate_nodes: rotate_nodes,
move_node_and_dependents: move_node_and_dependents,
new_text_label: new_text_label,
bezier_id_for_segment_id: bezier_id_for_segment_id,
bezier_ids_for_reaction_ids: bezier_ids_for_reaction_ids,
new_beziers_for_segments: new_beziers_for_segments,
new_beziers_for_reactions: new_beziers_for_reactions };
// definitions
function new_reaction(bigg_id, cobra_reaction, cobra_metabolites,
selected_node_id, selected_node,
largest_ids, cofactors, angle) {
/** New reaction.
angle: clockwise from 'right', in degrees
*/
// rotate the new reaction around the selected metabolite
// convert to radians
angle = Math.PI / 180 * angle;
// generate a new integer id
var new_reaction_id = String(++largest_ids.reactions);
// calculate coordinates of reaction
var selected_node_coords = { x: selected_node.x,
y: selected_node.y };
// rotate main axis around angle with distance
var reaction_length = 300,
main_axis = [ selected_node_coords,
utils.c_plus_c(selected_node_coords,
{'x': reaction_length, 'y': 0}) ],
center = { 'x': (main_axis[0].x + main_axis[1].x)/2,
'y': (main_axis[0].y + main_axis[1].y)/2 };
// relative label location
var label_d;
if (Math.abs(angle) < Math.PI/4 ||
Math.abs(angle - Math.PI) < Math.PI/4 ) {
label_d = { x: -50, y: -40 };
} else {
label_d = { x: 30, y: 10 };
}
// relative anchor node distance
var anchor_distance = 20;
// new reaction structure
var new_reaction = utils.clone(cobra_reaction);
utils.extend(new_reaction,
{ label_x: center.x + label_d.x,
label_y: center.y + label_d.y,
segments: {} });
// set primary metabolites and count reactants/products
// look for the selected metabolite, and record the indices
var reactant_ranks = [], product_ranks = [],
reactant_count = 0, product_count = 0,
reaction_is_reversed = false;
for (var met_bigg_id in new_reaction.metabolites) {
// make the metabolites into objects
var metabolite = cobra_metabolites[met_bigg_id],
coefficient = new_reaction.metabolites[met_bigg_id],
formula = metabolite.formula,
new_metabolite = { coefficient: coefficient,
bigg_id: met_bigg_id,
name: metabolite.name };
if (coefficient < 0) {
new_metabolite.index = reactant_count;
// score the metabolites. Infinity == selected, >= 1 == carbon containing
var carbons = /C([0-9]+)/.exec(formula);
if (selected_node.bigg_id==new_metabolite.bigg_id) {
reactant_ranks.push([new_metabolite.index, Infinity]);
} else if (carbons && cofactors.indexOf(utils.decompartmentalize(new_metabolite.bigg_id)[0])==-1) {
reactant_ranks.push([new_metabolite.index, parseInt(carbons[1])]);
}
reactant_count++;
} else {
new_metabolite.index = product_count;
var carbons = /C([0-9]+)/.exec(formula);
if (selected_node.bigg_id==new_metabolite.bigg_id) {
product_ranks.push([new_metabolite.index, Infinity]);
reaction_is_reversed = true;
} else if (carbons && cofactors.indexOf(utils.decompartmentalize(new_metabolite.bigg_id)[0])==-1) {
product_ranks.push([new_metabolite.index, parseInt(carbons[1])]);
}
product_count++;
}
new_reaction.metabolites[met_bigg_id] = new_metabolite;
}
// get the rank with the highest score
var max_rank = function(old, current) { return current[1] > old[1] ? current : old; },
primary_reactant_index = reactant_ranks.reduce(max_rank, [0,0])[0],
primary_product_index = product_ranks.reduce(max_rank, [0,0])[0];
// set primary metabolites, and keep track of the total counts
for (var met_bigg_id in new_reaction.metabolites) {
var metabolite = new_reaction.metabolites[met_bigg_id];
if (metabolite.coefficient < 0) {
if (metabolite.index==primary_reactant_index) metabolite.is_primary = true;
metabolite.count = reactant_count + 1;
} else {
if (metabolite.index==primary_product_index) metabolite.is_primary = true;
metabolite.count = product_count + 1;
}
}
// generate anchor nodes
var new_anchors = {},
anchors = [ { node_type: 'anchor_reactants',
dis: { x: anchor_distance * (reaction_is_reversed ? 1 : -1), y: 0 } },
{ node_type: 'center',
dis: { x: 0, y: 0 } },
{ node_type: 'anchor_products',
dis: { x: anchor_distance * (reaction_is_reversed ? -1 : 1), y: 0 } } ],
anchor_ids = {};
anchors.map(function(n) {
var new_id = String(++largest_ids.nodes),
general_node_type = (n.node_type=='center' ? 'midmarker' : 'multimarker');
new_anchors[new_id] = { node_type: general_node_type,
x: center.x + n.dis.x,
y: center.y + n.dis.y,
connected_segments: [],
name: null,
bigg_id: null,
label_x: null,
label_y: null,
node_is_primary: null };
anchor_ids[n.node_type] = new_id;
});
// add the segments, outside to inside
var new_anchor_groups = [ [ anchor_ids['anchor_reactants'], anchor_ids['center'] ],
[ anchor_ids['anchor_products'], anchor_ids['center'] ] ];
new_anchor_groups.map(function(l) {
var from_id = l[0], to_id = l[1],
new_segment_id = String(++largest_ids.segments);
new_reaction.segments[new_segment_id] = { b1: null,
b2: null,
from_node_id: from_id,
to_node_id: to_id,
from_node_coefficient: null,
to_node_coefficient: null,
reversibility: new_reaction.reversibility,
data: new_reaction.data,
reverse_flux: new_reaction.reverse_flux };
new_anchors[from_id].connected_segments.push({ segment_id: new_segment_id,
reaction_id: new_reaction_id });
new_anchors[to_id].connected_segments.push({ segment_id: new_segment_id,
reaction_id: new_reaction_id });
});
// Add the metabolites, keeping track of total reactants and products.
var new_nodes = new_anchors;
for (var met_bigg_id in new_reaction.metabolites) {
var metabolite = new_reaction.metabolites[met_bigg_id],
primary_index, from_node_id;
if (metabolite.coefficient < 0) {
// metabolite.count = reactant_count + 1;
primary_index = primary_reactant_index;
from_node_id = anchor_ids['anchor_reactants'];
} else {
// metabolite.count = product_count + 1;
primary_index = primary_product_index;
from_node_id = anchor_ids['anchor_products'];
}
// calculate coordinates of metabolite components
var met_loc = calculate_new_metabolite_coordinates(metabolite,
primary_index,
main_axis,
center,
reaction_length,
reaction_is_reversed);
// if this is the existing metabolite
if (selected_node.bigg_id==metabolite.bigg_id) {
var new_segment_id = String(++largest_ids.segments);
new_reaction.segments[new_segment_id] = { b1: met_loc.b1,
b2: met_loc.b2,
from_node_id: from_node_id,
to_node_id: selected_node_id,
from_node_coefficient: null,
to_node_coefficient: metabolite.coefficient,
reversibility: new_reaction.reversibility,
data: new_reaction.data,
reverse_flux: new_reaction.reverse_flux };
// update the existing node
selected_node.connected_segments.push({ segment_id: new_segment_id,
reaction_id: new_reaction_id });
new_nodes[from_node_id].connected_segments.push({ segment_id: new_segment_id,
reaction_id: new_reaction_id });
} else {
// save new metabolite
var new_segment_id = String(++largest_ids.segments),
new_node_id = String(++largest_ids.nodes);
new_reaction.segments[new_segment_id] = { b1: met_loc.b1,
b2: met_loc.b2,
from_node_id: from_node_id,
to_node_id: new_node_id,
from_node_coefficient: null,
to_node_coefficient: metabolite.coefficient,
reversibility: new_reaction.reversibility,
data: new_reaction.data,
reverse_flux: new_reaction.reverse_flux };
// save new node
new_nodes[new_node_id] = { connected_segments: [{ segment_id: new_segment_id,
reaction_id: new_reaction_id }],
x: met_loc.circle.x,
y: met_loc.circle.y,
node_is_primary: Boolean(metabolite.is_primary),
label_x: met_loc.circle.x + label_d.x,
label_y: met_loc.circle.y + label_d.y,
name: metabolite.name,
bigg_id: metabolite.bigg_id,
node_type: 'metabolite' };
new_nodes[from_node_id].connected_segments.push({ segment_id: new_segment_id,
reaction_id: new_reaction_id });
}
}
// now take out the extra reaction details
var metabolites_array = []
for (var bigg_id in new_reaction.metabolites) {
metabolites_array.push({'bigg_id': bigg_id,
'coefficient': new_reaction.metabolites[bigg_id].coefficient});
}
new_reaction.metabolites = metabolites_array;
// new_reactions object
var new_reactions = {};
new_reactions[new_reaction_id] = new_reaction;
// new_beziers object
var new_beziers = new_beziers_for_reactions(new_reactions);
// add the selected node for rotation, and return it as a new (updated) node
new_nodes[selected_node_id] = selected_node;
rotate_nodes(new_nodes, new_reactions, new_beziers,
angle, selected_node_coords);
return { new_reactions: new_reactions,
new_beziers: new_beziers,
new_nodes: new_nodes };
}
function rotate_nodes(selected_nodes, reactions, beziers, angle, center) {
/** Rotate the nodes around center.
selected_nodes: Nodes to rotate.
reactions: Only updates beziers for these reactions.
beziers: Also update the bezier points.
angle: Angle to rotate in radians.
center: Point to rotate around.
*/
// functions
var rotate_around = function(coord) {
if (coord === null)
return null;
return utils.rotate_coords(coord, angle, center);
};
// recalculate: node
var updated_node_ids = [], updated_reaction_ids = [];
for (var node_id in selected_nodes) {
var node = selected_nodes[node_id],
// rotation distance
displacement = rotate_around({ x: node.x, y: node.y }),
// move the node
updated = move_node_and_labels(node, reactions,
displacement);
// move the bezier points
node.connected_segments.map(function(segment_obj) {
var reaction = reactions[segment_obj.reaction_id];
// If the reaction was not passed in the reactions argument, then ignore
if (reaction === undefined) return;
// rotate the beziers
var segment_id = segment_obj.segment_id,
segment = reaction.segments[segment_id];
if (segment.to_node_id==node_id && segment.b2) {
var displacement = rotate_around(segment.b2),
bez_id = bezier_id_for_segment_id(segment_id, 'b2');
segment.b2 = utils.c_plus_c(segment.b2, displacement);
beziers[bez_id].x = segment.b2.x;
beziers[bez_id].y = segment.b2.y;
} else if (segment.from_node_id==node_id && segment.b1) {
var displacement = rotate_around(segment.b1),
bez_id = bezier_id_for_segment_id(segment_id, 'b1');
segment.b1 = utils.c_plus_c(segment.b1, displacement);
beziers[bez_id].x = segment.b1.x;
beziers[bez_id].y = segment.b1.y;
}
});
updated_reaction_ids = utils.unique_concat([updated_reaction_ids,
updated.reaction_ids]);
updated_node_ids.push(node_id);
}
return { node_ids: updated_node_ids,
reaction_ids: updated_reaction_ids };
}
function move_node_and_dependents(node, node_id, reactions, beziers, displacement) {
/** Move the node and its labels and beziers.
*/
var updated = move_node_and_labels(node, reactions, displacement);
// move beziers
node.connected_segments.map(function(segment_obj) {
var reaction = reactions[segment_obj.reaction_id];
// If the reaction was not passed in the reactions argument, then ignore
if (reaction === undefined) return;
// update beziers
var segment_id = segment_obj.segment_id,
segment = reaction.segments[segment_id];
[['b1', 'from_node_id'], ['b2', 'to_node_id']].forEach(function(c) {
var bez = c[0],
node = c[1];
if (segment[node]==node_id && segment[bez]) {
segment[bez] = utils.c_plus_c(segment[bez], displacement);
var tbez = beziers[bezier_id_for_segment_id(segment_id, bez)];
tbez.x = segment[bez].x;
tbez.y = segment[bez].y;
}
});
// add to list of updated reaction ids if it isn't already there
if (updated.reaction_ids.indexOf(segment_obj.reaction_id) < 0) {
updated.reaction_ids.push(segment_obj.reaction_id);
}
});
return updated;
}
function move_node_and_labels(node, reactions, displacement) {
node.x = node.x + displacement.x;
node.y = node.y + displacement.y;
// recalculate: node label
node.label_x = node.label_x + displacement.x;
node.label_y = node.label_y + displacement.y;
// recalculate: reaction label
var updated_reaction_ids = [];
node.connected_segments.map(function(segment_obj) {
var reaction = reactions[segment_obj.reaction_id];
// add to list of updated reaction ids if it isn't already there
if (updated_reaction_ids.indexOf(segment_obj.reaction_id) < 0) {
updated_reaction_ids.push(segment_obj.reaction_id);
// update reaction label (but only once per reaction
if (node.node_type == 'midmarker') {
reaction.label_x = reaction.label_x + displacement.x;
reaction.label_y = reaction.label_y + displacement.y;
}
}
});
return { reaction_ids: updated_reaction_ids };
}
function calculate_new_metabolite_coordinates(met, primary_index, main_axis, center, dis, is_reversed) {
/** Calculate metabolite coordinates for a new reaction metabolite.
*/
// new local coordinate system
var displacement = main_axis[0],
main_axis = [utils.c_minus_c(main_axis[0], displacement),
utils.c_minus_c(main_axis[1], displacement)],
center = utils.c_minus_c(center, displacement);
// Curve parameters
var w = 80, // distance between reactants and between products
b1_strength = 0.4,
b2_strength = 0.25,
w2 = w*0.7,
secondary_dis = 40,
num_slots = Math.min(2, met.count - 1);
// size and spacing for primary and secondary metabolites
var ds, draw_at_index, r;
if (met.is_primary) { // primary
ds = 20;
} else { // secondary
ds = 10;
// don't use center slot
if (met.index > primary_index) draw_at_index = met.index - 1;
else draw_at_index = met.index;
}
var de = dis - ds, // distance between ends of line axis
reaction_axis = [{'x': ds, 'y': 0},
{'x': de, 'y': 0}];
// Define line parameters and axis.
// Begin with unrotated coordinate system. +y = Down, +x = Right.
var end, circle, b1, b2;
// reactants
if (((met.coefficient < 0) != is_reversed) && met.is_primary) { // Ali == BADASS
end = {'x': reaction_axis[0].x,
'y': reaction_axis[0].y};
b1 = {'x': center.x*(1-b1_strength) + reaction_axis[0].x*b1_strength,
'y': center.y*(1-b1_strength) + reaction_axis[0].y*b1_strength};
b2 = {'x': center.x*b2_strength + (end.x)*(1-b2_strength),
'y': center.y*b2_strength + (end.y)*(1-b2_strength)},
circle = {'x': main_axis[0].x,
'y': main_axis[0].y};
} else if ((met.coefficient < 0) != is_reversed) {
end = {'x': reaction_axis[0].x + secondary_dis,
'y': reaction_axis[0].y + (w2*draw_at_index - w2*(num_slots-1)/2)},
b1 = {'x': center.x*(1-b1_strength) + reaction_axis[0].x*b1_strength,
'y': center.y*(1-b1_strength) + reaction_axis[0].y*b1_strength},
b2 = {'x': center.x*b2_strength + end.x*(1-b2_strength),
'y': center.y*b2_strength + end.y*(1-b2_strength)},
circle = {'x': main_axis[0].x + secondary_dis,
'y': main_axis[0].y + (w*draw_at_index - w*(num_slots-1)/2)};
} else if (((met.coefficient > 0) != is_reversed) && met.is_primary) { // products
end = {'x': reaction_axis[1].x,
'y': reaction_axis[1].y};
b1 = {'x': center.x*(1-b1_strength) + reaction_axis[1].x*b1_strength,
'y': center.y*(1-b1_strength) + reaction_axis[1].y*b1_strength};
b2 = {'x': center.x*b2_strength + end.x*(1-b2_strength),
'y': center.y*b2_strength + end.y*(1-b2_strength)},
circle = {'x': main_axis[1].x,
'y': main_axis[1].y};
} else if ((met.coefficient > 0) != is_reversed) {
end = {'x': reaction_axis[1].x - secondary_dis,
'y': reaction_axis[1].y + (w2*draw_at_index - w2*(num_slots-1)/2)},
b1 = {'x': center.x*(1-b1_strength) + reaction_axis[1].x*b1_strength,
'y': center.y*(1-b1_strength) + reaction_axis[1].y*b1_strength};
b2 = {'x': center.x*b2_strength + end.x*(1-b2_strength),
'y': center.y*b2_strength + end.y*(1-b2_strength)},
circle = {'x': main_axis[1].x - secondary_dis,
'y': main_axis[1].y + (w*draw_at_index - w*(num_slots-1)/2)};
}
var loc = {};
loc.b1 = utils.c_plus_c(displacement, b1);
loc.b2 = utils.c_plus_c(displacement, b2);
loc.circle = utils.c_plus_c(displacement, circle);
return loc;
}
function new_text_label(largest_ids, text, coords) {
var new_id = String(++largest_ids.text_labels),
new_label = { text: text,
x: coords.x,
y: coords.y };
return {id: new_id, label: new_label};
}
function bezier_id_for_segment_id(segment_id, bez) {
return segment_id+'_'+bez;
}
function bezier_ids_for_reaction_ids(reactions) {
/** Return an array of beziers ids for the array of reaction ids.
Arguments
---------
reactions: A reactions object, e.g. a subset of *escher.Map.reactions*.
*/
var bezier_ids = [];
for (var reaction_id in reactions) {
var reaction = reactions[reaction_id];
for (var segment_id in reaction.segments) {
var segment = reaction.segments[segment_id];
['b1', 'b2'].forEach(function(bez) {
var seg_bez = segment[bez];
if (seg_bez !== null) {
bezier_ids.push(bezier_id_for_segment_id(segment_id, bez));
}
});
}
}
return bezier_ids;
}
function new_beziers_for_segments(segments, reaction_id) {
/** Return an object containing beziers for the segments object.
Arguments
---------
segments: A segments object, e.g. *escher.Map.segments*.
reaction_id: The reaction id for the segments.
*/
var beziers = {};
for (var segment_id in segments) {
var segment = segments[segment_id];
['b1', 'b2'].forEach(function(bez) {
var seg_bez = segment[bez];
if (seg_bez !== null) {
var bezier_id = bezier_id_for_segment_id(segment_id, bez);
beziers[bezier_id] = {
bezier: bez,
x: seg_bez.x,
y: seg_bez.y,
reaction_id: reaction_id,
segment_id: segment_id
};
}
});
}
return beziers;
}
function new_beziers_for_reactions(reactions) {
/** Return an object containing beziers for the reactions object.
Arguments
---------
reactions: A reactions object, e.g. *escher.Map.reactions*.
*/
var beziers = {};
for (var reaction_id in reactions) {
var reaction = reactions[reaction_id];
var these = new_beziers_for_segments(reaction.segments, reaction_id);
utils.extend(beziers, these);
}
return beziers;
}
});
define('Behavior',["utils", "build"], function(utils, build) {
/** Defines the set of click and drag behaviors for the map, and keeps track
of which behaviors are activated.
A Behavior instance has the following attributes:
my_behavior.rotation_drag:
my_behavior.text_label_mousedown:
my_behavior.text_label_click:
my_behavior.selectable_mousedown:
my_behavior.selectable_click:
my_behavior.selectable_drag:
my_behavior.node_mouseover:
my_behavior.node_mouseout:
my_behavior.label_mousedown:
my_behavior.label_mouseover:
my_behavior.label_mouseout:
my_behavior.bezier_drag:
my_behavior.bezier_mouseover:
my_behavior.bezier_mouseout:
my_behavior.reaction_label_drag:
my_behavior.node_label_drag:
*/
var Behavior = utils.make_class();
// methods
Behavior.prototype = { init: init,
toggle_rotation_mode: toggle_rotation_mode,
turn_everything_on: turn_everything_on,
turn_everything_off: turn_everything_off,
// toggle
toggle_selectable_click: toggle_selectable_click,
toggle_text_label_edit: toggle_text_label_edit,
toggle_selectable_drag: toggle_selectable_drag,
toggle_label_drag: toggle_label_drag,
toggle_label_mousedown: toggle_label_mousedown,
toggle_bezier_drag: toggle_bezier_drag,
// util
turn_off_drag: turn_off_drag,
// get drag behaviors
_get_selectable_drag: _get_selectable_drag,
_get_bezier_drag: _get_bezier_drag,
_get_reaction_label_drag: _get_reaction_label_drag,
_get_node_label_drag: _get_node_label_drag,
_get_generic_drag: _get_generic_drag,
_get_generic_angular_drag: _get_generic_angular_drag };
return Behavior;
// definitions
function init(map, undo_stack) {
this.map = map;
this.undo_stack = undo_stack;
// make an empty function that can be called as a behavior and does nothing
this.empty_behavior = function() {};
// rotation mode operates separately from the rest
this.rotation_mode_enabled = false;
this.rotation_drag = d3.behavior.drag();
// behaviors to be applied
this.selectable_mousedown = null;
this.text_label_mousedown = null;
this.text_label_click = null;
this.selectable_drag = this.empty_behavior;
this.node_mouseover = null;
this.node_mouseout = null;
this.label_mousedown = null;
this.label_mouseover = null;
this.label_mouseout = null;
this.bezier_drag = this.empty_behavior;
this.bezier_mouseover = null;
this.bezier_mouseout = null;
this.reaction_label_drag = this.empty_behavior;
this.node_label_drag = this.empty_behavior;
this.turn_everything_on();
}
function turn_everything_on() {
/** Toggle everything except rotation mode and text mode.
*/
this.toggle_selectable_click(true);
this.toggle_selectable_drag(true);
this.toggle_label_drag(true);
this.toggle_label_mousedown(true);
}
function turn_everything_off() {
/** Toggle everything except rotation mode and text mode.
*/
this.toggle_selectable_click(false);
this.toggle_selectable_drag(false);
this.toggle_label_drag(false);
this.toggle_label_mousedown(false);
}
function toggle_rotation_mode(on_off) {
/** Listen for rotation, and rotate selected nodes.
*/
if (on_off===undefined) {
this.rotation_mode_enabled = !this.rotation_mode_enabled;
} else {
this.rotation_mode_enabled = on_off;
}
var selection_node = this.map.sel.selectAll('.node-circle'),
selection_background = this.map.sel.selectAll('#canvas');
if (this.rotation_mode_enabled) {
this.map.callback_manager.run('start_rotation');
var selected_nodes = this.map.get_selected_nodes();
if (Object.keys(selected_nodes).length == 0) {
console.warn('No selected nodes');
return;
}
// show center
this.center = average_location(selected_nodes);
show_center.call(this);
// this.set_status('Drag to rotate.');
var map = this.map,
selected_node_ids = Object.keys(selected_nodes),
reactions = this.map.reactions,
nodes = this.map.nodes,
beziers = this.map.beziers;
var start_fn = function(d) {
// silence other listeners
d3.event.sourceEvent.stopPropagation();
},
drag_fn = function(d, angle, total_angle, center) {
var updated = build.rotate_nodes(selected_nodes, reactions,
beziers, angle, center);
map.draw_these_nodes(updated.node_ids);
map.draw_these_reactions(updated.reaction_ids);
},
end_fn = function(d) {},
undo_fn = function(d, total_angle, center) {
// undo
var these_nodes = {};
selected_node_ids.forEach(function(id) {
these_nodes[id] = nodes[id];
});
var updated = build.rotate_nodes(these_nodes, reactions,
beziers, -total_angle,
center);
map.draw_these_nodes(updated.node_ids);
map.draw_these_reactions(updated.reaction_ids);
},
redo_fn = function(d, total_angle, center) {
// redo
var these_nodes = {};
selected_node_ids.forEach(function(id) {
these_nodes[id] = nodes[id];
});
var updated = build.rotate_nodes(these_nodes, reactions,
beziers, total_angle,
center);
map.draw_these_nodes(updated.node_ids);
map.draw_these_reactions(updated.reaction_ids);
},
center_fn = function() {
return this.center;
}.bind(this);
this.rotation_drag = this._get_generic_angular_drag(start_fn, drag_fn, end_fn,
undo_fn, redo_fn, center_fn,
this.map.sel);
selection_background.call(this.rotation_drag);
this.selectable_drag = this.rotation_drag;
} else {
// turn off all listeners
hide_center.call(this);
selection_node.on('mousedown.center', null);
selection_background.on('mousedown.center', null);
selection_background.on('mousedown.drag', null);
selection_background.on('touchstart.drag', null);
this.rotation_drag = null;
this.selectable_drag = null;
}
// definitions
function show_center() {
var s = this.map.sel.selectAll('#rotation-center')
.data([0]),
enter = s.enter()
.append('g').attr('id', 'rotation-center');
enter.append('path').attr('d', 'M-32 0 L32 0')
.attr('class', 'rotation-center-line');
enter.append('path').attr('d', 'M0 -32 L0 32')
.attr('class', 'rotation-center-line');
s.attr('transform', 'translate('+this.center.x+','+this.center.y+')')
.attr('visibility', 'visible');
s.call(d3.behavior.drag()
.on('drag', function(sel) {
var cur = d3.transform(sel.attr('transform')),
new_loc = [d3.event.dx + cur.translate[0],
d3.event.dy + cur.translate[1]];
sel.attr('transform', 'translate('+new_loc+')');
this.center = { x: new_loc[0], y: new_loc[1] };
}.bind(this, s)));
s.on('mouseover', function() {
var current = parseFloat(this.selectAll('path').style('stroke-width'));
this.selectAll('path').style('stroke-width', current * 2 + 'px');
}.bind(s));
s.on('mouseout', function() {
this.selectAll('path').style('stroke-width', null);
}.bind(s));
}
function hide_center(sel) {
this.map.sel.select('#rotation-center')
.attr('visibility', 'hidden');
}
function average_location(nodes) {
var xs = [], ys = [];
for (var node_id in nodes) {
var node = nodes[node_id];
if (node.x !== undefined)
xs.push(node.x);
if (node.y !== undefined)
ys.push(node.y);
}
return { x: utils.mean(xs),
y: utils.mean(ys) };
}
}
function toggle_selectable_click(on_off) {
/** With no argument, toggle the node click on or off.
Pass in a boolean argument to set the on/off state.
*/
if (on_off===undefined) on_off = this.selectable_mousedown==null;
if (on_off) {
var map = this.map;
this.selectable_mousedown = function(d) {
// stop propogation for the buildinput to work right
d3.event.stopPropagation();
// this.parentNode.__data__.was_selected = d3.select(this.parentNode).classed('selected');
// d3.select(this.parentNode).classed('selected', true);
};
this.selectable_click = function(d) {
// stop propogation for the buildinput to work right
d3.event.stopPropagation();
// click suppressed. This DOES have en effect.
if (d3.event.defaultPrevented) return;
// turn off the temporary selection so select_selectable
// works. This is a bit of a hack.
// if (!this.parentNode.__data__.was_selected)
// d3.select(this.parentNode).classed('selected', false);
map.select_selectable(this, d);
// this.parentNode.__data__.was_selected = false;
};
this.node_mouseover = function(d) {
d3.select(this).style('stroke-width', null);
var current = parseFloat(d3.select(this).style('stroke-width'));
if (!d3.select(this.parentNode).classed('selected'))
d3.select(this).style('stroke-width', current * 3 + 'px');
};
this.node_mouseout = function(d) {
d3.select(this).style('stroke-width', null);
};
} else {
this.selectable_mousedown = null;
this.selectable_click = null;
this.node_mouseover = null;
this.node_mouseout = null;
this.map.sel.select('#nodes')
.selectAll('.node-circle').style('stroke-width', null);
}
}
function toggle_text_label_edit(on_off) {
/** With no argument, toggle the text edit on mousedown on/off.
Pass in a boolean argument to set the on/off state.
The backup state is equal to selectable_mousedown.
*/
if (on_off===undefined) on_off = this.text_edit_mousedown == null;
if (on_off) {
var map = this.map,
selection = this.selection;
this.text_label_mousedown = function() {
if (d3.event.defaultPrevented) return; // mousedown suppressed
// run the callback
var coords_a = d3.transform(d3.select(this).attr('transform')).translate,
coords = {x: coords_a[0], y: coords_a[1]};
map.callback_manager.run('edit_text_label', null, d3.select(this), coords);
d3.event.stopPropagation();
};
this.text_label_click = null;
this.map.sel.select('#text-labels')
.selectAll('.label')
.classed('edit-text-cursor', true);
// add the new-label listener
this.map.sel.on('mousedown.new_text_label', function(node) {
// silence other listeners
d3.event.preventDefault();
var coords = { x: d3.mouse(node)[0],
y: d3.mouse(node)[1] };
this.map.callback_manager.run('new_text_label', null, coords);
}.bind(this, this.map.sel.node()));
} else {
this.text_label_mousedown = this.selectable_mousedown;
this.text_label_click = this.selectable_click;
this.map.sel.select('#text-labels')
.selectAll('.label')
.classed('edit-text-cursor', false);
// remove the new-label listener
this.map.sel.on('mousedown.new_text_label', null);
this.map.callback_manager.run('hide_text_label_editor');
}
}
function toggle_selectable_drag(on_off) {
/** With no argument, toggle the node drag & bezier drag on or off.
Pass in a boolean argument to set the on/off state.
*/
if (on_off===undefined) on_off = this.selectable_drag===this.empty_behavior;
if (on_off) {
this.selectable_drag = this._get_selectable_drag(this.map, this.undo_stack);
this.bezier_drag = this._get_bezier_drag(this.map, this.undo_stack);
} else {
this.selectable_drag = this.empty_behavior;
this.bezier_drag = this.empty_behavior;
}
}
function toggle_label_drag(on_off) {
/** With no argument, toggle the label drag on or off.
Pass in a boolean argument to set the on/off state.
*/
if (on_off===undefined) on_off = this.label_drag===this.empty_behavior;
if (on_off) {
this.reaction_label_drag = this._get_reaction_label_drag(this.map);
this.node_label_drag = this._get_node_label_drag(this.map);
} else {
this.reaction_label_drag = this.empty_behavior;
this.node_label_drag = this.empty_behavior;
}
}
function toggle_label_mousedown(on_off) {
/** With no argument, toggle the reaction label mousedown on or off.z
Arguments
---------
on_off: A boolean argument to set the on/off state.
*/
if (on_off===undefined) on_off = this.label_mousedown==null;
if (on_off) {
var map = this.map;
// TODO turn this feature (reaction label selection) back on, but
// with correct shift key management
this.label_mousedown = function(d) {
// if (d3.event.defaultPrevented) return; // mousedown suppressed
// // select reaction/node
// d3.select(this.parentNode.parentNode)
// .each(function(d) {
// var node_ids = {};
// for (var seg_id in d.segments) {
// ['to_node_id', 'from_node_id'].forEach(function(n) {
// node_ids[d.segments[seg_id][n]] = true;
// });
// }
// map.sel.selectAll('.selected').classed('selected', false);
// map.sel.selectAll('.node')
// .classed('selected', function(d) {
// return (d.node_id in node_ids);
// });
// });
// d3.event.stopPropagation();
};
this.label_mouseover = function(d) {
// d3.select(this).style('fill', 'rgb(56, 56, 184)');
};
this.label_mouseout = function(d) {
// d3.select(this).style('fill', null);
};
} else {
this.label_mousedown = null;
this.label_mouseover = null;
this.label_mouseout = null;
this.map.sel.select('.node-label,.reaction-label')
.style('fill', null);
}
}
function toggle_bezier_drag(on_off) {
/** With no argument, toggle the bezier drag on or off.
Pass in a boolean argument to set the on/off state.
*/
if (on_off===undefined) on_off = this.bezier_drag===this.empty_behavior;
if (on_off) {
this.bezier_drag = this._get_bezier_drag(this.map);
this.bezier_mouseover = function(d) {
d3.select(this).style('stroke-width', String(3)+'px');
};
this.bezier_mouseout = function(d) {
d3.select(this).style('stroke-width', String(1)+'px');
};
} else {
this.bezier_drag = this.empty_behavior;
this.bezier_mouseover = null;
this.bezier_mouseout = null;
}
}
function turn_off_drag(sel) {
sel.on('mousedown.drag', null);
sel.on('touchstart.drag', null);
}
function _get_selectable_drag(map, undo_stack) {
/** Drag the selected nodes and text labels.
*/
// define some variables
var behavior = d3.behavior.drag(),
the_timeout = null,
total_displacement = null,
// for nodes
node_ids_to_drag = null,
reaction_ids = null,
// for text labels
text_label_ids_to_drag = null,
move_label = function(text_label_id, displacement) {
var text_label = map.text_labels[text_label_id];
text_label.x = text_label.x + displacement.x;
text_label.y = text_label.y + displacement.y;
};
behavior.on("dragstart", function (d) {
// silence other listeners (e.g. nodes BELOW this one)
d3.event.sourceEvent.stopPropagation();
// remember the total displacement for later
// total_displacement = {};
total_displacement = {x: 0, y: 0};
// If a text label is selected, the rest is not necessary
if (d3.select(this).attr('class').indexOf('label') == -1) {
// Note that dragstart is called even for a click event
var data = this.parentNode.__data__,
bigg_id = data.bigg_id,
node_group = this.parentNode;
// Move element to back (for the next step to work). Wait 200ms
// before making the move, becuase otherwise the element will be
// deleted before the click event gets called, and selection
// will stop working.
the_timeout = window.setTimeout(function() {
node_group.parentNode.insertBefore(node_group,node_group.parentNode.firstChild);
}, 200);
// prepare to combine metabolites
map.sel.selectAll('.metabolite-circle')
.on('mouseover.combine', function(d) {
if (d.bigg_id==bigg_id && d.node_id!=data.node_id) {
d3.select(this).style('stroke-width', String(12)+'px')
.classed('node-to-combine', true);
}
}).on('mouseout.combine', function(d) {
if (d.bigg_id==bigg_id) {
map.sel.selectAll('.node-to-combine').style('stroke-width', String(2)+'px')
.classed('node-to-combine', false);
}
});
}
});
behavior.on("drag", function(d) {
// if this node is not already selected, then select this one and
// deselect all other nodes. Otherwise, leave the selection alone.
if (!d3.select(this.parentNode).classed('selected'))
map.select_selectable(this, d);
// get the grabbed id
var grabbed = {};
if (d3.select(this).attr('class').indexOf('label')==-1) {
// if it is a node
grabbed['type'] = 'node';
grabbed['id'] = this.parentNode.__data__.node_id;
} else {
// if it is a text label
grabbed['type'] = 'label';
grabbed['id'] = this.__data__.text_label_id;
}
var selected_node_ids = map.get_selected_node_ids(),
selected_text_label_ids = map.get_selected_text_label_ids();
node_ids_to_drag = []; text_label_ids_to_drag = [];
// choose the nodes and text labels to drag
if (grabbed['type']=='node' &&
selected_node_ids.indexOf(grabbed['id'])==-1) {
node_ids_to_drag.push(grabbed['id']);
} else if (grabbed['type']=='label' &&
selected_text_label_ids.indexOf(grabbed['id'])==-1) {
text_label_ids_to_drag.push(grabbed['id']);
} else {
node_ids_to_drag = selected_node_ids;
text_label_ids_to_drag = selected_text_label_ids;
}
reaction_ids = [];
var displacement = { x: d3.event.dx,
y: d3.event.dy };
total_displacement = utils.c_plus_c(total_displacement, displacement);
node_ids_to_drag.forEach(function(node_id) {
// update data
var node = map.nodes[node_id],
updated = build.move_node_and_dependents(node, node_id,
map.reactions,
map.beziers,
displacement);
reaction_ids = utils.unique_concat([reaction_ids, updated.reaction_ids]);
// remember the displacements
// if (!(node_id in total_displacement)) total_displacement[node_id] = { x: 0, y: 0 };
// total_displacement[node_id] = utils.c_plus_c(total_displacement[node_id], displacement);
});
text_label_ids_to_drag.forEach(function(text_label_id) {
move_label(text_label_id, displacement);
// remember the displacements
// if (!(node_id in total_displacement)) total_displacement[node_id] = { x: 0, y: 0 };
// total_displacement[node_id] = utils.c_plus_c(total_displacement[node_id], displacement);
});
// draw
map.draw_these_nodes(node_ids_to_drag);
map.draw_these_reactions(reaction_ids);
map.draw_these_text_labels(text_label_ids_to_drag);
});
behavior.on("dragend", function() {
if (node_ids_to_drag===null) {
// Dragend can be called when drag has not been called. In this,
// case, do nothing.
total_displacement = null;
node_ids_to_drag = null;
text_label_ids_to_drag = null;
reaction_ids = null;
the_timeout = null;
return;
}
// look for mets to combine
var node_to_combine_array = [];
map.sel.selectAll('.node-to-combine').each(function(d) {
node_to_combine_array.push(d.node_id);
});
if (node_to_combine_array.length==1) {
// If a node is ready for it, combine nodes
var fixed_node_id = node_to_combine_array[0],
dragged_node_id = this.parentNode.__data__.node_id,
saved_dragged_node = utils.clone(map.nodes[dragged_node_id]),
segment_objs_moved_to_combine = combine_nodes_and_draw(fixed_node_id,
dragged_node_id);
undo_stack.push(function() {
// undo
// put the old node back
map.nodes[dragged_node_id] = saved_dragged_node;
var fixed_node = map.nodes[fixed_node_id],
updated_reactions = [];
segment_objs_moved_to_combine.forEach(function(segment_obj) {
var segment = map.reactions[segment_obj.reaction_id].segments[segment_obj.segment_id];
if (segment.from_node_id==fixed_node_id) {
segment.from_node_id = dragged_node_id;
} else if (segment.to_node_id==fixed_node_id) {
segment.to_node_id = dragged_node_id;
} else {
console.error('Segment does not connect to fixed node');
}
// removed this segment_obj from the fixed node
fixed_node.connected_segments = fixed_node.connected_segments.filter(function(x) {
return !(x.reaction_id==segment_obj.reaction_id && x.segment_id==segment_obj.segment_id);
});
if (updated_reactions.indexOf(segment_obj.reaction_id)==-1)
updated_reactions.push(segment_obj.reaction_id);
});
map.draw_these_nodes([dragged_node_id]);
map.draw_these_reactions(updated_reactions);
}, function () {
// redo
combine_nodes_and_draw(fixed_node_id, dragged_node_id);
});
} else {
// otherwise, drag node
// add to undo/redo stack
// remember the displacement, dragged nodes, and reactions
var saved_displacement = utils.clone(total_displacement),
// BUG TODO this variable disappears!
// Happens sometimes when you drag a node, then delete it, then undo twice
saved_node_ids = utils.clone(node_ids_to_drag),
saved_text_label_ids = utils.clone(text_label_ids_to_drag),
saved_reaction_ids = utils.clone(reaction_ids);
undo_stack.push(function() {
// undo
saved_node_ids.forEach(function(node_id) {
var node = map.nodes[node_id];
build.move_node_and_dependents(node, node_id, map.reactions,
map.beziers,
utils.c_times_scalar(saved_displacement, -1));
});
saved_text_label_ids.forEach(function(text_label_id) {
move_label(text_label_id,
utils.c_times_scalar(saved_displacement, -1));
});
map.draw_these_nodes(saved_node_ids);
map.draw_these_reactions(saved_reaction_ids);
map.draw_these_text_labels(saved_text_label_ids);
}, function () {
// redo
saved_node_ids.forEach(function(node_id) {
var node = map.nodes[node_id];
build.move_node_and_dependents(node, node_id, map.reactions,
map.beziers,
saved_displacement);
});
saved_text_label_ids.forEach(function(text_label_id) {
move_label(text_label_id, saved_displacement);
});
map.draw_these_nodes(saved_node_ids);
map.draw_these_reactions(saved_reaction_ids);
map.draw_these_text_labels(saved_text_label_ids);
});
}
// stop combining metabolites
map.sel.selectAll('.metabolite-circle')
.on('mouseover.combine', null)
.on('mouseout.combine', null);
// clear the timeout
window.clearTimeout(the_timeout);
// clear the shared variables
total_displacement = null;
node_ids_to_drag = null;
text_label_ids_to_drag = null;
reaction_ids = null;
the_timeout = null;
});
return behavior;
// definitions
function combine_nodes_and_draw(fixed_node_id, dragged_node_id) {
var dragged_node = map.nodes[dragged_node_id],
fixed_node = map.nodes[fixed_node_id],
updated_segment_objs = [];
dragged_node.connected_segments.forEach(function(segment_obj) {
// change the segments to reflect
var segment;
try {
segment = map.reactions[segment_obj.reaction_id].segments[segment_obj.segment_id];
if (segment === undefined) throw new Error('undefined segment');
} catch (e) {
console.warn('Could not find connected segment ' + segment_obj.segment_id);
return;
}
if (segment.from_node_id==dragged_node_id) segment.from_node_id = fixed_node_id;
else if (segment.to_node_id==dragged_node_id) segment.to_node_id = fixed_node_id;
else {
console.error('Segment does not connect to dragged node');
return;
}
// moved segment_obj to fixed_node
fixed_node.connected_segments.push(segment_obj);
updated_segment_objs.push(utils.clone(segment_obj));
return;
});
// delete the old node
map.delete_node_data([dragged_node_id]);
// turn off the class
map.sel.selectAll('.node-to-combine').classed('node-to-combine', false);
// draw
map.draw_everything();
// return for undo
return updated_segment_objs;
}
}
function _get_bezier_drag(map) {
var move_bezier = function(reaction_id, segment_id, bez, bezier_id, displacement) {
var segment = map.reactions[reaction_id].segments[segment_id];
segment[bez] = utils.c_plus_c(segment[bez], displacement);
map.beziers[bezier_id].x = segment[bez].x;
map.beziers[bezier_id].y = segment[bez].y;
},
start_fn = function(d) {
d.dragging = true;
},
drag_fn = function(d, displacement, total_displacement) {
// draw
move_bezier(d.reaction_id, d.segment_id, d.bezier, d.bezier_id,
displacement);
map.draw_these_reactions([d.reaction_id], false);
map.draw_these_beziers([d.bezier_id]);
},
end_fn = function(d) {
d.dragging = false;
},
undo_fn = function(d, displacement) {
move_bezier(d.reaction_id, d.segment_id, d.bezier, d.bezier_id,
utils.c_times_scalar(displacement, -1));
map.draw_these_reactions([d.reaction_id], false);
map.draw_these_beziers([d.bezier_id]);
},
redo_fn = function(d, displacement) {
move_bezier(d.reaction_id, d.segment_id, d.bezier, d.bezier_id,
displacement);
map.draw_these_reactions([d.reaction_id], false);
map.draw_these_beziers([d.bezier_id]);
};
return this._get_generic_drag(start_fn, drag_fn, end_fn, undo_fn,
redo_fn, this.map.sel);
}
function _get_reaction_label_drag(map) {
var move_label = function(reaction_id, displacement) {
var reaction = map.reactions[reaction_id];
reaction.label_x = reaction.label_x + displacement.x;
reaction.label_y = reaction.label_y + displacement.y;
},
start_fn = function(d) {
},
drag_fn = function(d, displacement, total_displacement) {
// draw
move_label(d.reaction_id, displacement);
map.draw_these_reactions([d.reaction_id]);
},
end_fn = function(d) {
},
undo_fn = function(d, displacement) {
move_label(d.reaction_id, utils.c_times_scalar(displacement, -1));
map.draw_these_reactions([d.reaction_id]);
},
redo_fn = function(d, displacement) {
move_label(d.reaction_id, displacement);
map.draw_these_reactions([d.reaction_id]);
};
return this._get_generic_drag(start_fn, drag_fn, end_fn, undo_fn,
redo_fn, this.map.sel);
}
function _get_node_label_drag(map) {
var move_label = function(node_id, displacement) {
var node = map.nodes[node_id];
node.label_x = node.label_x + displacement.x;
node.label_y = node.label_y + displacement.y;
},
start_fn = function(d) {
},
drag_fn = function(d, displacement, total_displacement) {
// draw
move_label(d.node_id, displacement);
map.draw_these_nodes([d.node_id]);
},
end_fn = function(d) {
},
undo_fn = function(d, displacement) {
move_label(d.node_id, utils.c_times_scalar(displacement, -1));
map.draw_these_nodes([d.node_id]);
},
redo_fn = function(d, displacement) {
move_label(d.node_id, displacement);
map.draw_these_nodes([d.node_id]);
};
return this._get_generic_drag(start_fn, drag_fn, end_fn, undo_fn,
redo_fn, this.map.sel);
}
function _get_generic_drag(start_fn, drag_fn, end_fn, undo_fn, redo_fn, relative_to_selection) {
/** Make a generic drag behavior, with undo/redo.
start_fn: function(d) Called at dragstart.
drag_fn: function(d, displacement, total_displacement) Called during
drag.
end_fn
undo_fn
redo_fn
relative_to_selection: a d3 selection that the locations are calculated against.
*/
// define some variables
var behavior = d3.behavior.drag(),
total_displacement,
undo_stack = this.undo_stack,
rel = relative_to_selection.node();
behavior.on("dragstart", function (d) {
// silence other listeners
d3.event.sourceEvent.stopPropagation();
total_displacement = { x: 0, y: 0 };
start_fn(d);
});
behavior.on("drag", function(d) {
// update data
var displacement = { x: d3.event.dx,
y: d3.event.dy },
location = { x: d3.mouse(rel)[0],
y: d3.mouse(rel)[1] };
// remember the displacement
total_displacement = utils.c_plus_c(total_displacement, displacement);
drag_fn(d, displacement, total_displacement, location);
});
behavior.on("dragend", function(d) {
// add to undo/redo stack
// remember the displacement, dragged nodes, and reactions
var saved_d = utils.clone(d),
saved_displacement = utils.clone(total_displacement), // BUG TODO this variable disappears!
saved_location = { x: d3.mouse(rel)[0],
y: d3.mouse(rel)[1] };
undo_stack.push(function() {
// undo
undo_fn(saved_d, saved_displacement, saved_location);
}, function () {
// redo
redo_fn(saved_d, saved_displacement, saved_location);
});
end_fn(d);
});
return behavior;
}
function _get_generic_angular_drag(start_fn, drag_fn, end_fn, undo_fn, redo_fn,
get_center, relative_to_selection) {
/** Make a generic drag behavior, with undo/redo. Supplies angles in
place of displacements.
start_fn: function(d) Called at dragstart.
drag_fn: function(d, displacement, total_displacement) Called during
drag.
end_fn:
undo_fn:
redo_fn:
get_center:
relative_to_selection: a d3 selection that the locations are calculated against.
*/
// define some variables
var behavior = d3.behavior.drag(),
total_angle,
undo_stack = this.undo_stack,
rel = relative_to_selection.node();
behavior.on("dragstart", function (d) {
// silence other listeners
d3.event.sourceEvent.stopPropagation();
total_angle = 0;
start_fn(d);
});
behavior.on("drag", function(d) {
// update data
var displacement = { x: d3.event.dx,
y: d3.event.dy },
location = { x: d3.mouse(rel)[0],
y: d3.mouse(rel)[1] },
center = get_center(),
angle = utils.angle_for_event(displacement,
location,
center);
// remember the displacement
total_angle = total_angle + angle;
drag_fn(d, angle, total_angle, center);
});
behavior.on("dragend", function(d) {
// add to undo/redo stack
// remember the displacement, dragged nodes, and reactions
var saved_d = utils.clone(d),
saved_angle = total_angle,
saved_center = utils.clone(get_center());
undo_stack.push(function() {
// undo
undo_fn(saved_d, saved_angle, saved_center);
}, function () {
// redo
redo_fn(saved_d, saved_angle, saved_center);
});
end_fn(d);
});
return behavior;
}
});
define('Scale',["utils"], function(utils) {
/**
*/
var Scale = utils.make_class();
Scale.prototype = { init: init,
connect_to_settings: connect_to_settings };
return Scale;
// definitions
function init() {
this.x = d3.scale.linear();
this.y = d3.scale.linear();
this.x_size = d3.scale.linear();
this.y_size = d3.scale.linear();
this.size = d3.scale.linear();
this.reaction_color = d3.scale.linear().clamp(true);
this.reaction_size = d3.scale.linear().clamp(true);
this.metabolite_color = d3.scale.linear().clamp(true);
this.metabolite_size = d3.scale.linear().clamp(true);
this.scale_path = function(path) {
var x_fn = this.x, y_fn = this.y;
// TODO: scale arrow width
var str = d3.format(".2f"),
path = path.replace(/(M|L)([0-9-.]+),?\s*([0-9-.]+)/g, function (match, p0, p1, p2) {
return p0 + [str(x_fn(parseFloat(p1))), str(y_fn(parseFloat(p2)))].join(', ');
}),
reg = /C([0-9-.]+),?\s*([0-9-.]+)\s*([0-9-.]+),?\s*([0-9-.]+)\s*([0-9-.]+),?\s*([0-9-.]+)/g;
path = path.replace(reg, function (match, p1, p2, p3, p4, p5, p6) {
return 'C'+str(x_fn(parseFloat(p1)))+','+
str(y_fn(parseFloat(p2)))+' '+
str(x_fn(parseFloat(p3)))+','+
str(y_fn(parseFloat(p4)))+' '+
[str(x_fn(parseFloat(p5)))+','+str(y_fn(parseFloat(p6)))];
});
return path;
}.bind(this);
this.scale_decimals = function(path, scale_fn, precision) {
var str = d3.format("."+String(precision)+"f");
path = path.replace(/([0-9.]+)/g, function (match, p1) {
return str(scale_fn(parseFloat(p1)));
});
return path;
};
}
function connect_to_settings(settings, map, get_data_statistics) {
// domains
var update_reaction = function(s) {
var out = sort_scale(s, get_data_statistics()['reaction']);
this.reaction_color.domain(out.domain);
this.reaction_size.domain(out.domain);
this.reaction_color.range(out.color_range);
this.reaction_size.range(out.size_range);
}.bind(this);
var update_metabolite = function(s) {
var out = sort_scale(s, get_data_statistics()['metabolite']);
this.metabolite_color.domain(out.domain);
this.metabolite_size.domain(out.domain);
this.metabolite_color.range(out.color_range);
this.metabolite_size.range(out.size_range);
}.bind(this);
// scale changes
settings.streams['reaction_scale'].onValue(update_reaction);
settings.streams['metabolite_scale'].onValue(update_metabolite);
// stats changes
map.callback_manager.set('calc_data_stats__reaction', function(changed) {
if (changed) update_reaction(settings.get_option('reaction_scale'));
});
map.callback_manager.set('calc_data_stats__metabolite', function(changed) {
if (changed) update_metabolite(settings.get_option('metabolite_scale'));
});
// definitions
function sort_scale(scale, stats) {
var sorted = scale.map(function(x) {
var v;
if (x.type in stats)
v = stats[x.type];
else if (x.type == 'value')
v = x.value;
else
throw new Error('Bad domain type ' + x.type);
return { v: v,
color: x.color,
size: x.size };
}).sort(function(a, b) {
return a.v - b.v;
});
return { domain: sorted.map(function(x) { return x.v; }),
color_range: sorted.map(function(x) { return x.color; }),
size_range: sorted.map(function(x) { return x.size; }) };
}
}
});
define('UndoStack',["utils"], function(utils) {
/** UndoStack returns a constructor that can be used to store undo info.
*/
var UndoStack = utils.make_class();
UndoStack.prototype = { init: init,
push: push,
undo: undo,
redo: redo };
return UndoStack;
// definitions
function init() {
var stack_size = 40;
this.stack = Array(stack_size);
this.current = -1;
this.oldest = -1;
this.newest = -1;
this.end_of_stack = true;
this.top_of_stack = true;
}
function push(undo_fn, redo_fn) {
this.current = incr(this.current, this.stack.length);
// var p2 = incr(p1, this.stack.length);
// change the oldest
if (this.end_of_stack)
this.oldest = this.current;
else if (this.oldest == this.current)
this.oldest = incr(this.oldest, this.stack.length);
this.stack[this.current] = { undo: undo_fn, redo: redo_fn };
this.newest = this.current;
// top of the stack
this.top_of_stack = true;
this.end_of_stack = false;
}
function undo() {
// check that we haven't reached the end
if (this.end_of_stack) return console.warn('End of stack.');
// run the lastest stack function
this.stack[this.current].undo();
if (this.current == this.oldest) {
// if the next index is less than the oldest, then the stack is dead
this.end_of_stack = true;
} else {
// reference the next fn
this.current = decr(this.current, this.stack.length);
}
// not at the top of the stack
this.top_of_stack = false;
}
function redo() {
// check that we haven't reached the end
if (this.top_of_stack) return console.warn('Top of stack.');
if (!this.end_of_stack)
this.current = incr(this.current, this.stack.length);
this.stack[this.current].redo();
// if at top of stack
if (this.current == this.newest)
this.top_of_stack = true;
// not at the end of the stack
this.end_of_stack = false;
}
function incr(a, l) {
return a + 1 > l - 1 ? 0 : a + 1;
}
function decr(a, l) {
return a - 1 < 0 ? l - 1 : a - 1;
}
});
define('KeyManager',['utils'], function(utils) {
/**
*/
var KeyManager = utils.make_class();
// static methods
KeyManager.reset_held_keys = reset_held_keys;
// instance methods
KeyManager.prototype = { init: init,
update: update,
toggle: toggle,
add_escape_listener: add_escape_listener,
add_enter_listener: add_enter_listener,
add_key_listener: add_key_listener };
return KeyManager;
// static methods
function reset_held_keys(h) {
h.command = false;
h.control = false;
h.option = false;
h.shift = false;
}
// instance methods
function init(unique_map_id, assigned_keys, input_list, ctrl_equals_cmd) {
/** Assign keys for commands.
*/
// identify this key manager
if (unique_map_id===undefined) unique_map_id = null;
this.unique_string = (unique_map_id === null ? '' : '.' + unique_map_id);
if (assigned_keys===undefined) this.assigned_keys = {};
else this.assigned_keys = assigned_keys;
if (input_list===undefined) this.input_list = [];
else this.input_list = input_list;
if (ctrl_equals_cmd===undefined) ctrl_equals_cmd = true;
this.ctrl_equals_cmd = ctrl_equals_cmd;
this.held_keys = {};
reset_held_keys(this.held_keys);
this.enabled = true;
this.update();
}
function update() {
var held_keys = this.held_keys,
keys = this.assigned_keys,
self = this;
var modifier_keys = { command: 91,
command_right: 93,
control: 17,
option: 18,
shift: 16 };
d3.select(window).on('keydown.key_manager' + this.unique_string, null);
d3.select(window).on('keyup.key_manager' + this.unique_string, null);
if (!(this.enabled)) return;
d3.select(window).on('keydown.key_manager' + this.unique_string, function(ctrl_equals_cmd, input_list) {
var kc = d3.event.keyCode,
meaningless = true;
// check the inputs
var input_visible = false;
input_list.forEach(function(input) {
if (input.is_visible()) input_visible = true;
});
toggle_modifiers(modifier_keys, held_keys, kc, true);
for (var key_id in keys) {
var assigned_key = keys[key_id];
if (check_key(assigned_key, kc, held_keys, ctrl_equals_cmd)) {
meaningless = false;
if (!(assigned_key.ignore_with_input && input_visible)) {
if (assigned_key.fn) {
assigned_key.fn.call(assigned_key.target);
} else {
console.warn('No function for key');
}
// prevent browser action
d3.event.preventDefault();
}
}
}
// Sometimes modifiers get 'stuck', so reset them once in a while.
// Only do this when a meaningless key is pressed
for (var k in modifier_keys)
if (modifier_keys[k] == kc) meaningless = false;
if (meaningless)
reset_held_keys(held_keys);
}.bind(null, this.ctrl_equals_cmd, this.input_list))
.on('keyup.key_manager' + this.unique_string, function() {
toggle_modifiers(modifier_keys, held_keys,
d3.event.keyCode, false);
});
function toggle_modifiers(mod, held, kc, on_off) {
for (var k in mod)
if (mod[k] == kc)
held[k] = on_off;
}
function check_key(key, pressed, held, ctrl_equals_cmd) {
if (key.key != pressed) return false;
var mod = utils.clone(key.modifiers);
if (mod === undefined)
mod = { control: false,
command: false,
option: false,
shift: false };
for (var k in held) {
if (ctrl_equals_cmd &&
mod['control'] &&
(k=='command' || k=='command_right' || k=='control') &&
(held['command'] || held['command_right'] || held['control'])) {
continue;
}
if (mod[k] === undefined) mod[k] = false;
if (mod[k] != held[k]) return false;
}
return true;
}
}
function toggle(on_off) {
/** Turn the brush on or off
*/
if (on_off===undefined) on_off = !this.enabled;
this.enabled = on_off;
this.update();
}
function add_enter_listener(callback, id) {
/** Call the callback when the enter key is pressed, then
unregisters the listener.
*/
return this.add_key_listener(callback, 13, id);
}
function add_escape_listener(callback, id) {
/** Call the callback when the escape key is pressed, then
unregisters the listener.
*/
return this.add_key_listener(callback, 27, id);
}
function add_key_listener(callback, kc, id) {
/** Call the callback when the key is pressed, then unregisters the
listener.
*/
var event_name = 'keydown.' + kc;
if (id !== undefined)
event_name += ('.' + id);
event_name += this.unique_string;
var selection = d3.select(window);
selection.on(event_name, function() {
if (d3.event.keyCode==kc) {
callback();
}
});
return {
clear: function() {
selection.on(event_name, null);
}
};
}
});
define('Canvas',["utils", "CallbackManager"], function(utils, CallbackManager) {
/** Defines a canvas that accepts drag/zoom events and can be resized.
Canvas(selection, x, y, width, height)
Adapted from http://bl.ocks.org/mccannf/1629464.
*/
var Canvas = utils.make_class();
Canvas.prototype = { init: init,
toggle_resize: toggle_resize,
setup: setup,
size_and_location: size_and_location };
return Canvas;
function init(selection, size_and_location) {
this.selection = selection;
this.x = size_and_location.x;
this.y = size_and_location.y;
this.width = size_and_location.width;
this.height = size_and_location.height;
// enable by default
this.resize_enabled = true;
// set up the callbacks
this.callback_manager = new CallbackManager();
this.setup();
}
function toggle_resize(on_off) {
/** Turn the resize on or off
*/
if (on_off===undefined) on_off = !this.resize_enabled;
if (on_off) {
this.selection.selectAll('.drag-rect')
.style('pointer-events', 'auto');
} else {
this.selection.selectAll('.drag-rect')
.style('pointer-events', 'none');
}
}
function setup() {
var self = this,
extent = {"x": this.width, "y": this.height},
dragbar_width = 100,
mouse_node_mult = 10,
new_sel = this.selection.append('g')
.classed('canvas-group', true)
.data([{x: this.x, y: this.y}]);
var mouse_node = new_sel.append('rect')
.attr('id', 'mouse-node')
.attr("width", this.width*mouse_node_mult)
.attr("height", this.height*mouse_node_mult)
.attr("transform", "translate("+[self.x - this.width*mouse_node_mult/2,
self.y - this.height*mouse_node_mult/2]+")")
.attr('pointer-events', 'all');
this.mouse_node = mouse_node;
var rect = new_sel.append('rect')
.attr('id', 'canvas')
.attr("width", this.width)
.attr("height", this.height)
.attr("transform", "translate("+[self.x, self.y]+")");
var drag_right = d3.behavior.drag()
.origin(Object)
.on("dragstart", stop_propagation)
.on("drag", rdragresize),
drag_left = d3.behavior.drag()
.origin(Object)
.on("dragstart", stop_propagation)
.on("drag", ldragresize),
drag_top = d3.behavior.drag()
.origin(Object)
.on("dragstart", stop_propagation)
.on("drag", tdragresize),
drag_bottom = d3.behavior.drag()
.origin(Object)
.on("dragstart", stop_propagation)
.on("drag", bdragresize);
var left = new_sel.append("rect")
.classed('drag-rect', true)
.attr('transform', function(d) {
return 'translate('+[ d.x - (dragbar_width/2),
d.y + (dragbar_width/2) ]+')';
})
.attr("height", this.height - dragbar_width)
.attr("id", "dragleft")
.attr("width", dragbar_width)
.attr("cursor", "ew-resize")
.classed('resize-rect', true)
.call(drag_left);
var right = new_sel.append("rect")
.classed('drag-rect', true)
.attr('transform', function(d) {
return 'translate('+[ d.x + self.width - (dragbar_width/2),
d.y + (dragbar_width/2) ]+')';
})
.attr("id", "dragright")
.attr("height", this.height - dragbar_width)
.attr("width", dragbar_width)
.attr("cursor", "ew-resize")
.classed('resize-rect', true)
.call(drag_right);
var top = new_sel.append("rect")
.classed('drag-rect', true)
.attr('transform', function(d) {
return 'translate('+[ d.x + (dragbar_width/2),
d.y - (dragbar_width/2) ]+')';
})
.attr("height", dragbar_width)
.attr("id", "dragtop")
.attr("width", this.width - dragbar_width)
.attr("cursor", "ns-resize")
.classed('resize-rect', true)
.call(drag_top);
var bottom = new_sel.append("rect")
.classed('drag-rect', true)
.attr('transform', function(d) {
return 'translate('+[ d.x + (dragbar_width/2),
d.y + self.height - (dragbar_width/2) ]+')';
})
.attr("id", "dragbottom")
.attr("height", dragbar_width)
.attr("width", this.width - dragbar_width)
.attr("cursor", "ns-resize")
.classed('resize-rect', true)
.call(drag_bottom);
// definitions
function stop_propagation() {
d3.event.sourceEvent.stopPropagation();
}
function transform_string(x, y, current_transform) {
var tr = d3.transform(current_transform),
translate = tr.translate;
if (x!==null) translate[0] = x;
if (y!==null) translate[1] = y;
return 'translate('+translate+')';
}
function ldragresize(d) {
var oldx = d.x;
d.x = Math.min(d.x + self.width - (dragbar_width / 2), d3.event.x);
self.x = d.x;
self.width = self.width + (oldx - d.x);
left.attr("transform", function(d) {
return transform_string(d.x - (dragbar_width / 2), null, left.attr('transform'));
});
mouse_node.attr("transform", function(d) {
return transform_string(d.x, null, mouse_node.attr('transform'));
}).attr("width", self.width*mouse_node_mult);
rect.attr("transform", function(d) {
return transform_string(d.x, null, rect.attr('transform'));
}).attr("width", self.width);
top.attr("transform", function(d) {
return transform_string(d.x + (dragbar_width/2), null, top.attr('transform'));
}).attr("width", self.width - dragbar_width);
bottom.attr("transform", function(d) {
return transform_string(d.x + (dragbar_width/2), null, bottom.attr('transform'));
}).attr("width", self.width - dragbar_width);
self.callback_manager.run('resize');
}
function rdragresize(d) {
d3.event.sourceEvent.stopPropagation();
var dragx = Math.max(d.x + (dragbar_width/2), d.x + self.width + d3.event.dx);
//recalculate width
self.width = dragx - d.x;
//move the right drag handle
right.attr("transform", function(d) {
return transform_string(dragx - (dragbar_width/2), null, right.attr('transform'));
});
//resize the drag rectangle
//as we are only resizing from the right, the x coordinate does not need to change
mouse_node.attr("width", self.width*mouse_node_mult);
rect.attr("width", self.width);
top.attr("width", self.width - dragbar_width);
bottom.attr("width", self.width - dragbar_width);
self.callback_manager.run('resize');
}
function tdragresize(d) {
d3.event.sourceEvent.stopPropagation();
var oldy = d.y;
d.y = Math.min(d.y + self.height - (dragbar_width / 2), d3.event.y);
self.y = d.y;
self.height = self.height + (oldy - d.y);
top.attr("transform", function(d) {
return transform_string(null, d.y - (dragbar_width / 2), top.attr('transform'));
});
mouse_node.attr("transform", function(d) {
return transform_string(null, d.y, mouse_node.attr('transform'));
}).attr("width", self.height*mouse_node_mult);
rect.attr("transform", function(d) {
return transform_string(null, d.y, rect.attr('transform'));
}).attr("height", self.height);
left.attr("transform", function(d) {
return transform_string(null, d.y + (dragbar_width/2), left.attr('transform'));
}).attr("height", self.height - dragbar_width);
right.attr("transform", function(d) {
return transform_string(null, d.y + (dragbar_width/2), right.attr('transform'));
}).attr("height", self.height - dragbar_width);
self.callback_manager.run('resize');
}
function bdragresize(d) {
d3.event.sourceEvent.stopPropagation();
var dragy = Math.max(d.y + (dragbar_width/2), d.y + self.height + d3.event.dy);
//recalculate width
self.height = dragy - d.y;
//move the right drag handle
bottom.attr("transform", function(d) {
return transform_string(null, dragy - (dragbar_width/2), bottom.attr('transform'));
});
//resize the drag rectangle
//as we are only resizing from the right, the x coordinate does not need to change
mouse_node.attr("height", self.height*mouse_node_mult);
rect.attr("height", self.height);
left.attr("height", self.height - dragbar_width);
right.attr("height", self.height - dragbar_width);
self.callback_manager.run('resize');
}
}
function size_and_location() {
return { x: this.x,
y: this.y,
width: this.width,
height: this.height };
}
});
define('SearchIndex',["utils"], function(utils) {
/** Define an index for searching for reaction and metabolites in the map.
The index is stored in SearchIndex.index, an object of id/record pairs.
*/
var SearchIndex = utils.make_class();
SearchIndex.prototype = { init: init,
insert: insert,
remove: remove,
find: find };
return SearchIndex;
// definitions
function init() {
this.index = {};
}
function insert(id, record, overwrite, check_record) {
/** Insert a record into the index.
id: A unique string id.
record: Records have the form:
{ 'name': '',
'data': {} }
Search is performed on substrings of the name.
overwrite: (Default false) For faster performance, make overwrite true,
and records will be inserted without checking for an existing record.
check_record: (Default false) For faster performance, make check_record
false. If true, records will be checked to make sure they have name and
data attributes.
Returns undefined.
*/
if (!overwrite && (id in this.index))
throw new Error("id is already in the index");
if (check_record && !(('name' in record) && ('data' in record)))
throw new Error("malformed record");
this.index[id] = record;
}
function remove(record_id) {
/** Remove the matching record.
Returns true is a record is found, or false if no match is found.
*/
if (record_id in this.index) {
delete this.index[record_id];
return true;
} else {
return false;
}
}
function find(substring) {
/** Find a record that matches the substring.
Returns an array of data from matching records.
*/
var re = RegExp(substring, "i"), // ignore case
matches = [];
for (var id in this.index) {
var record = this.index[id];
if (re.exec(record.name))
matches.push(record.data);
}
return matches;
}
});
(function() {
var Bacon, BufferingSource, Bus, CompositeUnsubscribe, ConsumingSource, Desc, Dispatcher, End, Error, Event, EventStream, Initial, Next, None, Observable, Property, PropertyDispatcher, Some, Source, UpdateBarrier, addPropertyInitValueToStream, assert, assertArray, assertEventStream, assertFunction, assertNoArguments, assertString, cloneArray, compositeUnsubscribe, containsDuplicateDeps, convertArgsToFunction, describe, end, eventIdCounter, flatMap_, former, idCounter, initial, isArray, isFieldKey, isFunction, isObservable, latterF, liftCallback, makeFunction, makeFunctionArgs, makeFunction_, makeObservable, makeSpawner, next, nop, partiallyApplied, recursionDepth, registerObs, spys, toCombinator, toEvent, toFieldExtractor, toFieldKey, toOption, toSimpleExtractor, withDescription, withMethodCallSupport, _, _ref,
__slice = [].slice,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
Bacon = {
toString: function() {
return "Bacon";
}
};
Bacon.version = '0.7.12';
Bacon.fromBinder = function(binder, eventTransformer) {
if (eventTransformer == null) {
eventTransformer = _.id;
}
return new EventStream(describe(Bacon, "fromBinder", binder, eventTransformer), function(sink) {
var unbinder;
return unbinder = binder(function() {
var args, event, reply, value, _i, _len;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
value = eventTransformer.apply(null, args);
if (!(isArray(value) && _.last(value) instanceof Event)) {
value = [value];
}
reply = Bacon.more;
for (_i = 0, _len = value.length; _i < _len; _i++) {
event = value[_i];
reply = sink(event = toEvent(event));
if (reply === Bacon.noMore || event.isEnd()) {
if (unbinder != null) {
unbinder();
} else {
Bacon.scheduler.setTimeout((function() {
return unbinder();
}), 0);
}
return reply;
}
}
return reply;
});
});
};
Bacon.$ = {
asEventStream: function(eventName, selector, eventTransformer) {
var _ref;
if (isFunction(selector)) {
_ref = [selector, null], eventTransformer = _ref[0], selector = _ref[1];
}
return withDescription(this.selector || this, "asEventStream", eventName, Bacon.fromBinder((function(_this) {
return function(handler) {
_this.on(eventName, selector, handler);
return function() {
return _this.off(eventName, selector, handler);
};
};
})(this), eventTransformer));
}
};
if ((_ref = typeof jQuery !== "undefined" && jQuery !== null ? jQuery : typeof Zepto !== "undefined" && Zepto !== null ? Zepto : null) != null) {
_ref.fn.asEventStream = Bacon.$.asEventStream;
}
Bacon.fromEventTarget = function(target, eventName, eventTransformer) {
var sub, unsub, _ref1, _ref2, _ref3, _ref4;
sub = (_ref1 = target.addEventListener) != null ? _ref1 : (_ref2 = target.addListener) != null ? _ref2 : target.bind;
unsub = (_ref3 = target.removeEventListener) != null ? _ref3 : (_ref4 = target.removeListener) != null ? _ref4 : target.unbind;
return withDescription(Bacon, "fromEventTarget", target, eventName, Bacon.fromBinder(function(handler) {
sub.call(target, eventName, handler);
return function() {
return unsub.call(target, eventName, handler);
};
}, eventTransformer));
};
Bacon.fromPromise = function(promise, abort) {
return withDescription(Bacon, "fromPromise", promise, Bacon.fromBinder(function(handler) {
promise.then(handler, function(e) {
return handler(new Error(e));
});
return function() {
if (abort) {
return typeof promise.abort === "function" ? promise.abort() : void 0;
}
};
}, (function(value) {
return [value, end()];
})));
};
Bacon.noMore = ["<no-more>"];
Bacon.more = ["<more>"];
Bacon.later = function(delay, value) {
return withDescription(Bacon, "later", delay, value, Bacon.sequentially(delay, [value]));
};
Bacon.sequentially = function(delay, values) {
var index;
index = 0;
return withDescription(Bacon, "sequentially", delay, values, Bacon.fromPoll(delay, function() {
var value;
value = values[index++];
if (index < values.length) {
return value;
} else if (index === values.length) {
return [value, end()];
} else {
return end();
}
}));
};
Bacon.repeatedly = function(delay, values) {
var index;
index = 0;
return withDescription(Bacon, "repeatedly", delay, values, Bacon.fromPoll(delay, function() {
return values[index++ % values.length];
}));
};
Bacon.spy = function(spy) {
return spys.push(spy);
};
spys = [];
registerObs = function(obs) {
var spy, _i, _len, _results;
if (spys.length) {
if (!registerObs.running) {
try {
registerObs.running = true;
_results = [];
for (_i = 0, _len = spys.length; _i < _len; _i++) {
spy = spys[_i];
_results.push(spy(obs));
}
return _results;
} finally {
delete registerObs.running;
}
}
}
};
withMethodCallSupport = function(wrapped) {
return function() {
var args, context, f, methodName;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (typeof f === "object" && args.length) {
context = f;
methodName = args[0];
f = function() {
return context[methodName].apply(context, arguments);
};
args = args.slice(1);
}
return wrapped.apply(null, [f].concat(__slice.call(args)));
};
};
liftCallback = function(desc, wrapped) {
return withMethodCallSupport(function() {
var args, f, stream;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
stream = partiallyApplied(wrapped, [
function(values, callback) {
return f.apply(null, __slice.call(values).concat([callback]));
}
]);
return withDescription.apply(null, [Bacon, desc, f].concat(__slice.call(args), [Bacon.combineAsArray(args).flatMap(stream)]));
});
};
Bacon.fromCallback = liftCallback("fromCallback", function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return Bacon.fromBinder(function(handler) {
makeFunction(f, args)(handler);
return nop;
}, (function(value) {
return [value, end()];
}));
});
Bacon.fromNodeCallback = liftCallback("fromNodeCallback", function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return Bacon.fromBinder(function(handler) {
makeFunction(f, args)(handler);
return nop;
}, function(error, value) {
if (error) {
return [new Error(error), end()];
}
return [value, end()];
});
});
Bacon.fromPoll = function(delay, poll) {
return withDescription(Bacon, "fromPoll", delay, poll, Bacon.fromBinder((function(handler) {
var id;
id = Bacon.scheduler.setInterval(handler, delay);
return function() {
return Bacon.scheduler.clearInterval(id);
};
}), poll));
};
Bacon.interval = function(delay, value) {
if (value == null) {
value = {};
}
return withDescription(Bacon, "interval", delay, value, Bacon.fromPoll(delay, function() {
return next(value);
}));
};
Bacon.constant = function(value) {
return new Property(describe(Bacon, "constant", value), function(sink) {
sink(initial(value));
sink(end());
return nop;
});
};
Bacon.never = function() {
return withDescription(Bacon, "never", Bacon.fromArray([]));
};
Bacon.once = function(value) {
return withDescription(Bacon, "once", value, Bacon.fromArray([value]));
};
Bacon.fromArray = function(values) {
assertArray(values);
values = cloneArray(values);
return new EventStream(describe(Bacon, "fromArray", values), function(sink) {
var send, unsubd;
unsubd = false;
send = function() {
var reply, value;
if (_.empty(values)) {
return sink(end());
} else {
value = values.splice(0, 1)[0];
reply = sink(toEvent(value));
if ((reply !== Bacon.noMore) && !unsubd) {
return send();
}
}
};
send();
return function() {
return unsubd = true;
};
});
};
Bacon.mergeAll = function() {
var streams;
streams = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (isArray(streams[0])) {
streams = streams[0];
}
if (streams.length) {
return new EventStream(describe.apply(null, [Bacon, "mergeAll"].concat(__slice.call(streams))), function(sink) {
var ends, sinks, smartSink;
ends = 0;
smartSink = function(obs) {
return function(unsubBoth) {
return obs.subscribeInternal(function(event) {
var reply;
if (event.isEnd()) {
ends++;
if (ends === streams.length) {
return sink(end());
} else {
return Bacon.more;
}
} else {
reply = sink(event);
if (reply === Bacon.noMore) {
unsubBoth();
}
return reply;
}
});
};
};
sinks = _.map(smartSink, streams);
return compositeUnsubscribe.apply(null, sinks);
});
} else {
return Bacon.never();
}
};
Bacon.zipAsArray = function() {
var streams;
streams = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (isArray(streams[0])) {
streams = streams[0];
}
return withDescription.apply(null, [Bacon, "zipAsArray"].concat(__slice.call(streams), [Bacon.zipWith(streams, function() {
var xs;
xs = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return xs;
})]));
};
Bacon.zipWith = function() {
var f, streams, _ref1;
f = arguments[0], streams = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (!isFunction(f)) {
_ref1 = [f, streams[0]], streams = _ref1[0], f = _ref1[1];
}
streams = _.map((function(s) {
return s.toEventStream();
}), streams);
return withDescription.apply(null, [Bacon, "zipWith", f].concat(__slice.call(streams), [Bacon.when(streams, f)]));
};
Bacon.groupSimultaneous = function() {
var s, sources, streams;
streams = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (streams.length === 1 && isArray(streams[0])) {
streams = streams[0];
}
sources = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = streams.length; _i < _len; _i++) {
s = streams[_i];
_results.push(new BufferingSource(s));
}
return _results;
})();
return withDescription.apply(null, [Bacon, "groupSimultaneous"].concat(__slice.call(streams), [Bacon.when(sources, (function() {
var xs;
xs = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return xs;
}))]));
};
Bacon.combineAsArray = function() {
var index, s, sources, stream, streams, _i, _len;
streams = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (streams.length === 1 && isArray(streams[0])) {
streams = streams[0];
}
for (index = _i = 0, _len = streams.length; _i < _len; index = ++_i) {
stream = streams[index];
if (!(isObservable(stream))) {
streams[index] = Bacon.constant(stream);
}
}
if (streams.length) {
sources = (function() {
var _j, _len1, _results;
_results = [];
for (_j = 0, _len1 = streams.length; _j < _len1; _j++) {
s = streams[_j];
_results.push(new Source(s, true, s.subscribeInternal));
}
return _results;
})();
return withDescription.apply(null, [Bacon, "combineAsArray"].concat(__slice.call(streams), [Bacon.when(sources, (function() {
var xs;
xs = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return xs;
})).toProperty()]));
} else {
return Bacon.constant([]);
}
};
Bacon.onValues = function() {
var f, streams, _i;
streams = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), f = arguments[_i++];
return Bacon.combineAsArray(streams).onValues(f);
};
Bacon.combineWith = function() {
var f, streams;
f = arguments[0], streams = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return withDescription.apply(null, [Bacon, "combineWith", f].concat(__slice.call(streams), [Bacon.combineAsArray(streams).map(function(values) {
return f.apply(null, values);
})]));
};
Bacon.combineTemplate = function(template) {
var applyStreamValue, combinator, compile, compileTemplate, constantValue, current, funcs, mkContext, setValue, streams;
funcs = [];
streams = [];
current = function(ctxStack) {
return ctxStack[ctxStack.length - 1];
};
setValue = function(ctxStack, key, value) {
return current(ctxStack)[key] = value;
};
applyStreamValue = function(key, index) {
return function(ctxStack, values) {
return setValue(ctxStack, key, values[index]);
};
};
constantValue = function(key, value) {
return function(ctxStack) {
return setValue(ctxStack, key, value);
};
};
mkContext = function(template) {
if (isArray(template)) {
return [];
} else {
return {};
}
};
compile = function(key, value) {
var popContext, pushContext;
if (isObservable(value)) {
streams.push(value);
return funcs.push(applyStreamValue(key, streams.length - 1));
} else if (value === Object(value) && typeof value !== "function" && !(value instanceof RegExp) && !(value instanceof Date)) {
pushContext = function(key) {
return function(ctxStack) {
var newContext;
newContext = mkContext(value);
setValue(ctxStack, key, newContext);
return ctxStack.push(newContext);
};
};
popContext = function(ctxStack) {
return ctxStack.pop();
};
funcs.push(pushContext(key));
compileTemplate(value);
return funcs.push(popContext);
} else {
return funcs.push(constantValue(key, value));
}
};
compileTemplate = function(template) {
return _.each(template, compile);
};
compileTemplate(template);
combinator = function(values) {
var ctxStack, f, rootContext, _i, _len;
rootContext = mkContext(template);
ctxStack = [rootContext];
for (_i = 0, _len = funcs.length; _i < _len; _i++) {
f = funcs[_i];
f(ctxStack, values);
}
return rootContext;
};
return withDescription(Bacon, "combineTemplate", template, Bacon.combineAsArray(streams).map(combinator));
};
Bacon.retry = function(options) {
var interval, isRetryable, maxRetries, retries, retry, source;
if (!isFunction(options.source)) {
throw "'source' option has to be a function";
}
source = options.source;
retries = options.retries || 0;
maxRetries = options.maxRetries || retries;
interval = options.interval || function() {
return 0;
};
isRetryable = options.isRetryable || function() {
return true;
};
retry = function(context) {
var nextAttemptOptions;
nextAttemptOptions = {
source: source,
retries: retries - 1,
maxRetries: maxRetries,
interval: interval,
isRetryable: isRetryable
};
return Bacon.later(interval(context)).filter(false).concat(Bacon.retry(nextAttemptOptions));
};
return withDescription(Bacon, "retry", options, source().flatMapError(function(e) {
if (isRetryable(e) && retries > 0) {
return retry({
error: e,
retriesDone: maxRetries - retries
});
} else {
return Bacon.once(new Bacon.Error(e));
}
}));
};
eventIdCounter = 0;
Event = (function() {
function Event() {
this.id = ++eventIdCounter;
}
Event.prototype.isEvent = function() {
return true;
};
Event.prototype.isEnd = function() {
return false;
};
Event.prototype.isInitial = function() {
return false;
};
Event.prototype.isNext = function() {
return false;
};
Event.prototype.isError = function() {
return false;
};
Event.prototype.hasValue = function() {
return false;
};
Event.prototype.filter = function() {
return true;
};
Event.prototype.inspect = function() {
return this.toString();
};
Event.prototype.log = function() {
return this.toString();
};
return Event;
})();
Next = (function(_super) {
__extends(Next, _super);
function Next(valueF) {
Next.__super__.constructor.call(this);
if (isFunction(valueF)) {
this.value = _.cached(valueF);
} else {
this.value = _.always(valueF);
}
}
Next.prototype.isNext = function() {
return true;
};
Next.prototype.hasValue = function() {
return true;
};
Next.prototype.fmap = function(f) {
var value;
value = this.value;
return this.apply(function() {
return f(value());
});
};
Next.prototype.apply = function(value) {
return new Next(value);
};
Next.prototype.filter = function(f) {
return f(this.value());
};
Next.prototype.toString = function() {
return _.toString(this.value());
};
Next.prototype.log = function() {
return this.value();
};
return Next;
})(Event);
Initial = (function(_super) {
__extends(Initial, _super);
function Initial() {
return Initial.__super__.constructor.apply(this, arguments);
}
Initial.prototype.isInitial = function() {
return true;
};
Initial.prototype.isNext = function() {
return false;
};
Initial.prototype.apply = function(value) {
return new Initial(value);
};
Initial.prototype.toNext = function() {
return new Next(this.value);
};
return Initial;
})(Next);
End = (function(_super) {
__extends(End, _super);
function End() {
return End.__super__.constructor.apply(this, arguments);
}
End.prototype.isEnd = function() {
return true;
};
End.prototype.fmap = function() {
return this;
};
End.prototype.apply = function() {
return this;
};
End.prototype.toString = function() {
return "<end>";
};
return End;
})(Event);
Error = (function(_super) {
__extends(Error, _super);
function Error(error) {
this.error = error;
}
Error.prototype.isError = function() {
return true;
};
Error.prototype.fmap = function() {
return this;
};
Error.prototype.apply = function() {
return this;
};
Error.prototype.toString = function() {
return "<error> " + _.toString(this.error);
};
return Error;
})(Event);
idCounter = 0;
Observable = (function() {
function Observable(desc) {
this.flatMapError = __bind(this.flatMapError, this);
this.id = ++idCounter;
withDescription(desc, this);
}
Observable.prototype.onValue = function() {
var f;
f = makeFunctionArgs(arguments);
return this.subscribe(function(event) {
if (event.hasValue()) {
return f(event.value());
}
});
};
Observable.prototype.onValues = function(f) {
return this.onValue(function(args) {
return f.apply(null, args);
});
};
Observable.prototype.onError = function() {
var f;
f = makeFunctionArgs(arguments);
return this.subscribe(function(event) {
if (event.isError()) {
return f(event.error);
}
});
};
Observable.prototype.onEnd = function() {
var f;
f = makeFunctionArgs(arguments);
return this.subscribe(function(event) {
if (event.isEnd()) {
return f();
}
});
};
Observable.prototype.errors = function() {
return withDescription(this, "errors", this.filter(function() {
return false;
}));
};
Observable.prototype.filter = function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return convertArgsToFunction(this, f, args, function(f) {
return withDescription(this, "filter", f, this.withHandler(function(event) {
if (event.filter(f)) {
return this.push(event);
} else {
return Bacon.more;
}
}));
});
};
Observable.prototype.takeWhile = function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return convertArgsToFunction(this, f, args, function(f) {
return withDescription(this, "takeWhile", f, this.withHandler(function(event) {
if (event.filter(f)) {
return this.push(event);
} else {
this.push(end());
return Bacon.noMore;
}
}));
});
};
Observable.prototype.endOnError = function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (f == null) {
f = true;
}
return convertArgsToFunction(this, f, args, function(f) {
return withDescription(this, "endOnError", this.withHandler(function(event) {
if (event.isError() && f(event.error)) {
this.push(event);
return this.push(end());
} else {
return this.push(event);
}
}));
});
};
Observable.prototype.take = function(count) {
if (count <= 0) {
return Bacon.never();
}
return withDescription(this, "take", count, this.withHandler(function(event) {
if (!event.hasValue()) {
return this.push(event);
} else {
count--;
if (count > 0) {
return this.push(event);
} else {
if (count === 0) {
this.push(event);
}
this.push(end());
return Bacon.noMore;
}
}
}));
};
Observable.prototype.map = function() {
var args, p;
p = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (p instanceof Property) {
return p.sampledBy(this, former);
} else {
return convertArgsToFunction(this, p, args, function(f) {
return withDescription(this, "map", f, this.withHandler(function(event) {
return this.push(event.fmap(f));
}));
});
}
};
Observable.prototype.mapError = function() {
var f;
f = makeFunctionArgs(arguments);
return withDescription(this, "mapError", f, this.withHandler(function(event) {
if (event.isError()) {
return this.push(next(f(event.error)));
} else {
return this.push(event);
}
}));
};
Observable.prototype.mapEnd = function() {
var f;
f = makeFunctionArgs(arguments);
return withDescription(this, "mapEnd", f, this.withHandler(function(event) {
if (event.isEnd()) {
this.push(next(f(event)));
this.push(end());
return Bacon.noMore;
} else {
return this.push(event);
}
}));
};
Observable.prototype.doAction = function() {
var f;
f = makeFunctionArgs(arguments);
return withDescription(this, "doAction", f, this.withHandler(function(event) {
if (event.hasValue()) {
f(event.value());
}
return this.push(event);
}));
};
Observable.prototype.skip = function(count) {
return withDescription(this, "skip", count, this.withHandler(function(event) {
if (!event.hasValue()) {
return this.push(event);
} else if (count > 0) {
count--;
return Bacon.more;
} else {
return this.push(event);
}
}));
};
Observable.prototype.skipDuplicates = function(isEqual) {
if (isEqual == null) {
isEqual = function(a, b) {
return a === b;
};
}
return withDescription(this, "skipDuplicates", this.withStateMachine(None, function(prev, event) {
if (!event.hasValue()) {
return [prev, [event]];
} else if (event.isInitial() || prev === None || !isEqual(prev.get(), event.value())) {
return [new Some(event.value()), [event]];
} else {
return [prev, []];
}
}));
};
Observable.prototype.skipErrors = function() {
return withDescription(this, "skipErrors", this.withHandler(function(event) {
if (event.isError()) {
return Bacon.more;
} else {
return this.push(event);
}
}));
};
Observable.prototype.withStateMachine = function(initState, f) {
var state;
state = initState;
return withDescription(this, "withStateMachine", initState, f, this.withHandler(function(event) {
var fromF, newState, output, outputs, reply, _i, _len;
fromF = f(state, event);
newState = fromF[0], outputs = fromF[1];
state = newState;
reply = Bacon.more;
for (_i = 0, _len = outputs.length; _i < _len; _i++) {
output = outputs[_i];
reply = this.push(output);
if (reply === Bacon.noMore) {
return reply;
}
}
return reply;
}));
};
Observable.prototype.scan = function(seed, f, lazyF) {
var acc, f_, resultProperty, subscribe;
f_ = toCombinator(f);
f = lazyF ? f_ : function(x, y) {
return f_(x(), y());
};
acc = toOption(seed).map(function(x) {
return _.always(x);
});
subscribe = (function(_this) {
return function(sink) {
var initSent, reply, sendInit, unsub;
initSent = false;
unsub = nop;
reply = Bacon.more;
sendInit = function() {
if (!initSent) {
return acc.forEach(function(valueF) {
initSent = true;
reply = sink(new Initial(valueF));
if (reply === Bacon.noMore) {
unsub();
return unsub = nop;
}
});
}
};
unsub = _this.subscribeInternal(function(event) {
var next, prev;
if (event.hasValue()) {
if (initSent && event.isInitial()) {
return Bacon.more;
} else {
if (!event.isInitial()) {
sendInit();
}
initSent = true;
prev = acc.getOrElse(function() {
return void 0;
});
next = _.cached(function() {
return f(prev, event.value);
});
acc = new Some(next);
return sink(event.apply(next));
}
} else {
if (event.isEnd()) {
reply = sendInit();
}
if (reply !== Bacon.noMore) {
return sink(event);
}
}
});
UpdateBarrier.whenDoneWith(resultProperty, sendInit);
return unsub;
};
})(this);
return resultProperty = new Property(describe(this, "scan", seed, f), subscribe);
};
Observable.prototype.fold = function(seed, f) {
return withDescription(this, "fold", seed, f, this.scan(seed, f).sampledBy(this.filter(false).mapEnd().toProperty()));
};
Observable.prototype.zip = function(other, f) {
if (f == null) {
f = Array;
}
return withDescription(this, "zip", other, Bacon.zipWith([this, other], f));
};
Observable.prototype.diff = function(start, f) {
f = toCombinator(f);
return withDescription(this, "diff", start, f, this.scan([start], function(prevTuple, next) {
return [next, f(prevTuple[0], next)];
}).filter(function(tuple) {
return tuple.length === 2;
}).map(function(tuple) {
return tuple[1];
}));
};
Observable.prototype.flatMap = function() {
return flatMap_(this, makeSpawner(arguments));
};
Observable.prototype.flatMapFirst = function() {
return flatMap_(this, makeSpawner(arguments), true);
};
Observable.prototype.flatMapLatest = function() {
var f, stream;
f = makeSpawner(arguments);
stream = this.toEventStream();
return withDescription(this, "flatMapLatest", f, stream.flatMap(function(value) {
return makeObservable(f(value)).takeUntil(stream);
}));
};
Observable.prototype.flatMapError = function(fn) {
return withDescription(this, "flatMapError", fn, this.mapError(function(err) {
return new Bacon.Error(err);
}).flatMap(function(x) {
if (x instanceof Bacon.Error) {
return fn(x.error);
} else {
return Bacon.once(x);
}
}));
};
Observable.prototype.not = function() {
return withDescription(this, "not", this.map(function(x) {
return !x;
}));
};
Observable.prototype.log = function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
this.subscribe(function(event) {
return typeof console !== "undefined" && console !== null ? typeof console.log === "function" ? console.log.apply(console, __slice.call(args).concat([event.log()])) : void 0 : void 0;
});
return this;
};
Observable.prototype.slidingWindow = function(n, minValues) {
if (minValues == null) {
minValues = 0;
}
return withDescription(this, "slidingWindow", n, minValues, this.scan([], (function(window, value) {
return window.concat([value]).slice(-n);
})).filter((function(values) {
return values.length >= minValues;
})));
};
Observable.prototype.combine = function(other, f) {
var combinator;
combinator = toCombinator(f);
return withDescription(this, "combine", other, f, Bacon.combineAsArray(this, other).map(function(values) {
return combinator(values[0], values[1]);
}));
};
Observable.prototype.decode = function(cases) {
return withDescription(this, "decode", cases, this.combine(Bacon.combineTemplate(cases), function(key, values) {
return values[key];
}));
};
Observable.prototype.awaiting = function(other) {
return withDescription(this, "awaiting", other, Bacon.groupSimultaneous(this, other).map(function(_arg) {
var myValues, otherValues;
myValues = _arg[0], otherValues = _arg[1];
return otherValues.length === 0;
}).toProperty(false).skipDuplicates());
};
Observable.prototype.name = function(name) {
this.toString = function() {
return name;
};
return this;
};
Observable.prototype.withDescription = function() {
return describe.apply(null, arguments).apply(this);
};
return Observable;
})();
Observable.prototype.reduce = Observable.prototype.fold;
Observable.prototype.assign = Observable.prototype.onValue;
flatMap_ = function(root, f, firstOnly) {
return new EventStream(describe(root, "flatMap" + (firstOnly ? "First" : ""), f), function(sink) {
var checkEnd, composite;
composite = new CompositeUnsubscribe();
checkEnd = function(unsub) {
unsub();
if (composite.empty()) {
return sink(end());
}
};
composite.add(function(__, unsubRoot) {
return root.subscribeInternal(function(event) {
var child;
if (event.isEnd()) {
return checkEnd(unsubRoot);
} else if (event.isError()) {
return sink(event);
} else if (firstOnly && composite.count() > 1) {
return Bacon.more;
} else {
if (composite.unsubscribed) {
return Bacon.noMore;
}
child = makeObservable(f(event.value()));
return composite.add(function(unsubAll, unsubMe) {
return child.subscribeInternal(function(event) {
var reply;
if (event.isEnd()) {
checkEnd(unsubMe);
return Bacon.noMore;
} else {
if (event instanceof Initial) {
event = event.toNext();
}
reply = sink(event);
if (reply === Bacon.noMore) {
unsubAll();
}
return reply;
}
});
});
}
});
});
return composite.unsubscribe;
});
};
EventStream = (function(_super) {
__extends(EventStream, _super);
function EventStream(desc, subscribe) {
var dispatcher;
if (isFunction(desc)) {
subscribe = desc;
desc = [];
}
EventStream.__super__.constructor.call(this, desc);
assertFunction(subscribe);
dispatcher = new Dispatcher(subscribe);
this.subscribeInternal = dispatcher.subscribe;
this.subscribe = UpdateBarrier.wrappedSubscribe(this);
this.hasSubscribers = dispatcher.hasSubscribers;
registerObs(this);
}
EventStream.prototype.delay = function(delay) {
return withDescription(this, "delay", delay, this.flatMap(function(value) {
return Bacon.later(delay, value);
}));
};
EventStream.prototype.debounce = function(delay) {
return withDescription(this, "debounce", delay, this.flatMapLatest(function(value) {
return Bacon.later(delay, value);
}));
};
EventStream.prototype.debounceImmediate = function(delay) {
return withDescription(this, "debounceImmediate", delay, this.flatMapFirst(function(value) {
return Bacon.once(value).concat(Bacon.later(delay).filter(false));
}));
};
EventStream.prototype.throttle = function(delay) {
return withDescription(this, "throttle", delay, this.bufferWithTime(delay).map(function(values) {
return values[values.length - 1];
}));
};
EventStream.prototype.bufferWithTime = function(delay) {
return withDescription(this, "bufferWithTime", delay, this.bufferWithTimeOrCount(delay, Number.MAX_VALUE));
};
EventStream.prototype.bufferWithCount = function(count) {
return withDescription(this, "bufferWithCount", count, this.bufferWithTimeOrCount(void 0, count));
};
EventStream.prototype.bufferWithTimeOrCount = function(delay, count) {
var flushOrSchedule;
flushOrSchedule = function(buffer) {
if (buffer.values.length === count) {
return buffer.flush();
} else if (delay !== void 0) {
return buffer.schedule();
}
};
return withDescription(this, "bufferWithTimeOrCount", delay, count, this.buffer(delay, flushOrSchedule, flushOrSchedule));
};
EventStream.prototype.buffer = function(delay, onInput, onFlush) {
var buffer, delayMs, reply;
if (onInput == null) {
onInput = (function() {});
}
if (onFlush == null) {
onFlush = (function() {});
}
buffer = {
scheduled: false,
end: null,
values: [],
flush: function() {
var reply;
this.scheduled = false;
if (this.values.length > 0) {
reply = this.push(next(this.values));
this.values = [];
if (this.end != null) {
return this.push(this.end);
} else if (reply !== Bacon.noMore) {
return onFlush(this);
}
} else {
if (this.end != null) {
return this.push(this.end);
}
}
},
schedule: function() {
if (!this.scheduled) {
this.scheduled = true;
return delay((function(_this) {
return function() {
return _this.flush();
};
})(this));
}
}
};
reply = Bacon.more;
if (!isFunction(delay)) {
delayMs = delay;
delay = function(f) {
return Bacon.scheduler.setTimeout(f, delayMs);
};
}
return withDescription(this, "buffer", this.withHandler(function(event) {
buffer.push = this.push;
if (event.isError()) {
reply = this.push(event);
} else if (event.isEnd()) {
buffer.end = event;
if (!buffer.scheduled) {
buffer.flush();
}
} else {
buffer.values.push(event.value());
onInput(buffer);
}
return reply;
}));
};
EventStream.prototype.merge = function(right) {
var left;
assertEventStream(right);
left = this;
return withDescription(left, "merge", right, Bacon.mergeAll(this, right));
};
EventStream.prototype.toProperty = function(initValue) {
if (arguments.length === 0) {
initValue = None;
}
return withDescription(this, "toProperty", initValue, this.scan(initValue, latterF, true));
};
EventStream.prototype.toEventStream = function() {
return this;
};
EventStream.prototype.sampledBy = function(sampler, combinator) {
return withDescription(this, "sampledBy", sampler, combinator, this.toProperty().sampledBy(sampler, combinator));
};
EventStream.prototype.concat = function(right) {
var left;
left = this;
return new EventStream(describe(left, "concat", right), function(sink) {
var unsubLeft, unsubRight;
unsubRight = nop;
unsubLeft = left.subscribeInternal(function(e) {
if (e.isEnd()) {
return unsubRight = right.subscribeInternal(sink);
} else {
return sink(e);
}
});
return function() {
unsubLeft();
return unsubRight();
};
});
};
EventStream.prototype.takeUntil = function(stopper) {
var endMarker;
endMarker = {};
return withDescription(this, "takeUntil", stopper, Bacon.groupSimultaneous(this.mapEnd(endMarker), stopper.skipErrors()).withHandler(function(event) {
var data, reply, value, _i, _len, _ref1;
if (!event.hasValue()) {
return this.push(event);
} else {
_ref1 = event.value(), data = _ref1[0], stopper = _ref1[1];
if (stopper.length) {
return this.push(end());
} else {
reply = Bacon.more;
for (_i = 0, _len = data.length; _i < _len; _i++) {
value = data[_i];
if (value === endMarker) {
reply = this.push(end());
} else {
reply = this.push(next(value));
}
}
return reply;
}
}
}));
};
EventStream.prototype.skipUntil = function(starter) {
var started;
started = starter.take(1).map(true).toProperty(false);
return withDescription(this, "skipUntil", starter, this.filter(started));
};
EventStream.prototype.skipWhile = function() {
var args, f, ok;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
ok = false;
return convertArgsToFunction(this, f, args, function(f) {
return withDescription(this, "skipWhile", f, this.withHandler(function(event) {
if (ok || !event.hasValue() || !f(event.value())) {
if (event.hasValue()) {
ok = true;
}
return this.push(event);
} else {
return Bacon.more;
}
}));
});
};
EventStream.prototype.startWith = function(seed) {
return withDescription(this, "startWith", seed, Bacon.once(seed).concat(this));
};
EventStream.prototype.withHandler = function(handler) {
var dispatcher;
dispatcher = new Dispatcher(this.subscribeInternal, handler);
return new EventStream(describe(this, "withHandler", handler), dispatcher.subscribe);
};
return EventStream;
})(Observable);
Property = (function(_super) {
__extends(Property, _super);
function Property(desc, subscribe, handler) {
if (isFunction(desc)) {
handler = subscribe;
subscribe = desc;
desc = [];
}
Property.__super__.constructor.call(this, desc);
assertFunction(subscribe);
if (handler === true) {
this.subscribeInternal = subscribe;
} else {
this.subscribeInternal = new PropertyDispatcher(this, subscribe, handler).subscribe;
}
this.subscribe = UpdateBarrier.wrappedSubscribe(this);
registerObs(this);
}
Property.prototype.sampledBy = function(sampler, combinator) {
var lazy, result, samplerSource, stream, thisSource;
if (combinator != null) {
combinator = toCombinator(combinator);
} else {
lazy = true;
combinator = function(f) {
return f();
};
}
thisSource = new Source(this, false, this.subscribeInternal, lazy);
samplerSource = new Source(sampler, true, sampler.subscribeInternal, lazy);
stream = Bacon.when([thisSource, samplerSource], combinator);
result = sampler instanceof Property ? stream.toProperty() : stream;
return withDescription(this, "sampledBy", sampler, combinator, result);
};
Property.prototype.sample = function(interval) {
return withDescription(this, "sample", interval, this.sampledBy(Bacon.interval(interval, {})));
};
Property.prototype.changes = function() {
return new EventStream(describe(this, "changes"), (function(_this) {
return function(sink) {
return _this.subscribeInternal(function(event) {
if (!event.isInitial()) {
return sink(event);
}
});
};
})(this));
};
Property.prototype.withHandler = function(handler) {
return new Property(describe(this, "withHandler", handler), this.subscribeInternal, handler);
};
Property.prototype.toProperty = function() {
assertNoArguments(arguments);
return this;
};
Property.prototype.toEventStream = function() {
return new EventStream(describe(this, "toEventStream"), (function(_this) {
return function(sink) {
return _this.subscribeInternal(function(event) {
if (event.isInitial()) {
event = event.toNext();
}
return sink(event);
});
};
})(this));
};
Property.prototype.and = function(other) {
return withDescription(this, "and", other, this.combine(other, function(x, y) {
return x && y;
}));
};
Property.prototype.or = function(other) {
return withDescription(this, "or", other, this.combine(other, function(x, y) {
return x || y;
}));
};
Property.prototype.delay = function(delay) {
return this.delayChanges("delay", delay, function(changes) {
return changes.delay(delay);
});
};
Property.prototype.debounce = function(delay) {
return this.delayChanges("debounce", delay, function(changes) {
return changes.debounce(delay);
});
};
Property.prototype.throttle = function(delay) {
return this.delayChanges("throttle", delay, function(changes) {
return changes.throttle(delay);
});
};
Property.prototype.delayChanges = function() {
var desc, f, _i;
desc = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), f = arguments[_i++];
return withDescription.apply(null, [this].concat(__slice.call(desc), [addPropertyInitValueToStream(this, f(this.changes()))]));
};
Property.prototype.takeUntil = function(stopper) {
var changes;
changes = this.changes().takeUntil(stopper);
return withDescription(this, "takeUntil", stopper, addPropertyInitValueToStream(this, changes));
};
Property.prototype.startWith = function(value) {
return withDescription(this, "startWith", value, this.scan(value, function(prev, next) {
return next;
}));
};
return Property;
})(Observable);
convertArgsToFunction = function(obs, f, args, method) {
var sampled;
if (f instanceof Property) {
sampled = f.sampledBy(obs, function(p, s) {
return [p, s];
});
return method.apply(sampled, [
function(_arg) {
var p, s;
p = _arg[0], s = _arg[1];
return p;
}
]).map(function(_arg) {
var p, s;
p = _arg[0], s = _arg[1];
return s;
});
} else {
f = makeFunction(f, args);
return method.apply(obs, [f]);
}
};
addPropertyInitValueToStream = function(property, stream) {
var justInitValue;
justInitValue = new EventStream(describe(property, "justInitValue"), function(sink) {
var unsub, value;
value = null;
unsub = property.subscribeInternal(function(event) {
if (event.hasValue()) {
value = event;
}
return Bacon.noMore;
});
UpdateBarrier.whenDoneWith(justInitValue, function() {
if (value != null) {
sink(value);
}
return sink(end());
});
return unsub;
});
return justInitValue.concat(stream).toProperty();
};
Dispatcher = (function() {
function Dispatcher(subscribe, handleEvent) {
var done, ended, prevError, pushIt, pushing, queue, removeSub, subscriptions, unsubscribeFromSource, waiters;
if (subscribe == null) {
subscribe = function() {
return nop;
};
}
subscriptions = [];
queue = [];
pushing = false;
ended = false;
this.hasSubscribers = function() {
return subscriptions.length > 0;
};
prevError = null;
unsubscribeFromSource = nop;
removeSub = function(subscription) {
return subscriptions = _.without(subscription, subscriptions);
};
waiters = null;
done = function() {
var w, ws, _i, _len, _results;
if (waiters != null) {
ws = waiters;
waiters = null;
_results = [];
for (_i = 0, _len = ws.length; _i < _len; _i++) {
w = ws[_i];
_results.push(w());
}
return _results;
}
};
pushIt = function(event) {
var reply, sub, success, tmp, _i, _len;
if (!pushing) {
if (event === prevError) {
return;
}
if (event.isError()) {
prevError = event;
}
success = false;
try {
pushing = true;
tmp = subscriptions;
for (_i = 0, _len = tmp.length; _i < _len; _i++) {
sub = tmp[_i];
reply = sub.sink(event);
if (reply === Bacon.noMore || event.isEnd()) {
removeSub(sub);
}
}
success = true;
} finally {
pushing = false;
if (!success) {
queue = [];
}
}
success = true;
while (queue.length) {
event = queue.shift();
this.push(event);
}
done(event);
if (this.hasSubscribers()) {
return Bacon.more;
} else {
unsubscribeFromSource();
return Bacon.noMore;
}
} else {
queue.push(event);
return Bacon.more;
}
};
this.push = (function(_this) {
return function(event) {
return UpdateBarrier.inTransaction(event, _this, pushIt, [event]);
};
})(this);
if (handleEvent == null) {
handleEvent = function(event) {
return this.push(event);
};
}
this.handleEvent = (function(_this) {
return function(event) {
if (event.isEnd()) {
ended = true;
}
return handleEvent.apply(_this, [event]);
};
})(this);
this.subscribe = (function(_this) {
return function(sink) {
var subscription, unsubSrc;
if (ended) {
sink(end());
return nop;
} else {
assertFunction(sink);
subscription = {
sink: sink
};
subscriptions.push(subscription);
if (subscriptions.length === 1) {
unsubSrc = subscribe(_this.handleEvent);
unsubscribeFromSource = function() {
unsubSrc();
return unsubscribeFromSource = nop;
};
}
assertFunction(unsubscribeFromSource);
return function() {
removeSub(subscription);
if (!_this.hasSubscribers()) {
return unsubscribeFromSource();
}
};
}
};
})(this);
}
return Dispatcher;
})();
PropertyDispatcher = (function(_super) {
__extends(PropertyDispatcher, _super);
function PropertyDispatcher(p, subscribe, handleEvent) {
var current, currentValueRootId, ended, push;
PropertyDispatcher.__super__.constructor.call(this, subscribe, handleEvent);
current = None;
currentValueRootId = void 0;
push = this.push;
subscribe = this.subscribe;
ended = false;
this.push = (function(_this) {
return function(event) {
if (event.isEnd()) {
ended = true;
}
if (event.hasValue()) {
current = new Some(event);
currentValueRootId = UpdateBarrier.currentEventId();
}
return push.apply(_this, [event]);
};
})(this);
this.subscribe = (function(_this) {
return function(sink) {
var dispatchingId, initSent, maybeSubSource, reply, valId;
initSent = false;
reply = Bacon.more;
maybeSubSource = function() {
if (reply === Bacon.noMore) {
return nop;
} else if (ended) {
sink(end());
return nop;
} else {
return subscribe.apply(this, [sink]);
}
};
if (current.isDefined && (_this.hasSubscribers() || ended)) {
dispatchingId = UpdateBarrier.currentEventId();
valId = currentValueRootId;
if (!ended && valId && dispatchingId && dispatchingId !== valId) {
UpdateBarrier.whenDoneWith(p, function() {
if (currentValueRootId === valId) {
return sink(initial(current.get().value()));
}
});
return maybeSubSource();
} else {
UpdateBarrier.inTransaction(void 0, _this, (function() {
return reply = sink(initial(current.get().value()));
}), []);
return maybeSubSource();
}
} else {
return maybeSubSource();
}
};
})(this);
}
return PropertyDispatcher;
})(Dispatcher);
Bus = (function(_super) {
__extends(Bus, _super);
function Bus() {
var ended, guardedSink, sink, subscribeAll, subscribeInput, subscriptions, unsubAll, unsubscribeInput;
sink = void 0;
subscriptions = [];
ended = false;
guardedSink = (function(_this) {
return function(input) {
return function(event) {
if (event.isEnd()) {
unsubscribeInput(input);
return Bacon.noMore;
} else {
return sink(event);
}
};
};
})(this);
unsubAll = function() {
var sub, _i, _len, _results;
_results = [];
for (_i = 0, _len = subscriptions.length; _i < _len; _i++) {
sub = subscriptions[_i];
_results.push(typeof sub.unsub === "function" ? sub.unsub() : void 0);
}
return _results;
};
subscribeInput = function(subscription) {
return subscription.unsub = subscription.input.subscribeInternal(guardedSink(subscription.input));
};
unsubscribeInput = function(input) {
var i, sub, _i, _len;
for (i = _i = 0, _len = subscriptions.length; _i < _len; i = ++_i) {
sub = subscriptions[i];
if (sub.input === input) {
if (typeof sub.unsub === "function") {
sub.unsub();
}
subscriptions.splice(i, 1);
return;
}
}
};
subscribeAll = (function(_this) {
return function(newSink) {
var subscription, _i, _len, _ref1;
sink = newSink;
_ref1 = cloneArray(subscriptions);
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
subscription = _ref1[_i];
subscribeInput(subscription);
}
return unsubAll;
};
})(this);
Bus.__super__.constructor.call(this, describe(Bacon, "Bus"), subscribeAll);
this.plug = (function(_this) {
return function(input) {
var sub;
if (ended) {
return;
}
sub = {
input: input
};
subscriptions.push(sub);
if ((sink != null)) {
subscribeInput(sub);
}
return function() {
return unsubscribeInput(input);
};
};
})(this);
this.push = (function(_this) {
return function(value) {
return typeof sink === "function" ? sink(next(value)) : void 0;
};
})(this);
this.error = (function(_this) {
return function(error) {
return typeof sink === "function" ? sink(new Error(error)) : void 0;
};
})(this);
this.end = (function(_this) {
return function() {
ended = true;
unsubAll();
return typeof sink === "function" ? sink(end()) : void 0;
};
})(this);
}
return Bus;
})(EventStream);
Source = (function() {
function Source(obs, sync, subscribe, lazy) {
this.obs = obs;
this.sync = sync;
this.subscribe = subscribe;
this.lazy = lazy != null ? lazy : false;
this.queue = [];
if (this.subscribe == null) {
this.subscribe = this.obs.subscribeInternal;
}
this.toString = this.obs.toString;
}
Source.prototype.markEnded = function() {
return this.ended = true;
};
Source.prototype.consume = function() {
if (this.lazy) {
return _.always(this.queue[0]);
} else {
return this.queue[0];
}
};
Source.prototype.push = function(x) {
return this.queue = [x];
};
Source.prototype.mayHave = function() {
return true;
};
Source.prototype.hasAtLeast = function() {
return this.queue.length;
};
Source.prototype.flatten = true;
return Source;
})();
ConsumingSource = (function(_super) {
__extends(ConsumingSource, _super);
function ConsumingSource() {
return ConsumingSource.__super__.constructor.apply(this, arguments);
}
ConsumingSource.prototype.consume = function() {
return this.queue.shift();
};
ConsumingSource.prototype.push = function(x) {
return this.queue.push(x);
};
ConsumingSource.prototype.mayHave = function(c) {
return !this.ended || this.queue.length >= c;
};
ConsumingSource.prototype.hasAtLeast = function(c) {
return this.queue.length >= c;
};
ConsumingSource.prototype.flatten = false;
return ConsumingSource;
})(Source);
BufferingSource = (function(_super) {
__extends(BufferingSource, _super);
function BufferingSource(obs) {
this.obs = obs;
BufferingSource.__super__.constructor.call(this, this.obs, true, this.obs.subscribeInternal);
}
BufferingSource.prototype.consume = function() {
var values;
values = this.queue;
this.queue = [];
return function() {
return values;
};
};
BufferingSource.prototype.push = function(x) {
return this.queue.push(x());
};
BufferingSource.prototype.hasAtLeast = function() {
return true;
};
return BufferingSource;
})(Source);
Source.isTrigger = function(s) {
if (s instanceof Source) {
return s.sync;
} else {
return s instanceof EventStream;
}
};
Source.fromObservable = function(s) {
if (s instanceof Source) {
return s;
} else if (s instanceof Property) {
return new Source(s, false);
} else {
return new ConsumingSource(s, true);
}
};
describe = function() {
var args, context, method;
context = arguments[0], method = arguments[1], args = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
if ((context || method) instanceof Desc) {
return context || method;
} else {
return new Desc(context, method, args);
}
};
Desc = (function() {
function Desc(context, method, args) {
var collectDeps, dependsOn, findDeps, flatDeps;
findDeps = function(x) {
if (isArray(x)) {
return _.flatMap(findDeps, x);
} else if (isObservable(x)) {
return [x];
} else if (x instanceof Source) {
return [x.obs];
} else {
return [];
}
};
flatDeps = null;
collectDeps = function(o) {
var dep, deps, _i, _len, _results;
deps = o.internalDeps();
_results = [];
for (_i = 0, _len = deps.length; _i < _len; _i++) {
dep = deps[_i];
flatDeps[dep.id] = true;
_results.push(collectDeps(dep));
}
return _results;
};
dependsOn = function(b) {
if (flatDeps == null) {
flatDeps = {};
collectDeps(this);
}
return flatDeps[b.id];
};
this.apply = function(obs) {
var deps;
deps = _.cached((function() {
return findDeps([context].concat(args));
}));
obs.internalDeps = obs.internalDeps || deps;
obs.dependsOn = dependsOn;
obs.deps = deps;
obs.toString = function() {
return _.toString(context) + "." + _.toString(method) + "(" + _.map(_.toString, args) + ")";
};
obs.inspect = function() {
return obs.toString();
};
obs.desc = function() {
return {
context: context,
method: method,
args: args
};
};
return obs;
};
}
return Desc;
})();
withDescription = function() {
var desc, obs, _i;
desc = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), obs = arguments[_i++];
return describe.apply(null, desc).apply(obs);
};
Bacon.when = function() {
var f, i, index, ix, len, needsBarrier, pat, patSources, pats, patterns, resultStream, s, sources, triggerFound, usage, _i, _j, _len, _len1, _ref1;
patterns = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (patterns.length === 0) {
return Bacon.never();
}
len = patterns.length;
usage = "when: expecting arguments in the form (Observable+,function)+";
assert(usage, len % 2 === 0);
sources = [];
pats = [];
i = 0;
while (i < len) {
patSources = _.toArray(patterns[i]);
f = patterns[i + 1];
pat = {
f: (isFunction(f) ? f : (function() {
return f;
})),
ixs: []
};
triggerFound = false;
for (_i = 0, _len = patSources.length; _i < _len; _i++) {
s = patSources[_i];
index = _.indexOf(sources, s);
if (!triggerFound) {
triggerFound = Source.isTrigger(s);
}
if (index < 0) {
sources.push(s);
index = sources.length - 1;
}
_ref1 = pat.ixs;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
ix = _ref1[_j];
if (ix.index === index) {
ix.count++;
}
}
pat.ixs.push({
index: index,
count: 1
});
}
assert("At least one EventStream required", triggerFound || (!patSources.length));
if (patSources.length > 0) {
pats.push(pat);
}
i = i + 2;
}
if (!sources.length) {
return Bacon.never();
}
sources = _.map(Source.fromObservable, sources);
needsBarrier = (_.any(sources, function(s) {
return s.flatten;
})) && (containsDuplicateDeps(_.map((function(s) {
return s.obs;
}), sources)));
return resultStream = new EventStream(describe.apply(null, [Bacon, "when"].concat(__slice.call(patterns))), function(sink) {
var cannotMatch, cannotSync, ends, match, nonFlattened, part, triggers;
triggers = [];
ends = false;
match = function(p) {
var _k, _len2, _ref2;
_ref2 = p.ixs;
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
i = _ref2[_k];
if (!sources[i.index].hasAtLeast(i.count)) {
return false;
}
}
return true;
};
cannotSync = function(source) {
return !source.sync || source.ended;
};
cannotMatch = function(p) {
var _k, _len2, _ref2;
_ref2 = p.ixs;
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
i = _ref2[_k];
if (!sources[i.index].mayHave(i.count)) {
return true;
}
}
};
nonFlattened = function(trigger) {
return !trigger.source.flatten;
};
part = function(source) {
return function(unsubAll) {
var flush, flushLater, flushWhileTriggers;
flushLater = function() {
return UpdateBarrier.whenDoneWith(resultStream, flush);
};
flushWhileTriggers = function() {
var functions, p, reply, trigger, _k, _len2;
if (triggers.length > 0) {
reply = Bacon.more;
trigger = triggers.pop();
for (_k = 0, _len2 = pats.length; _k < _len2; _k++) {
p = pats[_k];
if (match(p)) {
functions = (function() {
var _l, _len3, _ref2, _results;
_ref2 = p.ixs;
_results = [];
for (_l = 0, _len3 = _ref2.length; _l < _len3; _l++) {
i = _ref2[_l];
_results.push(sources[i.index].consume());
}
return _results;
})();
reply = sink(trigger.e.apply(function() {
var fun, values;
values = (function() {
var _l, _len3, _results;
_results = [];
for (_l = 0, _len3 = functions.length; _l < _len3; _l++) {
fun = functions[_l];
_results.push(fun());
}
return _results;
})();
return p.f.apply(p, values);
}));
if (triggers.length && needsBarrier) {
triggers = _.filter(nonFlattened, triggers);
}
if (reply === Bacon.noMore) {
return reply;
} else {
return flushWhileTriggers();
}
}
}
} else {
return Bacon.more;
}
};
flush = function() {
var reply;
reply = flushWhileTriggers();
if (ends) {
ends = false;
if (_.all(sources, cannotSync) || _.all(pats, cannotMatch)) {
reply = Bacon.noMore;
sink(end());
}
}
if (reply === Bacon.noMore) {
unsubAll();
}
return reply;
};
return source.subscribe(function(e) {
var reply;
if (e.isEnd()) {
ends = true;
source.markEnded();
flushLater();
} else if (e.isError()) {
reply = sink(e);
} else {
source.push(e.value);
if (source.sync) {
triggers.push({
source: source,
e: e
});
if (needsBarrier) {
flushLater();
} else {
flush();
}
}
}
if (reply === Bacon.noMore) {
unsubAll();
}
return reply || Bacon.more;
});
};
};
return compositeUnsubscribe.apply(null, (function() {
var _k, _len2, _results;
_results = [];
for (_k = 0, _len2 = sources.length; _k < _len2; _k++) {
s = sources[_k];
_results.push(part(s));
}
return _results;
})());
});
};
containsDuplicateDeps = function(observables, state) {
var checkObservable;
if (state == null) {
state = [];
}
checkObservable = function(obs) {
var deps;
if (Bacon._.contains(state, obs)) {
return true;
} else {
deps = obs.internalDeps();
if (deps.length) {
state.push(obs);
return Bacon._.any(deps, checkObservable);
} else {
state.push(obs);
return false;
}
}
};
return Bacon._.any(observables, checkObservable);
};
Bacon.update = function() {
var i, initial, lateBindFirst, patterns;
initial = arguments[0], patterns = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
lateBindFirst = function(f) {
return function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return function(i) {
return f.apply(null, [i].concat(args));
};
};
};
i = patterns.length - 1;
while (i > 0) {
if (!(patterns[i] instanceof Function)) {
patterns[i] = (function(x) {
return function() {
return x;
};
})(patterns[i]);
}
patterns[i] = lateBindFirst(patterns[i]);
i = i - 2;
}
return withDescription.apply(null, [Bacon, "update", initial].concat(__slice.call(patterns), [Bacon.when.apply(Bacon, patterns).scan(initial, (function(x, f) {
return f(x);
}))]));
};
compositeUnsubscribe = function() {
var ss;
ss = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return new CompositeUnsubscribe(ss).unsubscribe;
};
CompositeUnsubscribe = (function() {
function CompositeUnsubscribe(ss) {
var s, _i, _len;
if (ss == null) {
ss = [];
}
this.unsubscribe = __bind(this.unsubscribe, this);
this.unsubscribed = false;
this.subscriptions = [];
this.starting = [];
for (_i = 0, _len = ss.length; _i < _len; _i++) {
s = ss[_i];
this.add(s);
}
}
CompositeUnsubscribe.prototype.add = function(subscription) {
var ended, unsub, unsubMe;
if (this.unsubscribed) {
return;
}
ended = false;
unsub = nop;
this.starting.push(subscription);
unsubMe = (function(_this) {
return function() {
if (_this.unsubscribed) {
return;
}
ended = true;
_this.remove(unsub);
return _.remove(subscription, _this.starting);
};
})(this);
unsub = subscription(this.unsubscribe, unsubMe);
if (!(this.unsubscribed || ended)) {
this.subscriptions.push(unsub);
}
_.remove(subscription, this.starting);
return unsub;
};
CompositeUnsubscribe.prototype.remove = function(unsub) {
if (this.unsubscribed) {
return;
}
if ((_.remove(unsub, this.subscriptions)) !== void 0) {
return unsub();
}
};
CompositeUnsubscribe.prototype.unsubscribe = function() {
var s, _i, _len, _ref1;
if (this.unsubscribed) {
return;
}
this.unsubscribed = true;
_ref1 = this.subscriptions;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
s = _ref1[_i];
s();
}
this.subscriptions = [];
return this.starting = [];
};
CompositeUnsubscribe.prototype.count = function() {
if (this.unsubscribed) {
return 0;
}
return this.subscriptions.length + this.starting.length;
};
CompositeUnsubscribe.prototype.empty = function() {
return this.count() === 0;
};
return CompositeUnsubscribe;
})();
Bacon.CompositeUnsubscribe = CompositeUnsubscribe;
Some = (function() {
function Some(value) {
this.value = value;
}
Some.prototype.getOrElse = function() {
return this.value;
};
Some.prototype.get = function() {
return this.value;
};
Some.prototype.filter = function(f) {
if (f(this.value)) {
return new Some(this.value);
} else {
return None;
}
};
Some.prototype.map = function(f) {
return new Some(f(this.value));
};
Some.prototype.forEach = function(f) {
return f(this.value);
};
Some.prototype.isDefined = true;
Some.prototype.toArray = function() {
return [this.value];
};
Some.prototype.inspect = function() {
return "Some(" + this.value + ")";
};
Some.prototype.toString = function() {
return this.inspect();
};
return Some;
})();
None = {
getOrElse: function(value) {
return value;
},
filter: function() {
return None;
},
map: function() {
return None;
},
forEach: function() {},
isDefined: false,
toArray: function() {
return [];
},
inspect: function() {
return "None";
},
toString: function() {
return this.inspect();
}
};
UpdateBarrier = (function() {
var afterTransaction, afters, currentEventId, findIndependent, flush, inTransaction, independent, rootEvent, waiters, whenDoneWith, wrappedSubscribe;
rootEvent = void 0;
waiters = [];
afters = [];
afterTransaction = function(f) {
if (rootEvent) {
return afters.push(f);
} else {
return f();
}
};
independent = function(waiter) {
return !_.any(waiters, (function(other) {
return waiter.obs.dependsOn(other.obs);
}));
};
whenDoneWith = function(obs, f) {
if (rootEvent) {
return waiters.push({
obs: obs,
f: f
});
} else {
return f();
}
};
findIndependent = function() {
while (!independent(waiters[0])) {
waiters.push(waiters.splice(0, 1)[0]);
}
return waiters.splice(0, 1)[0];
};
flush = function() {
var _results;
_results = [];
while (waiters.length) {
_results.push(findIndependent().f());
}
return _results;
};
inTransaction = function(event, context, f, args) {
var result;
if (rootEvent) {
return f.apply(context, args);
} else {
rootEvent = event;
try {
result = f.apply(context, args);
flush();
} finally {
rootEvent = void 0;
while (afters.length) {
f = afters.splice(0, 1)[0];
f();
}
}
return result;
}
};
currentEventId = function() {
if (rootEvent) {
return rootEvent.id;
} else {
return void 0;
}
};
wrappedSubscribe = function(obs) {
return function(sink) {
var doUnsub, unsub, unsubd;
unsubd = false;
doUnsub = function() {};
unsub = function() {
unsubd = true;
return doUnsub();
};
if (!unsubd) {
doUnsub = obs.subscribeInternal(function(event) {
return afterTransaction(function() {
var reply;
if (!unsubd) {
reply = sink(event);
if (reply === Bacon.noMore) {
return unsub();
}
}
});
});
}
return unsub;
};
};
return {
whenDoneWith: whenDoneWith,
inTransaction: inTransaction,
currentEventId: currentEventId,
wrappedSubscribe: wrappedSubscribe
};
})();
Bacon.EventStream = EventStream;
Bacon.Property = Property;
Bacon.Observable = Observable;
Bacon.Bus = Bus;
Bacon.Initial = Initial;
Bacon.Next = Next;
Bacon.End = End;
Bacon.Error = Error;
nop = function() {};
latterF = function(_, x) {
return x();
};
former = function(x, _) {
return x;
};
initial = function(value) {
return new Initial(_.always(value));
};
next = function(value) {
return new Next(_.always(value));
};
end = function() {
return new End();
};
toEvent = function(x) {
if (x instanceof Event) {
return x;
} else {
return next(x);
}
};
cloneArray = function(xs) {
return xs.slice(0);
};
assert = function(message, condition) {
if (!condition) {
throw message;
}
};
assertEventStream = function(event) {
if (!(event instanceof EventStream)) {
throw "not an EventStream : " + event;
}
};
assertFunction = function(f) {
return assert("not a function : " + f, isFunction(f));
};
isFunction = function(f) {
return typeof f === "function";
};
isArray = function(xs) {
return xs instanceof Array;
};
isObservable = function(x) {
return x instanceof Observable;
};
assertArray = function(xs) {
if (!isArray(xs)) {
throw "not an array : " + xs;
}
};
assertNoArguments = function(args) {
return assert("no arguments supported", args.length === 0);
};
assertString = function(x) {
if (typeof x !== "string") {
throw "not a string : " + x;
}
};
partiallyApplied = function(f, applied) {
return function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return f.apply(null, applied.concat(args));
};
};
makeSpawner = function(args) {
if (args.length === 1 && isObservable(args[0])) {
return _.always(args[0]);
} else {
return makeFunctionArgs(args);
}
};
makeFunctionArgs = function(args) {
args = Array.prototype.slice.call(args);
return makeFunction_.apply(null, args);
};
makeFunction_ = withMethodCallSupport(function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (isFunction(f)) {
if (args.length) {
return partiallyApplied(f, args);
} else {
return f;
}
} else if (isFieldKey(f)) {
return toFieldExtractor(f, args);
} else {
return _.always(f);
}
});
makeFunction = function(f, args) {
return makeFunction_.apply(null, [f].concat(__slice.call(args)));
};
makeObservable = function(x) {
if (isObservable(x)) {
return x;
} else {
return Bacon.once(x);
}
};
isFieldKey = function(f) {
return (typeof f === "string") && f.length > 1 && f.charAt(0) === ".";
};
Bacon.isFieldKey = isFieldKey;
toFieldExtractor = function(f, args) {
var partFuncs, parts;
parts = f.slice(1).split(".");
partFuncs = _.map(toSimpleExtractor(args), parts);
return function(value) {
var _i, _len;
for (_i = 0, _len = partFuncs.length; _i < _len; _i++) {
f = partFuncs[_i];
value = f(value);
}
return value;
};
};
toSimpleExtractor = function(args) {
return function(key) {
return function(value) {
var fieldValue;
if (value == null) {
return void 0;
} else {
fieldValue = value[key];
if (isFunction(fieldValue)) {
return fieldValue.apply(value, args);
} else {
return fieldValue;
}
}
};
};
};
toFieldKey = function(f) {
return f.slice(1);
};
toCombinator = function(f) {
var key;
if (isFunction(f)) {
return f;
} else if (isFieldKey(f)) {
key = toFieldKey(f);
return function(left, right) {
return left[key](right);
};
} else {
return assert("not a function or a field key: " + f, false);
}
};
toOption = function(v) {
if (v instanceof Some || v === None) {
return v;
} else {
return new Some(v);
}
};
_ = {
indexOf: Array.prototype.indexOf ? function(xs, x) {
return xs.indexOf(x);
} : function(xs, x) {
var i, y, _i, _len;
for (i = _i = 0, _len = xs.length; _i < _len; i = ++_i) {
y = xs[i];
if (x === y) {
return i;
}
}
return -1;
},
indexWhere: function(xs, f) {
var i, y, _i, _len;
for (i = _i = 0, _len = xs.length; _i < _len; i = ++_i) {
y = xs[i];
if (f(y)) {
return i;
}
}
return -1;
},
head: function(xs) {
return xs[0];
},
always: function(x) {
return function() {
return x;
};
},
negate: function(f) {
return function(x) {
return !f(x);
};
},
empty: function(xs) {
return xs.length === 0;
},
tail: function(xs) {
return xs.slice(1, xs.length);
},
filter: function(f, xs) {
var filtered, x, _i, _len;
filtered = [];
for (_i = 0, _len = xs.length; _i < _len; _i++) {
x = xs[_i];
if (f(x)) {
filtered.push(x);
}
}
return filtered;
},
map: function(f, xs) {
var x, _i, _len, _results;
_results = [];
for (_i = 0, _len = xs.length; _i < _len; _i++) {
x = xs[_i];
_results.push(f(x));
}
return _results;
},
each: function(xs, f) {
var key, value, _results;
_results = [];
for (key in xs) {
value = xs[key];
_results.push(f(key, value));
}
return _results;
},
toArray: function(xs) {
if (isArray(xs)) {
return xs;
} else {
return [xs];
}
},
contains: function(xs, x) {
return _.indexOf(xs, x) !== -1;
},
id: function(x) {
return x;
},
last: function(xs) {
return xs[xs.length - 1];
},
all: function(xs, f) {
var x, _i, _len;
if (f == null) {
f = _.id;
}
for (_i = 0, _len = xs.length; _i < _len; _i++) {
x = xs[_i];
if (!f(x)) {
return false;
}
}
return true;
},
any: function(xs, f) {
var x, _i, _len;
if (f == null) {
f = _.id;
}
for (_i = 0, _len = xs.length; _i < _len; _i++) {
x = xs[_i];
if (f(x)) {
return true;
}
}
return false;
},
without: function(x, xs) {
return _.filter((function(y) {
return y !== x;
}), xs);
},
remove: function(x, xs) {
var i;
i = _.indexOf(xs, x);
if (i >= 0) {
return xs.splice(i, 1);
}
},
fold: function(xs, seed, f) {
var x, _i, _len;
for (_i = 0, _len = xs.length; _i < _len; _i++) {
x = xs[_i];
seed = f(seed, x);
}
return seed;
},
flatMap: function(f, xs) {
return _.fold(xs, [], (function(ys, x) {
return ys.concat(f(x));
}));
},
cached: function(f) {
var value;
value = None;
return function() {
if (value === None) {
value = f();
f = null;
}
return value;
};
},
toString: function(obj) {
var ex, internals, key, value;
try {
recursionDepth++;
if (obj == null) {
return "undefined";
} else if (isFunction(obj)) {
return "function";
} else if (isArray(obj)) {
if (recursionDepth > 5) {
return "[..]";
}
return "[" + _.map(_.toString, obj).toString() + "]";
} else if (((obj != null ? obj.toString : void 0) != null) && obj.toString !== Object.prototype.toString) {
return obj.toString();
} else if (typeof obj === "object") {
if (recursionDepth > 5) {
return "{..}";
}
internals = (function() {
var _results;
_results = [];
for (key in obj) {
if (!__hasProp.call(obj, key)) continue;
value = (function() {
try {
return obj[key];
} catch (_error) {
ex = _error;
return ex;
}
})();
_results.push(_.toString(key) + ":" + _.toString(value));
}
return _results;
})();
return "{" + internals + "}";
} else {
return obj;
}
} finally {
recursionDepth--;
}
}
};
recursionDepth = 0;
Bacon._ = _;
Bacon.scheduler = {
setTimeout: function(f, d) {
return setTimeout(f, d);
},
setInterval: function(f, i) {
return setInterval(f, i);
},
clearInterval: function(id) {
return clearInterval(id);
},
now: function() {
return new Date().getTime();
}
};
if ((typeof define !== "undefined" && define !== null) && (define.amd != null)) {
define('lib/bacon',[], function() {
return Bacon;
});
this.Bacon = Bacon;
} else if (typeof module !== "undefined" && module !== null) {
module.exports = Bacon;
Bacon.Bacon = Bacon;
} else {
this.Bacon = Bacon;
}
}).call(this);
!function(a,b){"function"==typeof define&&define.amd?define('lib/tv4',[],b):"undefined"!=typeof module&&module.exports?module.exports=b():a.tv4=b()}(this,function(){function a(a){return encodeURI(a).replace(/%25[0-9][0-9]/g,function(a){return"%"+a.substring(3)})}function b(b){var c="";l[b.charAt(0)]&&(c=b.charAt(0),b=b.substring(1));var d="",e="",f=!0,g=!1,h=!1;"+"===c?f=!1:"."===c?(e=".",d="."):"/"===c?(e="/",d="/"):"#"===c?(e="#",f=!1):";"===c?(e=";",d=";",g=!0,h=!0):"?"===c?(e="?",d="&",g=!0):"&"===c&&(e="&",d="&",g=!0);for(var i=[],j=b.split(","),k=[],n={},o=0;o<j.length;o++){var p=j[o],q=null;if(-1!==p.indexOf(":")){var r=p.split(":");p=r[0],q=parseInt(r[1],10)}for(var s={};m[p.charAt(p.length-1)];)s[p.charAt(p.length-1)]=!0,p=p.substring(0,p.length-1);var t={truncate:q,name:p,suffices:s};k.push(t),n[p]=t,i.push(p)}var u=function(b){for(var c="",i=0,j=0;j<k.length;j++){var l=k[j],m=b(l.name);if(null===m||void 0===m||Array.isArray(m)&&0===m.length||"object"==typeof m&&0===Object.keys(m).length)i++;else if(c+=j===i?e:d||",",Array.isArray(m)){g&&(c+=l.name+"=");for(var n=0;n<m.length;n++)n>0&&(c+=l.suffices["*"]?d||",":",",l.suffices["*"]&&g&&(c+=l.name+"=")),c+=f?encodeURIComponent(m[n]).replace(/!/g,"%21"):a(m[n])}else if("object"==typeof m){g&&!l.suffices["*"]&&(c+=l.name+"=");var o=!0;for(var p in m)o||(c+=l.suffices["*"]?d||",":","),o=!1,c+=f?encodeURIComponent(p).replace(/!/g,"%21"):a(p),c+=l.suffices["*"]?"=":",",c+=f?encodeURIComponent(m[p]).replace(/!/g,"%21"):a(m[p])}else g&&(c+=l.name,h&&""===m||(c+="=")),null!=l.truncate&&(m=m.substring(0,l.truncate)),c+=f?encodeURIComponent(m).replace(/!/g,"%21"):a(m)}return c};return u.varNames=i,{prefix:e,substitution:u}}function c(a){if(!(this instanceof c))return new c(a);for(var d=a.split("{"),e=[d.shift()],f=[],g=[],h=[];d.length>0;){var i=d.shift(),j=i.split("}")[0],k=i.substring(j.length+1),l=b(j);g.push(l.substitution),f.push(l.prefix),e.push(k),h=h.concat(l.substitution.varNames)}this.fill=function(a){for(var b=e[0],c=0;c<g.length;c++){var d=g[c];b+=d(a),b+=e[c+1]}return b},this.varNames=h,this.template=a}function d(a,b){if(a===b)return!0;if("object"==typeof a&&"object"==typeof b){if(Array.isArray(a)!==Array.isArray(b))return!1;if(Array.isArray(a)){if(a.length!==b.length)return!1;for(var c=0;c<a.length;c++)if(!d(a[c],b[c]))return!1}else{var e;for(e in a)if(void 0===b[e]&&void 0!==a[e])return!1;for(e in b)if(void 0===a[e]&&void 0!==b[e])return!1;for(e in a)if(!d(a[e],b[e]))return!1}return!0}return!1}function e(a){var b=String(a).replace(/^\s+|\s+$/g,"").match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);return b?{href:b[0]||"",protocol:b[1]||"",authority:b[2]||"",host:b[3]||"",hostname:b[4]||"",port:b[5]||"",pathname:b[6]||"",search:b[7]||"",hash:b[8]||""}:null}function f(a,b){function c(a){var b=[];return a.replace(/^(\.\.?(\/|$))+/,"").replace(/\/(\.(\/|$))+/g,"/").replace(/\/\.\.$/,"/../").replace(/\/?[^\/]*/g,function(a){"/.."===a?b.pop():b.push(a)}),b.join("").replace(/^\//,"/"===a.charAt(0)?"/":"")}return b=e(b||""),a=e(a||""),b&&a?(b.protocol||a.protocol)+(b.protocol||b.authority?b.authority:a.authority)+c(b.protocol||b.authority||"/"===b.pathname.charAt(0)?b.pathname:b.pathname?(a.authority&&!a.pathname?"/":"")+a.pathname.slice(0,a.pathname.lastIndexOf("/")+1)+b.pathname:a.pathname)+(b.protocol||b.authority||b.pathname?b.search:b.search||a.search)+b.hash:null}function g(a){return a.split("#")[0]}function h(a,b){if(a&&"object"==typeof a)if(void 0===b?b=a.id:"string"==typeof a.id&&(b=f(b,a.id),a.id=b),Array.isArray(a))for(var c=0;c<a.length;c++)h(a[c],b);else{"string"==typeof a.$ref&&(a.$ref=f(b,a.$ref));for(var d in a)"enum"!==d&&h(a[d],b)}}function i(a,b,c,d,e,f){if(Error.call(this),void 0===a)throw new Error("No code supplied for error: "+b);this.message=b,this.params=c,this.code=a,this.dataPath=d||"",this.schemaPath=e||"",this.subErrors=f||null;var g=new Error(this.message);if(this.stack=g.stack||g.stacktrace,!this.stack)try{throw g}catch(g){this.stack=g.stack||g.stacktrace}}function j(a,b){if(b.substring(0,a.length)===a){var c=b.substring(a.length);if(b.length>0&&"/"===b.charAt(a.length-1)||"#"===c.charAt(0)||"?"===c.charAt(0))return!0}return!1}function k(a){var b=new n,c=a||"en",d={addFormat:function(){b.addFormat.apply(b,arguments)},language:function(a){return a?(s[a]||(a=a.split("-")[0]),s[a]?(c=a,a):!1):c},addLanguage:function(a,b){var c;for(c in o)b[c]&&!b[o[c]]&&(b[o[c]]=b[c]);var d=a.split("-")[0];if(s[d]){s[a]=Object.create(s[d]);for(c in b)"undefined"==typeof s[d][c]&&(s[d][c]=b[c]),s[a][c]=b[c]}else s[a]=b,s[d]=b;return this},freshApi:function(a){var b=k();return a&&b.language(a),b},validate:function(a,d,e,f){var g=new n(b,!1,s[c],e,f);"string"==typeof d&&(d={$ref:d}),g.addSchema("",d);var h=g.validateAll(a,d,null,null,"");return!h&&f&&(h=g.banUnknownProperties()),this.error=h,this.missing=g.missing,this.valid=null===h,this.valid},validateResult:function(){var a={};return this.validate.apply(a,arguments),a},validateMultiple:function(a,d,e,f){var g=new n(b,!0,s[c],e,f);"string"==typeof d&&(d={$ref:d}),g.addSchema("",d),g.validateAll(a,d,null,null,""),f&&g.banUnknownProperties();var h={};return h.errors=g.errors,h.missing=g.missing,h.valid=0===h.errors.length,h},addSchema:function(){return b.addSchema.apply(b,arguments)},getSchema:function(){return b.getSchema.apply(b,arguments)},getSchemaMap:function(){return b.getSchemaMap.apply(b,arguments)},getSchemaUris:function(){return b.getSchemaUris.apply(b,arguments)},getMissingUris:function(){return b.getMissingUris.apply(b,arguments)},dropSchemas:function(){b.dropSchemas.apply(b,arguments)},defineKeyword:function(){b.defineKeyword.apply(b,arguments)},defineError:function(a,b,c){if("string"!=typeof a||!/^[A-Z]+(_[A-Z]+)*$/.test(a))throw new Error("Code name must be a string in UPPER_CASE_WITH_UNDERSCORES");if("number"!=typeof b||b%1!==0||1e4>b)throw new Error("Code number must be an integer > 10000");if("undefined"!=typeof o[a])throw new Error("Error already defined: "+a+" as "+o[a]);if("undefined"!=typeof p[b])throw new Error("Error code already used: "+p[b]+" as "+b);o[a]=b,p[b]=a,r[a]=r[b]=c;for(var d in s){var e=s[d];e[a]&&(e[b]=e[b]||e[a])}},reset:function(){b.reset(),this.error=null,this.missing=[],this.valid=!0},missing:[],error:null,valid:!0,normSchema:h,resolveUrl:f,getDocumentUri:g,errorCodes:o};return d}Object.keys||(Object.keys=function(){var a=Object.prototype.hasOwnProperty,b=!{toString:null}.propertyIsEnumerable("toString"),c=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],d=c.length;return function(e){if("object"!=typeof e&&"function"!=typeof e||null===e)throw new TypeError("Object.keys called on non-object");var f=[];for(var g in e)a.call(e,g)&&f.push(g);if(b)for(var h=0;d>h;h++)a.call(e,c[h])&&f.push(c[h]);return f}}()),Object.create||(Object.create=function(){function a(){}return function(b){if(1!==arguments.length)throw new Error("Object.create implementation only accepts one parameter.");return a.prototype=b,new a}}()),Array.isArray||(Array.isArray=function(a){return"[object Array]"===Object.prototype.toString.call(a)}),Array.prototype.indexOf||(Array.prototype.indexOf=function(a){if(null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if(0===c)return-1;var d=0;if(arguments.length>1&&(d=Number(arguments[1]),d!==d?d=0:0!==d&&1/0!==d&&d!==-1/0&&(d=(d>0||-1)*Math.floor(Math.abs(d)))),d>=c)return-1;for(var e=d>=0?d:Math.max(c-Math.abs(d),0);c>e;e++)if(e in b&&b[e]===a)return e;return-1}),Object.isFrozen||(Object.isFrozen=function(a){for(var b="tv4_test_frozen_key";a.hasOwnProperty(b);)b+=Math.random();try{return a[b]=!0,delete a[b],!1}catch(c){return!0}});var l={"+":!0,"#":!0,".":!0,"/":!0,";":!0,"?":!0,"&":!0},m={"*":!0};c.prototype={toString:function(){return this.template},fillFromObject:function(a){return this.fill(function(b){return a[b]})}};var n=function(a,b,c,d,e){if(this.missing=[],this.missingMap={},this.formatValidators=a?Object.create(a.formatValidators):{},this.schemas=a?Object.create(a.schemas):{},this.collectMultiple=b,this.errors=[],this.handleError=b?this.collectError:this.returnError,d&&(this.checkRecursive=!0,this.scanned=[],this.scannedFrozen=[],this.scannedFrozenSchemas=[],this.scannedFrozenValidationErrors=[],this.validatedSchemasKey="tv4_validation_id",this.validationErrorsKey="tv4_validation_errors_id"),e&&(this.trackUnknownProperties=!0,this.knownPropertyPaths={},this.unknownPropertyPaths={}),this.errorMessages=c,this.definedKeywords={},a)for(var f in a.definedKeywords)this.definedKeywords[f]=a.definedKeywords[f].slice(0)};n.prototype.defineKeyword=function(a,b){this.definedKeywords[a]=this.definedKeywords[a]||[],this.definedKeywords[a].push(b)},n.prototype.createError=function(a,b,c,d,e){var f=this.errorMessages[a]||r[a];if("string"!=typeof f)return new i(a,"Unknown error code "+a+": "+JSON.stringify(b),b,c,d,e);var g=f.replace(/\{([^{}]*)\}/g,function(a,c){var d=b[c];return"string"==typeof d||"number"==typeof d?d:a});return new i(a,g,b,c,d,e)},n.prototype.returnError=function(a){return a},n.prototype.collectError=function(a){return a&&this.errors.push(a),null},n.prototype.prefixErrors=function(a,b,c){for(var d=a;d<this.errors.length;d++)this.errors[d]=this.errors[d].prefixWith(b,c);return this},n.prototype.banUnknownProperties=function(){for(var a in this.unknownPropertyPaths){var b=this.createError(o.UNKNOWN_PROPERTY,{path:a},a,""),c=this.handleError(b);if(c)return c}return null},n.prototype.addFormat=function(a,b){if("object"==typeof a){for(var c in a)this.addFormat(c,a[c]);return this}this.formatValidators[a]=b},n.prototype.resolveRefs=function(a,b){if(void 0!==a.$ref){if(b=b||{},b[a.$ref])return this.createError(o.CIRCULAR_REFERENCE,{urls:Object.keys(b).join(", ")},"","");b[a.$ref]=!0,a=this.getSchema(a.$ref,b)}return a},n.prototype.getSchema=function(a,b){var c;if(void 0!==this.schemas[a])return c=this.schemas[a],this.resolveRefs(c,b);var d=a,e="";if(-1!==a.indexOf("#")&&(e=a.substring(a.indexOf("#")+1),d=a.substring(0,a.indexOf("#"))),"object"==typeof this.schemas[d]){c=this.schemas[d];var f=decodeURIComponent(e);if(""===f)return this.resolveRefs(c,b);if("/"!==f.charAt(0))return void 0;for(var g=f.split("/").slice(1),h=0;h<g.length;h++){var i=g[h].replace(/~1/g,"/").replace(/~0/g,"~");if(void 0===c[i]){c=void 0;break}c=c[i]}if(void 0!==c)return this.resolveRefs(c,b)}void 0===this.missing[d]&&(this.missing.push(d),this.missing[d]=d,this.missingMap[d]=d)},n.prototype.searchSchemas=function(a,b){if(a&&"object"==typeof a){"string"==typeof a.id&&j(b,a.id)&&void 0===this.schemas[a.id]&&(this.schemas[a.id]=a);for(var c in a)if("enum"!==c)if("object"==typeof a[c])this.searchSchemas(a[c],b);else if("$ref"===c){var d=g(a[c]);d&&void 0===this.schemas[d]&&void 0===this.missingMap[d]&&(this.missingMap[d]=d)}}},n.prototype.addSchema=function(a,b){if("string"!=typeof a||"undefined"==typeof b){if("object"!=typeof a||"string"!=typeof a.id)return;b=a,a=b.id}a===g(a)+"#"&&(a=g(a)),this.schemas[a]=b,delete this.missingMap[a],h(b,a),this.searchSchemas(b,a)},n.prototype.getSchemaMap=function(){var a={};for(var b in this.schemas)a[b]=this.schemas[b];return a},n.prototype.getSchemaUris=function(a){var b=[];for(var c in this.schemas)(!a||a.test(c))&&b.push(c);return b},n.prototype.getMissingUris=function(a){var b=[];for(var c in this.missingMap)(!a||a.test(c))&&b.push(c);return b},n.prototype.dropSchemas=function(){this.schemas={},this.reset()},n.prototype.reset=function(){this.missing=[],this.missingMap={},this.errors=[]},n.prototype.validateAll=function(a,b,c,d,e){var f;if(b=this.resolveRefs(b),!b)return null;if(b instanceof i)return this.errors.push(b),b;var g,h=this.errors.length,j=null,k=null;if(this.checkRecursive&&a&&"object"==typeof a){if(f=!this.scanned.length,a[this.validatedSchemasKey]){var l=a[this.validatedSchemasKey].indexOf(b);if(-1!==l)return this.errors=this.errors.concat(a[this.validationErrorsKey][l]),null}if(Object.isFrozen(a)&&(g=this.scannedFrozen.indexOf(a),-1!==g)){var m=this.scannedFrozenSchemas[g].indexOf(b);if(-1!==m)return this.errors=this.errors.concat(this.scannedFrozenValidationErrors[g][m]),null}if(this.scanned.push(a),Object.isFrozen(a))-1===g&&(g=this.scannedFrozen.length,this.scannedFrozen.push(a),this.scannedFrozenSchemas.push([])),j=this.scannedFrozenSchemas[g].length,this.scannedFrozenSchemas[g][j]=b,this.scannedFrozenValidationErrors[g][j]=[];else{if(!a[this.validatedSchemasKey])try{Object.defineProperty(a,this.validatedSchemasKey,{value:[],configurable:!0}),Object.defineProperty(a,this.validationErrorsKey,{value:[],configurable:!0})}catch(n){a[this.validatedSchemasKey]=[],a[this.validationErrorsKey]=[]}k=a[this.validatedSchemasKey].length,a[this.validatedSchemasKey][k]=b,a[this.validationErrorsKey][k]=[]}}var o=this.errors.length,p=this.validateBasic(a,b,e)||this.validateNumeric(a,b,e)||this.validateString(a,b,e)||this.validateArray(a,b,e)||this.validateObject(a,b,e)||this.validateCombinations(a,b,e)||this.validateHypermedia(a,b,e)||this.validateFormat(a,b,e)||this.validateDefinedKeywords(a,b,e)||null;if(f){for(;this.scanned.length;){var q=this.scanned.pop();delete q[this.validatedSchemasKey]}this.scannedFrozen=[],this.scannedFrozenSchemas=[]}if(p||o!==this.errors.length)for(;c&&c.length||d&&d.length;){var r=c&&c.length?""+c.pop():null,s=d&&d.length?""+d.pop():null;p&&(p=p.prefixWith(r,s)),this.prefixErrors(o,r,s)}return null!==j?this.scannedFrozenValidationErrors[g][j]=this.errors.slice(h):null!==k&&(a[this.validationErrorsKey][k]=this.errors.slice(h)),this.handleError(p)},n.prototype.validateFormat=function(a,b){if("string"!=typeof b.format||!this.formatValidators[b.format])return null;var c=this.formatValidators[b.format].call(null,a,b);return"string"==typeof c||"number"==typeof c?this.createError(o.FORMAT_CUSTOM,{message:c}).prefixWith(null,"format"):c&&"object"==typeof c?this.createError(o.FORMAT_CUSTOM,{message:c.message||"?"},c.dataPath||null,c.schemaPath||"/format"):null},n.prototype.validateDefinedKeywords=function(a,b){for(var c in this.definedKeywords)if("undefined"!=typeof b[c])for(var d=this.definedKeywords[c],e=0;e<d.length;e++){var f=d[e],g=f(a,b[c],b);if("string"==typeof g||"number"==typeof g)return this.createError(o.KEYWORD_CUSTOM,{key:c,message:g}).prefixWith(null,"format");if(g&&"object"==typeof g){var h=g.code||o.KEYWORD_CUSTOM;if("string"==typeof h){if(!o[h])throw new Error("Undefined error code (use defineError): "+h);h=o[h]}var i="object"==typeof g.message?g.message:{key:c,message:g.message||"?"},j=g.schemaPath||"/"+c.replace(/~/g,"~0").replace(/\//g,"~1");return this.createError(h,i,g.dataPath||null,j)}}return null},n.prototype.validateBasic=function(a,b,c){var d;return(d=this.validateType(a,b,c))?d.prefixWith(null,"type"):(d=this.validateEnum(a,b,c))?d.prefixWith(null,"type"):null},n.prototype.validateType=function(a,b){if(void 0===b.type)return null;var c=typeof a;null===a?c="null":Array.isArray(a)&&(c="array");var d=b.type;"object"!=typeof d&&(d=[d]);for(var e=0;e<d.length;e++){var f=d[e];if(f===c||"integer"===f&&"number"===c&&a%1===0)return null}return this.createError(o.INVALID_TYPE,{type:c,expected:d.join("/")})},n.prototype.validateEnum=function(a,b){if(void 0===b["enum"])return null;for(var c=0;c<b["enum"].length;c++){var e=b["enum"][c];if(d(a,e))return null}return this.createError(o.ENUM_MISMATCH,{value:"undefined"!=typeof JSON?JSON.stringify(a):a})},n.prototype.validateNumeric=function(a,b,c){return this.validateMultipleOf(a,b,c)||this.validateMinMax(a,b,c)||null},n.prototype.validateMultipleOf=function(a,b){var c=b.multipleOf||b.divisibleBy;return void 0===c?null:"number"==typeof a&&a%c!==0?this.createError(o.NUMBER_MULTIPLE_OF,{value:a,multipleOf:c}):null},n.prototype.validateMinMax=function(a,b){if("number"!=typeof a)return null;if(void 0!==b.minimum){if(a<b.minimum)return this.createError(o.NUMBER_MINIMUM,{value:a,minimum:b.minimum}).prefixWith(null,"minimum");if(b.exclusiveMinimum&&a===b.minimum)return this.createError(o.NUMBER_MINIMUM_EXCLUSIVE,{value:a,minimum:b.minimum}).prefixWith(null,"exclusiveMinimum")}if(void 0!==b.maximum){if(a>b.maximum)return this.createError(o.NUMBER_MAXIMUM,{value:a,maximum:b.maximum}).prefixWith(null,"maximum");if(b.exclusiveMaximum&&a===b.maximum)return this.createError(o.NUMBER_MAXIMUM_EXCLUSIVE,{value:a,maximum:b.maximum}).prefixWith(null,"exclusiveMaximum")}return null},n.prototype.validateString=function(a,b,c){return this.validateStringLength(a,b,c)||this.validateStringPattern(a,b,c)||null},n.prototype.validateStringLength=function(a,b){return"string"!=typeof a?null:void 0!==b.minLength&&a.length<b.minLength?this.createError(o.STRING_LENGTH_SHORT,{length:a.length,minimum:b.minLength}).prefixWith(null,"minLength"):void 0!==b.maxLength&&a.length>b.maxLength?this.createError(o.STRING_LENGTH_LONG,{length:a.length,maximum:b.maxLength}).prefixWith(null,"maxLength"):null},n.prototype.validateStringPattern=function(a,b){if("string"!=typeof a||void 0===b.pattern)return null;var c=new RegExp(b.pattern);return c.test(a)?null:this.createError(o.STRING_PATTERN,{pattern:b.pattern}).prefixWith(null,"pattern")},n.prototype.validateArray=function(a,b,c){return Array.isArray(a)?this.validateArrayLength(a,b,c)||this.validateArrayUniqueItems(a,b,c)||this.validateArrayItems(a,b,c)||null:null},n.prototype.validateArrayLength=function(a,b){var c;return void 0!==b.minItems&&a.length<b.minItems&&(c=this.createError(o.ARRAY_LENGTH_SHORT,{length:a.length,minimum:b.minItems}).prefixWith(null,"minItems"),this.handleError(c))?c:void 0!==b.maxItems&&a.length>b.maxItems&&(c=this.createError(o.ARRAY_LENGTH_LONG,{length:a.length,maximum:b.maxItems}).prefixWith(null,"maxItems"),this.handleError(c))?c:null},n.prototype.validateArrayUniqueItems=function(a,b){if(b.uniqueItems)for(var c=0;c<a.length;c++)for(var e=c+1;e<a.length;e++)if(d(a[c],a[e])){var f=this.createError(o.ARRAY_UNIQUE,{match1:c,match2:e}).prefixWith(null,"uniqueItems");if(this.handleError(f))return f}return null},n.prototype.validateArrayItems=function(a,b,c){if(void 0===b.items)return null;var d,e;if(Array.isArray(b.items)){for(e=0;e<a.length;e++)if(e<b.items.length){if(d=this.validateAll(a[e],b.items[e],[e],["items",e],c+"/"+e))return d}else if(void 0!==b.additionalItems)if("boolean"==typeof b.additionalItems){if(!b.additionalItems&&(d=this.createError(o.ARRAY_ADDITIONAL_ITEMS,{}).prefixWith(""+e,"additionalItems"),this.handleError(d)))return d}else if(d=this.validateAll(a[e],b.additionalItems,[e],["additionalItems"],c+"/"+e))return d}else for(e=0;e<a.length;e++)if(d=this.validateAll(a[e],b.items,[e],["items"],c+"/"+e))return d;return null},n.prototype.validateObject=function(a,b,c){return"object"!=typeof a||null===a||Array.isArray(a)?null:this.validateObjectMinMaxProperties(a,b,c)||this.validateObjectRequiredProperties(a,b,c)||this.validateObjectProperties(a,b,c)||this.validateObjectDependencies(a,b,c)||null},n.prototype.validateObjectMinMaxProperties=function(a,b){var c,d=Object.keys(a);return void 0!==b.minProperties&&d.length<b.minProperties&&(c=this.createError(o.OBJECT_PROPERTIES_MINIMUM,{propertyCount:d.length,minimum:b.minProperties}).prefixWith(null,"minProperties"),this.handleError(c))?c:void 0!==b.maxProperties&&d.length>b.maxProperties&&(c=this.createError(o.OBJECT_PROPERTIES_MAXIMUM,{propertyCount:d.length,maximum:b.maxProperties}).prefixWith(null,"maxProperties"),this.handleError(c))?c:null},n.prototype.validateObjectRequiredProperties=function(a,b){if(void 0!==b.required)for(var c=0;c<b.required.length;c++){var d=b.required[c];if(void 0===a[d]){var e=this.createError(o.OBJECT_REQUIRED,{key:d}).prefixWith(null,""+c).prefixWith(null,"required");if(this.handleError(e))return e}}return null},n.prototype.validateObjectProperties=function(a,b,c){var d;for(var e in a){var f=c+"/"+e.replace(/~/g,"~0").replace(/\//g,"~1"),g=!1;if(void 0!==b.properties&&void 0!==b.properties[e]&&(g=!0,d=this.validateAll(a[e],b.properties[e],[e],["properties",e],f)))return d;if(void 0!==b.patternProperties)for(var h in b.patternProperties){var i=new RegExp(h);if(i.test(e)&&(g=!0,d=this.validateAll(a[e],b.patternProperties[h],[e],["patternProperties",h],f)))return d}if(g)this.trackUnknownProperties&&(this.knownPropertyPaths[f]=!0,delete this.unknownPropertyPaths[f]);else if(void 0!==b.additionalProperties){if(this.trackUnknownProperties&&(this.knownPropertyPaths[f]=!0,delete this.unknownPropertyPaths[f]),"boolean"==typeof b.additionalProperties){if(!b.additionalProperties&&(d=this.createError(o.OBJECT_ADDITIONAL_PROPERTIES,{}).prefixWith(e,"additionalProperties"),this.handleError(d)))return d}else if(d=this.validateAll(a[e],b.additionalProperties,[e],["additionalProperties"],f))return d}else this.trackUnknownProperties&&!this.knownPropertyPaths[f]&&(this.unknownPropertyPaths[f]=!0)}return null},n.prototype.validateObjectDependencies=function(a,b,c){var d;if(void 0!==b.dependencies)for(var e in b.dependencies)if(void 0!==a[e]){var f=b.dependencies[e];if("string"==typeof f){if(void 0===a[f]&&(d=this.createError(o.OBJECT_DEPENDENCY_KEY,{key:e,missing:f}).prefixWith(null,e).prefixWith(null,"dependencies"),this.handleError(d)))return d}else if(Array.isArray(f))for(var g=0;g<f.length;g++){var h=f[g];if(void 0===a[h]&&(d=this.createError(o.OBJECT_DEPENDENCY_KEY,{key:e,missing:h}).prefixWith(null,""+g).prefixWith(null,e).prefixWith(null,"dependencies"),this.handleError(d)))return d}else if(d=this.validateAll(a,f,[],["dependencies",e],c))return d}return null},n.prototype.validateCombinations=function(a,b,c){return this.validateAllOf(a,b,c)||this.validateAnyOf(a,b,c)||this.validateOneOf(a,b,c)||this.validateNot(a,b,c)||null},n.prototype.validateAllOf=function(a,b,c){if(void 0===b.allOf)return null;for(var d,e=0;e<b.allOf.length;e++){var f=b.allOf[e];if(d=this.validateAll(a,f,[],["allOf",e],c))return d}return null},n.prototype.validateAnyOf=function(a,b,c){if(void 0===b.anyOf)return null;var d,e,f=[],g=this.errors.length;this.trackUnknownProperties&&(d=this.unknownPropertyPaths,e=this.knownPropertyPaths);for(var h=!0,i=0;i<b.anyOf.length;i++){this.trackUnknownProperties&&(this.unknownPropertyPaths={},this.knownPropertyPaths={});var j=b.anyOf[i],k=this.errors.length,l=this.validateAll(a,j,[],["anyOf",i],c);if(null===l&&k===this.errors.length){if(this.errors=this.errors.slice(0,g),this.trackUnknownProperties){for(var m in this.knownPropertyPaths)e[m]=!0,delete d[m];for(var n in this.unknownPropertyPaths)e[n]||(d[n]=!0);h=!1;continue}return null}l&&f.push(l.prefixWith(null,""+i).prefixWith(null,"anyOf"))}return this.trackUnknownProperties&&(this.unknownPropertyPaths=d,this.knownPropertyPaths=e),h?(f=f.concat(this.errors.slice(g)),this.errors=this.errors.slice(0,g),this.createError(o.ANY_OF_MISSING,{},"","/anyOf",f)):void 0},n.prototype.validateOneOf=function(a,b,c){if(void 0===b.oneOf)return null;var d,e,f=null,g=[],h=this.errors.length;this.trackUnknownProperties&&(d=this.unknownPropertyPaths,e=this.knownPropertyPaths);for(var i=0;i<b.oneOf.length;i++){this.trackUnknownProperties&&(this.unknownPropertyPaths={},this.knownPropertyPaths={});var j=b.oneOf[i],k=this.errors.length,l=this.validateAll(a,j,[],["oneOf",i],c);if(null===l&&k===this.errors.length){if(null!==f)return this.errors=this.errors.slice(0,h),this.createError(o.ONE_OF_MULTIPLE,{index1:f,index2:i},"","/oneOf");if(f=i,this.trackUnknownProperties){for(var m in this.knownPropertyPaths)e[m]=!0,delete d[m];for(var n in this.unknownPropertyPaths)e[n]||(d[n]=!0)}}else l&&g.push(l)}return this.trackUnknownProperties&&(this.unknownPropertyPaths=d,this.knownPropertyPaths=e),null===f?(g=g.concat(this.errors.slice(h)),this.errors=this.errors.slice(0,h),this.createError(o.ONE_OF_MISSING,{},"","/oneOf",g)):(this.errors=this.errors.slice(0,h),null)},n.prototype.validateNot=function(a,b,c){if(void 0===b.not)return null;var d,e,f=this.errors.length;this.trackUnknownProperties&&(d=this.unknownPropertyPaths,e=this.knownPropertyPaths,this.unknownPropertyPaths={},this.knownPropertyPaths={});var g=this.validateAll(a,b.not,null,null,c),h=this.errors.slice(f);return this.errors=this.errors.slice(0,f),this.trackUnknownProperties&&(this.unknownPropertyPaths=d,this.knownPropertyPaths=e),null===g&&0===h.length?this.createError(o.NOT_PASSED,{},"","/not"):null},n.prototype.validateHypermedia=function(a,b,d){if(!b.links)return null;for(var e,f=0;f<b.links.length;f++){var g=b.links[f];if("describedby"===g.rel){for(var h=new c(g.href),i=!0,j=0;j<h.varNames.length;j++)if(!(h.varNames[j]in a)){i=!1;break}if(i){var k=h.fillFromObject(a),l={$ref:k};if(e=this.validateAll(a,l,[],["links",f],d))return e}}}};var o={INVALID_TYPE:0,ENUM_MISMATCH:1,ANY_OF_MISSING:10,ONE_OF_MISSING:11,ONE_OF_MULTIPLE:12,NOT_PASSED:13,NUMBER_MULTIPLE_OF:100,NUMBER_MINIMUM:101,NUMBER_MINIMUM_EXCLUSIVE:102,NUMBER_MAXIMUM:103,NUMBER_MAXIMUM_EXCLUSIVE:104,STRING_LENGTH_SHORT:200,STRING_LENGTH_LONG:201,STRING_PATTERN:202,OBJECT_PROPERTIES_MINIMUM:300,OBJECT_PROPERTIES_MAXIMUM:301,OBJECT_REQUIRED:302,OBJECT_ADDITIONAL_PROPERTIES:303,OBJECT_DEPENDENCY_KEY:304,ARRAY_LENGTH_SHORT:400,ARRAY_LENGTH_LONG:401,ARRAY_UNIQUE:402,ARRAY_ADDITIONAL_ITEMS:403,FORMAT_CUSTOM:500,KEYWORD_CUSTOM:501,CIRCULAR_REFERENCE:600,UNKNOWN_PROPERTY:1e3},p={};for(var q in o)p[o[q]]=q;var r={INVALID_TYPE:"Invalid type: {type} (expected {expected})",ENUM_MISMATCH:"No enum match for: {value}",ANY_OF_MISSING:'Data does not match any schemas from "anyOf"',ONE_OF_MISSING:'Data does not match any schemas from "oneOf"',ONE_OF_MULTIPLE:'Data is valid against more than one schema from "oneOf": indices {index1} and {index2}',NOT_PASSED:'Data matches schema from "not"',NUMBER_MULTIPLE_OF:"Value {value} is not a multiple of {multipleOf}",NUMBER_MINIMUM:"Value {value} is less than minimum {minimum}",NUMBER_MINIMUM_EXCLUSIVE:"Value {value} is equal to exclusive minimum {minimum}",NUMBER_MAXIMUM:"Value {value} is greater than maximum {maximum}",NUMBER_MAXIMUM_EXCLUSIVE:"Value {value} is equal to exclusive maximum {maximum}",STRING_LENGTH_SHORT:"String is too short ({length} chars), minimum {minimum}",STRING_LENGTH_LONG:"String is too long ({length} chars), maximum {maximum}",STRING_PATTERN:"String does not match pattern: {pattern}",OBJECT_PROPERTIES_MINIMUM:"Too few properties defined ({propertyCount}), minimum {minimum}",OBJECT_PROPERTIES_MAXIMUM:"Too many properties defined ({propertyCount}), maximum {maximum}",OBJECT_REQUIRED:"Missing required property: {key}",OBJECT_ADDITIONAL_PROPERTIES:"Additional properties not allowed",OBJECT_DEPENDENCY_KEY:"Dependency failed - key must exist: {missing} (due to key: {key})",ARRAY_LENGTH_SHORT:"Array is too short ({length}), minimum {minimum}",ARRAY_LENGTH_LONG:"Array is too long ({length}), maximum {maximum}",ARRAY_UNIQUE:"Array items are not unique (indices {match1} and {match2})",ARRAY_ADDITIONAL_ITEMS:"Additional items not allowed",FORMAT_CUSTOM:"Format validation failed ({message})",KEYWORD_CUSTOM:"Keyword failed: {key} ({message})",CIRCULAR_REFERENCE:"Circular $refs: {urls}",UNKNOWN_PROPERTY:"Unknown property (not in schema)"};i.prototype=Object.create(Error.prototype),i.prototype.constructor=i,i.prototype.name="ValidationError",i.prototype.prefixWith=function(a,b){if(null!==a&&(a=a.replace(/~/g,"~0").replace(/\//g,"~1"),this.dataPath="/"+a+this.dataPath),null!==b&&(b=b.replace(/~/g,"~0").replace(/\//g,"~1"),this.schemaPath="/"+b+this.schemaPath),null!==this.subErrors)for(var c=0;c<this.subErrors.length;c++)this.subErrors[c].prefixWith(a,b);return this};var s={},t=k();return t.addLanguage("en-gb",r),t.tv4=t,t});
define('Map',['utils', 'Draw', 'Behavior', 'Scale', 'build', 'UndoStack', 'CallbackManager', 'KeyManager', 'Canvas', 'data_styles', 'SearchIndex', 'lib/bacon', 'lib/tv4'], function(utils, Draw, Behavior, Scale, build, UndoStack, CallbackManager, KeyManager, Canvas, data_styles, SearchIndex, bacon, tv4) {
/** Defines the metabolic map data, and manages drawing and building.
Arguments
---------
svg: The parent SVG container for the map.
css:
selection: A d3 selection for a node to place the map inside.
selection:
zoom_container:
settings:
cobra_model:
canvas_size_and_loc:
enable_search:
map_name: (Optional, Default: 'new map')
map_id: (Optional, Default: A string of random characters.)
map_description: (Optional, Default: '')
Callbacks
---------
map.callback_manager.run('set_status', null, status);
map.callback_manager.run('toggle_beziers', null, beziers_enabled);
map.callback_manager.run('select_metabolite_with_id', null, selected_node, coords);
map.callback_manager.run('select_selectable', null, node_count, selected_node, coords);
map.callback_manager.run('deselect_nodes');
map.callback_manager.run('select_text_label');
map.callback_manager.run('before_svg_export');
map.callback_manager.run('after_svg_export');
this.callback_manager.run('calc_data_stats__reaction', null, changed);
this.callback_manager.run('calc_data_stats__metabolite', null, changed);
*/
var Map = utils.make_class();
// class methods
Map.from_data = from_data;
// instance methods
Map.prototype = {
// setup
init: init,
// more setup
setup_containers: setup_containers,
reset_containers: reset_containers,
// appearance
set_status: set_status,
clear_map: clear_map,
// selection
select_all: select_all,
select_none: select_none,
invert_selection: invert_selection,
select_selectable: select_selectable,
select_metabolite_with_id: select_metabolite_with_id,
select_single_node: select_single_node,
deselect_nodes: deselect_nodes,
select_text_label: select_text_label,
deselect_text_labels: deselect_text_labels,
// build
new_reaction_from_scratch: new_reaction_from_scratch,
extend_nodes: extend_nodes,
extend_reactions: extend_reactions,
new_reaction_for_metabolite: new_reaction_for_metabolite,
cycle_primary_node: cycle_primary_node,
toggle_selected_node_primary: toggle_selected_node_primary,
new_text_label: new_text_label,
edit_text_label: edit_text_label,
// delete
delete_selected: delete_selected,
delete_selectable: delete_selectable,
delete_node_data: delete_node_data,
delete_segment_data: delete_segment_data,
delete_reaction_data: delete_reaction_data,
delete_text_label_data: delete_text_label_data,
// find
get_selected_node_ids: get_selected_node_ids,
get_selected_nodes: get_selected_nodes,
get_selected_text_label_ids: get_selected_text_label_ids,
get_selected_text_labels: get_selected_text_labels,
segments_and_reactions_for_nodes: segments_and_reactions_for_nodes,
// draw
draw_everything: draw_everything,
// draw reactions
draw_all_reactions: draw_all_reactions,
draw_these_reactions: draw_these_reactions,
clear_deleted_reactions: clear_deleted_reactions,
// draw nodes
draw_all_nodes: draw_all_nodes,
draw_these_nodes: draw_these_nodes,
clear_deleted_nodes: clear_deleted_nodes,
// draw text_labels
draw_all_text_labels: draw_all_text_labels,
draw_these_text_labels: draw_these_text_labels,
clear_deleted_text_labels: clear_deleted_text_labels,
// draw beziers
draw_all_beziers: draw_all_beziers,
draw_these_beziers: draw_these_beziers,
clear_deleted_beziers: clear_deleted_beziers,
toggle_beziers: toggle_beziers,
hide_beziers: hide_beziers,
show_beziers: show_beziers,
// data
has_cobra_model: has_cobra_model,
apply_reaction_data_to_map: apply_reaction_data_to_map,
apply_metabolite_data_to_map: apply_metabolite_data_to_map,
apply_gene_data_to_map: apply_gene_data_to_map,
// data statistics
get_data_statistics: get_data_statistics,
calc_data_stats: calc_data_stats,
// zoom
zoom_extent_nodes: zoom_extent_nodes,
zoom_extent_canvas: zoom_extent_canvas,
_zoom_extent: _zoom_extent,
get_size: get_size,
zoom_to_reaction: zoom_to_reaction,
zoom_to_node: zoom_to_node,
zoom_to_text_label: zoom_to_text_label,
highlight_reaction: highlight_reaction,
highlight_node: highlight_node,
highlight_text_label: highlight_text_label,
highlight: highlight,
// io
save: save,
map_for_export: map_for_export,
save_svg: save_svg
};
return Map;
// -------------------------------------------------------------------------
// setup
function init(svg, css, selection, zoom_container, settings,
cobra_model, canvas_size_and_loc, enable_search,
map_name, map_id, map_description) {
if (canvas_size_and_loc===null) {
var size = zoom_container.get_size();
canvas_size_and_loc = {x: -size.width, y: -size.height,
width: size.width*3, height: size.height*3};
}
if (map_name === undefined || map_name === null || map_name == '')
map_name = 'new_map';
else
map_name = String(map_name);
if (map_id === undefined || map_id === null || map_id == '')
map_id = utils.generate_map_id();
else
map_id = String(map_id);
if (map_description === undefined || map_description === null)
map_description = '';
else
map_description = String(map_description);
// set up the callbacks
this.callback_manager = new CallbackManager();
// set up the defs
this.svg = svg;
this.defs = utils.setup_defs(svg, css);
// make the canvas
this.canvas = new Canvas(selection, canvas_size_and_loc);
this.setup_containers(selection);
this.sel = selection;
this.zoom_container = zoom_container;
this.settings = settings;
// set the model AFTER loading the datasets
this.cobra_model = cobra_model;
this.largest_ids = { reactions: -1,
nodes: -1,
segments: -1,
text_labels: -1 };
// make the scales
this.scale = new Scale();
// initialize stats
this.calc_data_stats('reaction');
this.calc_data_stats('metabolite');
this.scale.connect_to_settings(this.settings, this,
get_data_statistics.bind(this));
// make the undo/redo stack
this.undo_stack = new UndoStack();
// make a behavior object
this.behavior = new Behavior(this, this.undo_stack);
// draw manager
this.draw = new Draw(this.behavior, this.settings);
// make a key manager
this.key_manager = new KeyManager(this.settings.get_option('unique_map_id'));
// make the search index
this.enable_search = enable_search;
this.search_index = new SearchIndex();
// map properties
this.map_name = map_name;
this.map_id = map_id;
this.map_description = map_description;
// deal with the window
var window_translate = {'x': 0, 'y': 0},
window_scale = 1;
// hide beziers
this.beziers_enabled = false;
// data
this.has_data_on_reactions = false;
this.has_data_on_nodes = false;
this.nodes = {};
this.reactions = {};
this.beziers = {};
this.text_labels = {};
// update data with null to populate data-specific attributes
this.apply_reaction_data_to_map(null);
this.apply_metabolite_data_to_map(null);
this.apply_gene_data_to_map(null);
// rotation mode off
this.rotation_on = false;
// validate the JSON file during map export
this.debug = false;
};
// -------------------------------------------------------------------------
// Import
function from_data(map_data, svg, css, selection, zoom_container, settings,
cobra_model, enable_search) {
/** Load a json map and add necessary fields for rendering.
*/
var canvas = map_data[1].canvas,
map_name = map_data[0].map_name,
map_id = map_data[0].map_id,
map_description = (map_data[0].map_description.replace(/(\nLast Modified.*)+$/g, '')
+ '\nLast Modified ' + Date(Date.now()).toString()),
map = new Map(svg, css, selection, zoom_container, settings,
cobra_model, canvas, enable_search,
map_name, map_id, map_description);
map.reactions = map_data[1].reactions;
map.nodes = map_data[1].nodes;
map.text_labels = map_data[1].text_labels;
for (var n_id in map.nodes) {
var node = map.nodes[n_id];
// clear all the connected segments
node.connected_segments = [];
// populate the nodes search index.
if (enable_search) {
if (node.node_type!='metabolite') continue;
map.search_index.insert('n'+n_id, { 'name': node.bigg_id,
'data': { type: 'metabolite',
node_id: n_id }});
map.search_index.insert('n_name'+n_id, { 'name': node.name,
'data': { type: 'metabolite',
node_id: n_id }});
}
}
// Propagate coefficients and reversibility, build the connected
// segments, add bezier points, and populate the reaction search index.
for (var r_id in map.reactions) {
var reaction = map.reactions[r_id];
// reaction search index
if (enable_search) {
map.search_index.insert('r' + r_id,
{ 'name': reaction.bigg_id,
'data': { type: 'reaction',
reaction_id: r_id }});
map.search_index.insert('r_name' + r_id,
{ 'name': reaction.name,
'data': { type: 'reaction',
reaction_id: r_id }});
for (var g_id in reaction.genes) {
var gene = reaction.genes[g_id];
map.search_index.insert('r' + r_id + '_g' + g_id,
{ 'name': gene.bigg_id,
'data': { type: 'reaction',
reaction_id: r_id }});
map.search_index.insert('r' + r_id + '_g_name' + g_id,
{ 'name': gene.name,
'data': { type: 'reaction',
reaction_id: r_id }});
}
}
// keep track of any bad segments
var segments_to_delete = [];
for (var s_id in reaction.segments) {
var segment = reaction.segments[s_id];
// propagate reversibility
segment.reversibility = reaction.reversibility;
// if there is an error with to_ or from_ nodes, remove this segment
if (!(segment.from_node_id in map.nodes) || !(segment.to_node_id in map.nodes)) {
console.warn('Bad node references in segment ' + s_id + '. Deleting segment.');
segments_to_delete.push(s_id);
continue
}
var from_node = map.nodes[segment.from_node_id],
to_node = map.nodes[segment.to_node_id];
// propagate coefficients
reaction.metabolites.forEach(function(met) {
if (met.bigg_id==from_node.bigg_id) {
segment.from_node_coefficient = met.coefficient;
} else if (met.bigg_id==to_node.bigg_id) {
segment.to_node_coefficient = met.coefficient;
}
});
// build connected segments
[from_node, to_node].forEach(function(node) {
node.connected_segments.push({ segment_id: s_id,
reaction_id: r_id });
});
// If the metabolite has no bezier points, then add them.
var start = map.nodes[segment.from_node_id],
end = map.nodes[segment.to_node_id];
if (start['node_type']=='metabolite' || end['node_type']=='metabolite') {
var midpoint = utils.c_plus_c(start, utils.c_times_scalar(utils.c_minus_c(end, start), 0.5));
if (segment.b1 === null) segment.b1 = midpoint;
if (segment.b2 === null) segment.b2 = midpoint;
}
}
// delete the bad segments
segments_to_delete.forEach(function(s_id) {
delete reaction.segments[s_id];
});
}
// add text_labels to the search index
if (enable_search) {
for (var label_id in map.text_labels) {
var label = map.text_labels[label_id];
map.search_index.insert('l'+label_id, { 'name': label.text,
'data': { type: 'text_label',
text_label_id: label_id }});
}
}
// populate the beziers
map.beziers = build.new_beziers_for_reactions(map.reactions);
// get largest ids for adding new reactions, nodes, text labels, and
// segments
map.largest_ids.reactions = get_largest_id(map.reactions);
map.largest_ids.nodes = get_largest_id(map.nodes);
map.largest_ids.text_labels = get_largest_id(map.text_labels);
var largest_segment_id = 0;
for (var id in map.reactions) {
largest_segment_id = get_largest_id(map.reactions[id].segments,
largest_segment_id);
}
map.largest_ids.segments = largest_segment_id;
// update data with null to populate data-specific attributes
map.apply_reaction_data_to_map(null);
map.apply_metabolite_data_to_map(null);
map.apply_gene_data_to_map(null);
return map;
// definitions
function get_largest_id(obj, current_largest) {
/** Return the largest integer key in obj, or current_largest, whichever is bigger. */
if (current_largest===undefined) current_largest = 0;
if (obj===undefined) return current_largest;
return Math.max.apply(null, Object.keys(obj).map(function(x) {
return parseInt(x);
}).concat([current_largest]));
}
}
// ---------------------------------------------------------------------
// more setup
function setup_containers(sel) {
sel.append('g')
.attr('id', 'reactions');
sel.append('g')
.attr('id', 'nodes');
sel.append('g')
.attr('id', 'beziers');
sel.append('g')
.attr('id', 'text-labels');
}
function reset_containers() {
this.sel.select('#reactions')
.selectAll('.reaction')
.remove();
this.sel.select('#nodes')
.selectAll('.node')
.remove();
this.sel.select('#beziers')
.selectAll('.bezier')
.remove();
this.sel.select('#text-labels')
.selectAll('.text-label')
.remove();
}
// -------------------------------------------------------------------------
// Appearance
function set_status(status, time) {
/** Set the status of the map, with an optional expiration
time. Rendering the status is taken care of by the Builder.
Arguments
---------
status: The status string.
time: An optional time, in ms, after which the status is set to ''.
*/
this.callback_manager.run('set_status', null, status);
// clear any other timers on the status bar
window.clearTimeout(this._status_timer);
this._status_timer = null;
if (time!==undefined) {
this._status_timer = window.setTimeout(function() {
this.callback_manager.run('set_status', null, '');
}.bind(this), time);
}
}
function clear_map() {
this.reactions = {};
this.beziers = {};
this.nodes = {};
this.text_labels = {};
this.map_name = 'new_map';
this.map_id = utils.generate_map_id();
this.map_description = '';
// reaction_data onto existing map reactions
this.apply_reaction_data_to_map(null);
this.apply_metabolite_data_to_map(null);
this.apply_gene_data_to_map(null);
this.draw_everything();
}
function has_cobra_model() {
return (this.cobra_model !== null);
}
function draw_everything() {
/** Draw the all reactions, nodes, & text labels.
*/
this.draw_all_reactions(true, true); // also draw beziers
this.draw_all_nodes(true);
this.draw_all_text_labels();
}
function draw_all_reactions(draw_beziers, clear_deleted) {
/** Draw all reactions, and clear deleted reactions.
Arguments
---------
draw_beziers: (Boolean, default True) Whether to also draw the bezier
control points.
clear_deleted: (Optional, Default: true) Boolean, if true, then also
clear deleted nodes.
*/
if (draw_beziers===undefined) draw_beziers = true;
if (clear_deleted===undefined) clear_deleted = true;
// Draw all reactions.
var reaction_ids = [];
for (var reaction_id in this.reactions) {
reaction_ids.push(reaction_id);
}
// If draw_beziers is true, just draw them all, rather than deciding
// which ones to draw.
this.draw_these_reactions(reaction_ids, false);
if (draw_beziers && this.beziers_enabled)
this.draw_all_beziers();
// Clear all deleted reactions.
if (clear_deleted)
this.clear_deleted_reactions(draw_beziers);
}
function draw_these_reactions(reaction_ids, draw_beziers) {
/** Draw specific reactions.
Does nothing with exit selection. Use clear_deleted_reactions to remove
reactions from the DOM.
Arguments
---------
reactions_ids: An array of reaction_ids to update.
draw_beziers: (Boolean, default True) Whether to also draw the bezier
control points.
*/
if (draw_beziers===undefined) draw_beziers = true;
// find reactions for reaction_ids
var reaction_subset = utils.object_slice_for_ids_ref(this.reactions,
reaction_ids);
// function to update reactions
var update_fn = function(sel) {
return this.draw.update_reaction(sel, this.scale, this.cobra_model,
this.nodes, this.defs,
this.has_data_on_reactions);
}.bind(this);
// draw the reactions
utils.draw_an_object(this.sel, '#reactions', '.reaction', reaction_subset,
'reaction_id', this.draw.create_reaction.bind(this.draw),
update_fn);
if (draw_beziers) {
// particular beziers to draw
var bezier_ids = build.bezier_ids_for_reaction_ids(reaction_subset);
this.draw_these_beziers(bezier_ids);
}
}
function clear_deleted_reactions(draw_beziers) {
/** Remove any reactions that are not in *this.reactions*.
Arguments
---------
draw_beziers: (Boolean, default True) Whether to also clear deleted
bezier control points.
*/
if (draw_beziers===undefined) draw_beziers = true;
// remove deleted reactions and segments
utils.draw_an_object(this.sel, '#reactions', '.reaction', this.reactions, 'reaction_id',
null,
clear_deleted_segments,
function(sel) { sel.remove(); });
if (draw_beziers==true)
this.clear_deleted_beziers();
// definitions
function clear_deleted_segments(update_selection) {
// draw segments
utils.draw_a_nested_object(update_selection, '.segment-group', 'segments', 'segment_id',
null,
null,
function(sel) { sel.remove(); });
};
}
function draw_all_nodes(clear_deleted) {
/** Draw all nodes, and clear deleted nodes.
Arguments
---------
clear_deleted: (Optional, Default: true) Boolean, if true, then also
clear deleted nodes.
*/
if (clear_deleted === undefined) clear_deleted = true;
var node_ids = [];
for (var node_id in this.nodes) {
node_ids.push(node_id);
}
this.draw_these_nodes(node_ids);
// clear the deleted nodes
if (clear_deleted)
this.clear_deleted_nodes();
}
function draw_these_nodes(node_ids) {
/** Draw specific nodes.
Does nothing with exit selection. Use clear_deleted_nodes to remove
nodes from the DOM.
Arguments
---------
nodes_ids: An array of node_ids to update.
*/
// find reactions for reaction_ids
var node_subset = utils.object_slice_for_ids_ref(this.nodes, node_ids);
// functions to create and update nodes
var create_fn = function(sel) {
return this.draw.create_node(sel,
this.nodes,
this.reactions);
}.bind(this),
update_fn = function(sel) {
return this.draw.update_node(sel,
this.scale,
this.has_data_on_nodes,
this.settings.get_option('identifiers_on_map'),
this.settings.get_option('metabolite_styles'),
{ color: this.settings.get_option('metabolite_no_data_color'),
size: this.settings.get_option('metabolite_no_data_size') },
this.behavior.selectable_mousedown,
this.behavior.selectable_click,
this.behavior.node_mouseover,
this.behavior.node_mouseout,
this.behavior.selectable_drag,
this.behavior.node_label_drag);
}.bind(this);
// draw the nodes
utils.draw_an_object(this.sel, '#nodes', '.node', node_subset, 'node_id',
create_fn, update_fn);
}
function clear_deleted_nodes() {
/** Remove any nodes that are not in *this.nodes*.
*/
// run remove for exit selection
utils.draw_an_object(this.sel, '#nodes', '.node', this.nodes, 'node_id',
null, null, function(sel) { sel.remove(); });
}
function draw_all_text_labels() {
// Draw all text_labels.
var text_label_ids = [];
for (var text_label_id in this.text_labels) {
text_label_ids.push(text_label_id);
}
this.draw_these_text_labels(text_label_ids);
// Clear all deleted text_labels.
this.clear_deleted_text_labels();
}
function draw_these_text_labels(text_label_ids) {
/** Draw specific text_labels.
Does nothing with exit selection. Use clear_deleted_text_labels to remove
text_labels from the DOM.
Arguments
---------
text_labels_ids: An array of text_label_ids to update.
*/
// find reactions for reaction_ids
var text_label_subset = utils.object_slice_for_ids_ref(this.text_labels, text_label_ids);
// function to update text_labels
var update_fn = function(sel) {
return this.draw.update_text_label(sel, this.behavior);;
}.bind(this);
// draw the text_labels
utils.draw_an_object(this.sel, '#text-labels', '.text-label',
text_label_subset, 'text_label_id',
this.draw.create_text_label.bind(this.draw),
update_fn);
}
function clear_deleted_text_labels() {
/** Remove any text_labels that are not in *this.text_labels*.
*/
// clear deleted
utils.draw_an_object(this.sel, '#text-labels', '.text-label',
this.text_labels, 'text_label_id', null, null,
function(sel) { sel.remove(); });
}
function draw_all_beziers() {
/** Draw all beziers, and clear deleted reactions.
*/
var bezier_ids = [];
for (var bezier_id in this.beziers) {
bezier_ids.push(bezier_id);
}
this.draw_these_beziers(bezier_ids);
// clear delete beziers
this.clear_deleted_beziers();
}
function draw_these_beziers(bezier_ids) {
/** Draw specific beziers.
Does nothing with exit selection. Use clear_deleted_beziers to remove
beziers from the DOM.
Arguments
---------
beziers_ids: An array of bezier_ids to update.
*/
// find reactions for reaction_ids
var bezier_subset = utils.object_slice_for_ids_ref(this.beziers, bezier_ids);
// function to update beziers
var update_fn = function(sel) {
return this.draw.update_bezier(sel,
this.beziers_enabled,
this.behavior.bezier_drag,
this.behavior.bezier_mouseover,
this.behavior.bezier_mouseout,
this.nodes,
this.reactions);
}.bind(this);
// draw the beziers
utils.draw_an_object(this.sel, '#beziers', '.bezier', bezier_subset,
'bezier_id', this.draw.create_bezier.bind(this.draw),
update_fn);
}
function clear_deleted_beziers() {
/** Remove any beziers that are not in *this.beziers*.
*/
// remove deleted
utils.draw_an_object(this.sel, '#beziers', '.bezier', this.beziers,
'bezier_id', null, null,
function(sel) { sel.remove(); });
}
function show_beziers() {
this.toggle_beziers(true);
}
function hide_beziers() {
this.toggle_beziers(false);
}
function toggle_beziers(on_off) {
if (on_off===undefined) this.beziers_enabled = !this.beziers_enabled;
else this.beziers_enabled = on_off;
this.draw_all_beziers();
this.callback_manager.run('toggle_beziers', null, this.beziers_enabled);
}
function apply_reaction_data_to_map(data) {
/** Returns True if the scale has changed.
*/
var styles = this.settings.get_option('reaction_styles'),
compare_style = this.settings.get_option('reaction_compare_style');
var has_data = data_styles.apply_reaction_data_to_reactions(this.reactions, data,
styles, compare_style);
this.has_data_on_reactions = has_data;
return this.calc_data_stats('reaction');
}
function apply_metabolite_data_to_map(data) {
/** Returns True if the scale has changed.
*/
var styles = this.settings.get_option('metabolite_styles'),
compare_style = this.settings.get_option('metabolite_compare_style');
var has_data = data_styles.apply_metabolite_data_to_nodes(this.nodes, data,
styles, compare_style);
this.has_data_on_nodes = has_data;
return this.calc_data_stats('metabolite');
}
function apply_gene_data_to_map(gene_data_obj) {
/** Returns True if the scale has changed.
Arguments
---------
gene_data_obj: The gene data object, with the following style:
{ reaction_id: { rule: 'rule_string', genes: { gene_id: value } } }
*/
var styles = this.settings.get_option('reaction_styles'),
compare_style = this.settings.get_option('reaction_compare_style'),
identifiers_on_map = this.settings.get_option('identifiers_on_map'),
and_method_in_gene_reaction_rule = this.settings.get_option('and_method_in_gene_reaction_rule');
var has_data = data_styles.apply_gene_data_to_reactions(this.reactions, gene_data_obj,
styles, identifiers_on_map,
compare_style,
and_method_in_gene_reaction_rule);
this.has_data_on_reactions = has_data;
return this.calc_data_stats('reaction');
}
// ------------------------------------------------
// Data domains
function get_data_statistics() {
return this.data_statistics;
}
function calc_data_stats(type) {
/** Returns True if the stats have changed.
Arguments
---------
type: Either 'metabolite' or 'reaction'
*/
if (['reaction', 'metabolite'].indexOf(type) == -1)
throw new Error('Bad type ' + type);
// make the data structure
if (!('data_statistics' in this)) {
this.data_statistics = {};
this.data_statistics[type] = {};
} else if (!(type in this.data_statistics)) {
this.data_statistics[type] = {};
}
var same = true;
// default min and max
var vals = [];
if (type == 'metabolite') {
for (var node_id in this.nodes) {
var node = this.nodes[node_id];
// check number
if (node.data !== null)
vals.push(node.data);
}
} else if (type == 'reaction') {
for (var reaction_id in this.reactions) {
var reaction = this.reactions[reaction_id];
// check number
if (reaction.data !== null)
vals.push(reaction.data);
}
}
// calculate these statistics
var quartiles = utils.quartiles(vals),
funcs = [['min', on_array(Math.min)],
['max', on_array(Math.max)],
['mean', utils.mean],
['Q1', function() { return quartiles[0]; }],
['median', function() { return quartiles[1]; }],
['Q3', function() { return quartiles[2]; }]];
funcs.forEach(function(ar) {
var new_val, name = ar[0];
if (vals.length == 0) {
new_val = null;
} else {
var fn = ar[1];
new_val = fn(vals);
}
if (new_val != this.data_statistics[type][name])
same = false;
this.data_statistics[type][name] = new_val;
}.bind(this));
if (type == 'reaction')
this.callback_manager.run('calc_data_stats__reaction', null, !same);
else
this.callback_manager.run('calc_data_stats__metabolite', null, !same);
return !same;
// definitions
function on_array(fn) {
return function (array) { return fn.apply(null, array); };
}
}
// ---------------------------------------------------------------------
// Node interaction
function get_coords_for_node(node_id) {
var node = this.nodes[node_id],
coords = {'x': node.x, 'y': node.y};
return coords;
}
function get_selected_node_ids() {
var selected_node_ids = [];
this.sel.select('#nodes')
.selectAll('.selected')
.each(function(d) { selected_node_ids.push(d.node_id); });
return selected_node_ids;
}
function get_selected_nodes() {
var selected_nodes = {},
self = this;
this.sel.select('#nodes')
.selectAll('.selected')
.each(function(d) {
selected_nodes[d.node_id] = this.nodes[d.node_id];
}.bind(this));
return selected_nodes;
}
function get_selected_text_label_ids() {
var selected_text_label_ids = [];
this.sel.select('#text-labels')
.selectAll('.selected')
.each(function(d) { selected_text_label_ids.push(d.text_label_id); });
return selected_text_label_ids;
}
function get_selected_text_labels() {
var selected_text_labels = {},
self = this;
this.sel.select('#text-labels')
.selectAll('.selected')
.each(function(d) {
selected_text_labels[d.text_label_id] = this.text_labels[d.text_label_id];
}.bind(this));
return selected_text_labels;
}
function select_all() {
/** Select all nodes and text labels.
*/
this.sel.selectAll('#nodes,#text-labels')
.selectAll('.node,.text-label')
.classed('selected', true);
}
function select_none() {
/** Deselect all nodes and text labels.
*/
this.sel.selectAll('.selected')
.classed('selected', false);
}
function invert_selection() {
/** Invert selection of nodes and text labels.
*/
var selection = this.sel.selectAll('#nodes,#text-labels')
.selectAll('.node,.text-label');
selection.classed('selected', function() {
return !d3.select(this).classed('selected');
});
}
function select_metabolite_with_id(node_id) {
/** Select a metabolite with the given id, and turn off the reaction
target.
*/
// deselect all text labels
this.deselect_text_labels();
var node_selection = this.sel.select('#nodes').selectAll('.node'),
coords,
selected_node;
node_selection.classed('selected', function(d) {
var selected = String(d.node_id) == String(node_id);
if (selected) {
selected_node = d;
coords = { x: d.x, y: d.y };
}
return selected;
});
this.sel.selectAll('.start-reaction-target').style('visibility', 'hidden');
this.callback_manager.run('select_metabolite_with_id', null, selected_node, coords);
}
function select_selectable(node, d) {
/** Select a metabolite or text label, and manage the shift key.
*/
var classable_selection = this.sel.selectAll('#nodes,#text-labels')
.selectAll('.node,.text-label'),
shift_key_on = this.key_manager.held_keys.shift,
classable_node;
if (d3.select(node).attr('class').indexOf('text-label') == -1) {
// node
classable_node = node.parentNode;
} else {
// text-label
classable_node = node;
}
// toggle selection
if (shift_key_on) {
// toggle this node
d3.select(classable_node)
.classed('selected', !d3.select(classable_node).classed('selected'));
} else {
// unselect all other nodes, and select this one
classable_selection.classed('selected', false);
d3.select(classable_node).classed('selected', true);
}
// run the select_metabolite callback
var selected_nodes = this.sel.select('#nodes').selectAll('.selected'),
node_count = 0,
coords,
selected_node;
selected_nodes.each(function(d) {
selected_node = d;
coords = { x: d.x, y: d.y };
node_count++;
});
this.callback_manager.run('select_selectable', null, node_count, selected_node, coords);
}
function select_single_node() {
/** Unselect all but one selected node, and return the node.
If no nodes are selected, return null.
*/
var out = null,
self = this,
node_selection = this.sel.select('#nodes').selectAll('.selected');
node_selection.classed('selected', function(d, i) {
if (i==0) {
out = d;
return true;
} else {
return false;
}
});
return out;
}
function deselect_nodes() {
var node_selection = this.sel.select('#nodes').selectAll('.node');
node_selection.classed('selected', false);
this.callback_manager.run('deselect_nodes');
}
function select_text_label(sel, d) {
// deselect all nodes
this.deselect_nodes();
// find the new selection
// Ignore shift key and only allow single selection for now
var text_label_selection = this.sel.select('#text-labels').selectAll('.text-label');
text_label_selection.classed('selected', function(p) { return d === p; });
var selected_text_labels = this.sel.select('#text-labels').selectAll('.selected'),
coords;
selected_text_labels.each(function(d) {
coords = { x: d.x, y: d.y };
});
this.callback_manager.run('select_text_label');
}
function deselect_text_labels() {
var text_label_selection = this.sel.select('#text-labels').selectAll('.text-label');
text_label_selection.classed('selected', false);
}
// ---------------------------------------------------------------------
// Delete
function delete_selected() {
/** Delete the selected nodes and associated segments and reactions, and selected labels.
Undoable.
*/
var selected_nodes = this.get_selected_nodes(),
selected_text_labels = this.get_selected_text_labels();
if (Object.keys(selected_nodes).length >= 1 ||
Object.keys(selected_text_labels).length >= 1)
this.delete_selectable(selected_nodes, selected_text_labels, true);
}
function delete_selectable(selected_nodes, selected_text_labels, should_draw) {
/** Delete the nodes and associated segments and reactions. Undoable.
Arguments
---------
selected_nodes: An object that is a subset of map.nodes.
selected_text_labels: An object that is a subset of map.text_labels.
should_draw: A boolean argument to determine whether to draw the changes to the map.
*/
var out = this.segments_and_reactions_for_nodes(selected_nodes),
segment_objs_w_segments = out.segment_objs_w_segments, // TODO repeated values here
reactions = out.reactions;
// copy nodes to undelete
var saved_nodes = utils.clone(selected_nodes),
saved_segment_objs_w_segments = utils.clone(segment_objs_w_segments),
saved_reactions = utils.clone(reactions),
saved_text_labels = utils.clone(selected_text_labels),
delete_and_draw = function(nodes, reactions, segment_objs,
selected_text_labels) {
// delete nodes, segments, and reactions with no segments
this.delete_node_data(Object.keys(selected_nodes));
this.delete_segment_data(segment_objs); // also deletes beziers
this.delete_reaction_data(Object.keys(reactions));
this.delete_text_label_data(Object.keys(selected_text_labels));
// apply the reaction and node data
var changed_r_scale = false,
changed_m_scale = false;
if (this.has_data_on_reactions)
changed_r_scale = this.calc_data_stats('reaction');
if (this.has_data_on_nodes)
changed_m_scale = this.calc_data_stats('metabolite');
// redraw
if (should_draw) {
if (changed_r_scale)
this.draw_all_reactions(true, true);
else
this.clear_deleted_reactions(); // also clears segments and beziers
if (changed_m_scale)
this.draw_all_nodes(true);
else
this.clear_deleted_nodes();
this.clear_deleted_text_labels();
}
}.bind(this);
// delete
delete_and_draw(selected_nodes, reactions, segment_objs_w_segments,
selected_text_labels);
// add to undo/redo stack
this.undo_stack.push(function() {
// undo
// redraw the saved nodes, reactions, and segments
this.extend_nodes(saved_nodes);
this.extend_reactions(saved_reactions);
var reaction_ids_to_draw = Object.keys(saved_reactions);
for (var segment_id in saved_segment_objs_w_segments) {
var segment_obj = saved_segment_objs_w_segments[segment_id];
var segment = segment_obj.segment;
this.reactions[segment_obj.reaction_id]
.segments[segment_obj.segment_id] = segment;
// updated connected nodes
[segment.from_node_id, segment.to_node_id].forEach(function(node_id) {
// not necessary for the deleted nodes
if (node_id in saved_nodes) return;
var node = this.nodes[node_id];
node.connected_segments.push({ reaction_id: segment_obj.reaction_id,
segment_id: segment_obj.segment_id });
}.bind(this));
// extend the beziers
var seg_id = segment_obj.segment_id,
r_id = segment_obj.reaction_id,
seg_o = {};
seg_o[seg_id] = segment_obj.segment;
utils.extend(this.beziers, build.new_beziers_for_segments(seg_o, r_id));
if (reaction_ids_to_draw.indexOf(segment_obj.reaction_id)==-1)
reaction_ids_to_draw.push(segment_obj.reaction_id);
}
// apply the reaction and node data
// if the scale changes, redraw everything
if (this.has_data_on_reactions) {
var scale_changed = this.calc_data_stats('reaction');
if (scale_changed) this.draw_all_reactions(true, false);
else this.draw_these_reactions(reaction_ids_to_draw);
} else {
if (should_draw) this.draw_these_reactions(reaction_ids_to_draw);
}
if (this.has_data_on_nodes) {
var scale_changed = this.calc_data_stats('metabolite');
if (should_draw) {
if (scale_changed) this.draw_all_nodes(false);
else this.draw_these_nodes(Object.keys(saved_nodes));
}
} else {
if (should_draw) this.draw_these_nodes(Object.keys(saved_nodes));
}
// redraw the saved text_labels
utils.extend(this.text_labels, saved_text_labels);
if (should_draw) this.draw_these_text_labels(Object.keys(saved_text_labels));
// copy text_labels to re-delete
selected_text_labels = utils.clone(saved_text_labels);
// copy nodes to re-delete
selected_nodes = utils.clone(saved_nodes);
segment_objs_w_segments = utils.clone(saved_segment_objs_w_segments);
reactions = utils.clone(saved_reactions);
}.bind(this), function () {
// redo
// clone the nodes and reactions, to redo this action later
delete_and_draw(selected_nodes, reactions, segment_objs_w_segments,
selected_text_labels);
}.bind(this));
}
function delete_node_data(node_ids) {
/** Delete nodes, and remove from search index.
*/
node_ids.forEach(function(node_id) {
if (this.enable_search && this.nodes[node_id].node_type=='metabolite') {
var found = (this.search_index.remove('n' + node_id)
&& this.search_index.remove('n_name' + node_id));
if (!found)
console.warn('Could not find deleted metabolite in search index');
}
delete this.nodes[node_id];
}.bind(this));
}
function delete_segment_data(segment_objs) {
/** Delete segments, update connected_segments in nodes, and delete
bezier points.
segment_objs: Object with values like { reaction_id: '123', segment_id: '456' }
*/
for (var segment_id in segment_objs) {
var segment_obj = segment_objs[segment_id];
var reaction = this.reactions[segment_obj.reaction_id];
// segment already deleted
if (!(segment_obj.segment_id in reaction.segments)) return;
var segment = reaction.segments[segment_obj.segment_id];
// updated connected nodes
[segment.from_node_id, segment.to_node_id].forEach(function(node_id) {
if (!(node_id in this.nodes)) return;
var node = this.nodes[node_id];
node.connected_segments = node.connected_segments.filter(function(so) {
return so.segment_id != segment_obj.segment_id;
});
}.bind(this));
// remove beziers
['b1', 'b2'].forEach(function(bez) {
var bez_id = build.bezier_id_for_segment_id(segment_obj.segment_id, bez);
delete this.beziers[bez_id];
}.bind(this));
delete reaction.segments[segment_obj.segment_id];
}
}
function delete_reaction_data(reaction_ids) {
/** Delete reactions, segments, and beziers, and remove reaction from
search index.
*/
reaction_ids.forEach(function(reaction_id) {
// remove beziers
var reaction = this.reactions[reaction_id];
for (var segment_id in reaction.segments) {
['b1', 'b2'].forEach(function(bez) {
var bez_id = build.bezier_id_for_segment_id(segment_id, bez);
delete this.beziers[bez_id];
}.bind(this));
}
// delete reaction
delete this.reactions[reaction_id];
// remove from search index
var found = (this.search_index.remove('r' + reaction_id)
&& this.search_index.remove('r_name' + reaction_id));
if (!found)
console.warn('Could not find deleted reaction ' +
reaction_id + ' in search index');
for (var g_id in reaction.genes) {
var found = (this.search_index.remove('r' + reaction_id + '_g' + g_id)
&& this.search_index.remove('r' + reaction_id + '_g_name' + g_id));
if (!found)
console.warn('Could not find deleted gene ' +
g_id + ' in search index');
}
}.bind(this));
}
function delete_text_label_data(text_label_ids) {
/** delete text labels for an array of ids
*/
text_label_ids.forEach(function(text_label_id) {
// delete label
delete this.text_labels[text_label_id];
// remove from search index
var found = this.search_index.remove('l'+text_label_id);
if (!found)
console.warn('Could not find deleted text label in search index');
}.bind(this));
}
// ---------------------------------------------------------------------
// Building
function new_reaction_from_scratch(starting_reaction, coords, direction) {
/** Draw a reaction on a blank canvas.
starting_reaction: bigg_id for a reaction to draw.
coords: coordinates to start drawing
*/
// If there is no cobra model, error
if (!this.cobra_model) return console.error('No CobraModel. Cannot build new reaction');
// set reaction coordinates and angle
// be sure to copy the reaction recursively
var cobra_reaction = utils.clone(this.cobra_model.reactions[starting_reaction]);
// create the first node
for (var metabolite_id in cobra_reaction.metabolites) {
var coefficient = cobra_reaction.metabolites[metabolite_id],
metabolite = this.cobra_model.metabolites[metabolite_id];
if (coefficient < 0) {
var selected_node_id = String(++this.largest_ids.nodes),
label_d = { x: 30, y: 10 },
selected_node = { connected_segments: [],
x: coords.x,
y: coords.y,
node_is_primary: true,
label_x: coords.x + label_d.x,
label_y: coords.y + label_d.y,
name: metabolite.name,
bigg_id: metabolite_id,
node_type: 'metabolite' },
new_nodes = {};
new_nodes[selected_node_id] = selected_node;
break;
}
}
// draw
extend_and_draw_metabolite.apply(this, [new_nodes, selected_node_id]);
// clone the nodes and reactions, to redo this action later
var saved_nodes = utils.clone(new_nodes);
// draw the reaction
var out = this.new_reaction_for_metabolite(starting_reaction,
selected_node_id,
direction, false),
reaction_redo = out.redo,
reaction_undo = out.undo;
// add to undo/redo stack
this.undo_stack.push(function() {
// undo
// first undo the reaction
reaction_undo();
// get the nodes to delete
this.delete_node_data(Object.keys(new_nodes));
// save the nodes and reactions again, for redo
new_nodes = utils.clone(saved_nodes);
// draw
this.clear_deleted_nodes();
// deselect
this.deselect_nodes();
}.bind(this), function () {
// redo
// clone the nodes and reactions, to redo this action later
extend_and_draw_metabolite.apply(this, [new_nodes, selected_node_id]);
// now redo the reaction
reaction_redo();
}.bind(this));
return null;
// definitions
function extend_and_draw_metabolite(new_nodes, selected_node_id) {
this.extend_nodes(new_nodes);
if (this.has_data_on_nodes) {
var scale_changed = this.apply_metabolite_data_to_nodes(new_nodes);
if (scale_changed) this.draw_all_nodes(false);
else this.draw_these_nodes([selected_node_id]);
} else {
this.draw_these_nodes([selected_node_id]);
}
}
}
function extend_nodes(new_nodes) {
/** Add new nodes to data and search index.
*/
if (this.enable_search) {
for (var node_id in new_nodes) {
var node = new_nodes[node_id];
if (node.node_type != 'metabolite')
continue;
this.search_index.insert('n' + node_id,
{ 'name': node.bigg_id,
'data': { type: 'metabolite',
node_id: node_id }});
this.search_index.insert('n_name' + node_id,
{ 'name': node.name,
'data': { type: 'metabolite',
node_id: node_id }});
}
}
utils.extend(this.nodes, new_nodes);
}
function extend_reactions(new_reactions) {
/** Add new reactions to data and search index.
*/
if (this.enable_search) {
for (var r_id in new_reactions) {
var reaction = new_reactions[r_id];
this.search_index.insert('r' + r_id, { 'name': reaction.bigg_id,
'data': { type: 'reaction',
reaction_id: r_id }});
this.search_index.insert('r_name' + r_id, { 'name': reaction.name,
'data': { type: 'reaction',
reaction_id: r_id }});
for (var g_id in reaction.genes) {
var gene = reaction.genes[g_id];
this.search_index.insert('r' + r_id + '_g' + g_id,
{ 'name': gene.bigg_id,
'data': { type: 'reaction',
reaction_id: r_id }});
this.search_index.insert('r' + r_id + '_g_name' + g_id,
{ 'name': gene.name,
'data': { type: 'reaction',
reaction_id: r_id }});
}
}
}
utils.extend(this.reactions, new_reactions);
}
function new_reaction_for_metabolite(reaction_bigg_id, selected_node_id,
direction, apply_undo_redo) {
/** Build a new reaction starting with selected_met.
Undoable
Arguments
---------
reaction_bigg_id: The BiGG ID of the reaction to draw.
selected_node_id: The ID of the node to begin drawing with.
direction: The direction to draw in.
apply_undo_redo: (Optional, Default: true) If true, then add to the
undo stack. Otherwise, just return the undo and redo functions.
Returns
-------
{ undo: undo_function,
redo: redo_function }
*/
// default args
if (apply_undo_redo === undefined) apply_undo_redo = true;
// get the metabolite node
var selected_node = this.nodes[selected_node_id];
// set reaction coordinates and angle
// be sure to copy the reaction recursively
var cobra_reaction = this.cobra_model.reactions[reaction_bigg_id];
// build the new reaction
var out = build.new_reaction(reaction_bigg_id, cobra_reaction,
this.cobra_model.metabolites,
selected_node_id,
utils.clone(selected_node),
this.largest_ids,
this.cobra_model.cofactors,
direction),
new_nodes = out.new_nodes,
new_reactions = out.new_reactions,
new_beziers = out.new_beziers;
// draw
extend_and_draw_reaction.apply(this, [new_nodes, new_reactions,
new_beziers, selected_node_id]);
// clone the nodes and reactions, to redo this action later
var saved_nodes = utils.clone(new_nodes),
saved_reactions = utils.clone(new_reactions),
saved_beziers = utils.clone(new_beziers);
// add to undo/redo stack
var undo_fn = function() {
// undo
// get the nodes to delete
delete new_nodes[selected_node_id];
this.delete_node_data(Object.keys(new_nodes));
this.delete_reaction_data(Object.keys(new_reactions)); // also deletes beziers
select_metabolite_with_id.apply(this, [selected_node_id]);
// save the nodes and reactions again, for redo
new_nodes = utils.clone(saved_nodes);
new_reactions = utils.clone(saved_reactions);
new_beziers = utils.clone(saved_beziers);
// draw
if (this.has_data_on_reactions) {
var scale_changed = this.calc_data_stats('reaction');
if (scale_changed) this.draw_all_reactions(true, true);
else this.draw_these_reactions(Object.keys(new_reactions));
} else {
this.clear_deleted_reactions(true); // also clears segments and beziers
}
if (this.has_data_on_nodes) {
var scale_changed = this.calc_data_stats('metabolite');
if (scale_changed) this.draw_all_nodes(true);
else this.draw_these_nodes(Object.keys(new_nodes));
} else {
this.clear_deleted_nodes();
}
}.bind(this),
redo_fn = function () {
// redo
// clone the nodes and reactions, to redo this action later
extend_and_draw_reaction.apply(this, [new_nodes, new_reactions,
new_beziers, selected_node_id]);
}.bind(this);
if (apply_undo_redo)
this.undo_stack.push(undo_fn, redo_fn);
return { undo: undo_fn,
redo: redo_fn };
// definitions
function extend_and_draw_reaction(new_nodes, new_reactions, new_beziers,
selected_node_id) {
this.extend_reactions(new_reactions);
utils.extend(this.beziers, new_beziers);
// remove the selected node so it can be updated
this.delete_node_data([selected_node_id]); // TODO this is a hack. fix
this.extend_nodes(new_nodes);
// apply the reaction and node data to the scales
// if the scale changes, redraw everything
if (this.has_data_on_reactions) {
var scale_changed = this.calc_data_stats('reaction');
if (scale_changed) this.draw_all_reactions(true, false);
else this.draw_these_reactions(Object.keys(new_reactions));
} else {
this.draw_these_reactions(Object.keys(new_reactions));
}
if (this.has_data_on_nodes) {
var scale_changed = this.calc_data_stats('metabolite');
if (scale_changed) this.draw_all_nodes(false);
else this.draw_these_nodes(Object.keys(new_nodes));
} else {
this.draw_these_nodes(Object.keys(new_nodes));
}
// select new primary metabolite
for (var node_id in new_nodes) {
var node = new_nodes[node_id];
if (node.node_is_primary && node_id!=selected_node_id) {
this.select_metabolite_with_id(node_id);
var new_coords = { x: node.x, y: node.y };
if (this.zoom_container)
this.zoom_container.translate_off_screen(new_coords);
}
}
}
}
function cycle_primary_node() {
var selected_nodes = this.get_selected_nodes();
// get the first node
var node_id = Object.keys(selected_nodes)[0],
node = selected_nodes[node_id],
reactions = this.reactions,
nodes = this.nodes;
// make the other reactants or products secondary
// 1. Get the connected anchor nodes for the node
var connected_anchor_ids = [],
reactions_to_draw;
nodes[node_id].connected_segments.forEach(function(segment_info) {
reactions_to_draw = [segment_info.reaction_id];
var segment;
try {
segment = reactions[segment_info.reaction_id].segments[segment_info.segment_id];
if (segment === undefined) throw new Error('undefined segment');
} catch (e) {
console.warn('Could not find connected segment ' + segment_info.segment_id);
return;
}
connected_anchor_ids.push(segment.from_node_id==node_id ?
segment.to_node_id : segment.from_node_id);
});
// can only be connected to one anchor
if (connected_anchor_ids.length != 1) {
console.error('Only connected nodes with a single reaction can be selected');
return;
}
var connected_anchor_id = connected_anchor_ids[0];
// 2. find nodes connected to the anchor that are metabolites
var related_node_ids = [node_id];
var segments = [];
nodes[connected_anchor_id].connected_segments.forEach(function(segment_info) { // deterministic order
var segment;
try {
segment = reactions[segment_info.reaction_id].segments[segment_info.segment_id];
if (segment === undefined) throw new Error('undefined segment');
} catch (e) {
console.warn('Could not find connected segment ' + segment_info.segment_id);
return;
}
var conn_met_id = segment.from_node_id == connected_anchor_id ? segment.to_node_id : segment.from_node_id,
conn_node = nodes[conn_met_id];
if (conn_node.node_type == 'metabolite' && conn_met_id != node_id) {
related_node_ids.push(String(conn_met_id));
}
});
// 3. make sure they only have 1 reaction connection, and check if
// they match the other selected nodes
for (var i=0; i<related_node_ids.length; i++) {
if (nodes[related_node_ids[i]].connected_segments.length > 1) {
console.error('Only connected nodes with a single reaction can be selected');
return;
}
}
for (var a_selected_node_id in selected_nodes) {
if (a_selected_node_id!=node_id && related_node_ids.indexOf(a_selected_node_id) == -1) {
console.warn('Selected nodes are not on the same reaction');
return;
}
}
// 4. change the primary node, and change coords, label coords, and beziers
var nodes_to_draw = [],
last_i = related_node_ids.length - 1,
last_node = nodes[related_node_ids[last_i]],
last_is_primary = last_node.node_is_primary,
last_coords = { x: last_node.x, y: last_node.y,
label_x: last_node.label_x, label_y: last_node.label_y };
if (last_node.connected_segments.length > 1)
console.warn('Too many connected segments for node ' + last_node.node_id);
var last_segment_info = last_node.connected_segments[0], // guaranteed above to have only one
last_segment;
try {
last_segment = reactions[last_segment_info.reaction_id].segments[last_segment_info.segment_id];
if (last_segment === undefined) throw new Error('undefined segment');
} catch (e) {
console.error('Could not find connected segment ' + last_segment_info.segment_id);
return;
}
var last_bezier = { b1: last_segment.b1, b2: last_segment.b2 },
primary_node_id;
related_node_ids.forEach(function(related_node_id) {
var node = nodes[related_node_id],
this_is_primary = node.node_is_primary,
these_coords = { x: node.x, y: node.y,
label_x: node.label_x, label_y: node.label_y },
this_segment_info = node.connected_segments[0],
this_segment = reactions[this_segment_info.reaction_id].segments[this_segment_info.segment_id],
this_bezier = { b1: this_segment.b1, b2: this_segment.b2 };
node.node_is_primary = last_is_primary;
node.x = last_coords.x; node.y = last_coords.y;
node.label_x = last_coords.label_x; node.label_y = last_coords.label_y;
this_segment.b1 = last_bezier.b1; this_segment.b2 = last_bezier.b2;
last_is_primary = this_is_primary;
last_coords = these_coords;
last_bezier = this_bezier;
if (node.node_is_primary) primary_node_id = related_node_id;
nodes_to_draw.push(related_node_id);
});
// 5. cycle the connected_segments array so the next time, it cycles differently
var old_connected_segments = nodes[connected_anchor_id].connected_segments,
last_i = old_connected_segments.length - 1,
new_connected_segments = [old_connected_segments[last_i]];
old_connected_segments.forEach(function(segment, i) {
if (last_i==i) return;
new_connected_segments.push(segment);
});
nodes[connected_anchor_id].connected_segments = new_connected_segments;
// 6. draw the nodes
this.draw_these_nodes(nodes_to_draw);
this.draw_these_reactions(reactions_to_draw);
// 7. select the primary node
this.select_metabolite_with_id(primary_node_id);
return;
}
function toggle_selected_node_primary() {
/** Toggle the primary/secondary status of each selected node.
Undoable.
*/
var selected_node_ids = this.get_selected_node_ids(),
go = function(ids) {
var nodes_to_draw = {},
hide_secondary_metabolites = this.settings.get_option('hide_secondary_metabolites');
ids.forEach(function(id) {
if (!(id in this.nodes)) {
console.warn('Could not find node: ' + id);
return;
}
var node = this.nodes[id];
if (node.node_type == 'metabolite') {
node.node_is_primary = !node.node_is_primary;
nodes_to_draw[id] = node;
}
}.bind(this));
// draw the nodes
this.draw_these_nodes(Object.keys(nodes_to_draw));
// draw associated reactions
if (hide_secondary_metabolites) {
var out = this.segments_and_reactions_for_nodes(nodes_to_draw),
reaction_ids_to_draw_o = {};
for (var id in out.segment_objs_w_segments) {
var r_id = out.segment_objs_w_segments[id].reaction_id;
reaction_ids_to_draw_o[r_id] = true;
}
this.draw_these_reactions(Object.keys(reaction_ids_to_draw_o));
}
}.bind(this);
// go
go(selected_node_ids);
// add to the undo stack
this.undo_stack.push(function () {
go(selected_node_ids);
}, function () {
go(selected_node_ids);
});
}
function segments_and_reactions_for_nodes(nodes) {
/** Get segments and reactions that should be deleted with node deletions
*/
var segment_objs_w_segments = {},
these_reactions = {},
segment_ids_for_reactions = {},
reactions = this.reactions;
// for each node
for (var node_id in nodes) {
var node = nodes[node_id];
// find associated segments and reactions
node.connected_segments.forEach(function(segment_obj) {
var segment;
try {
segment = reactions[segment_obj.reaction_id].segments[segment_obj.segment_id];
if (segment === undefined) throw new Error('undefined segment');
} catch (e) {
console.warn('Could not find connected segments for node');
return;
}
var segment_obj_w_segment = utils.clone(segment_obj);
segment_obj_w_segment['segment'] = utils.clone(segment);
segment_objs_w_segments[segment_obj.segment_id] = segment_obj_w_segment;
if (!(segment_obj.reaction_id in segment_ids_for_reactions))
segment_ids_for_reactions[segment_obj.reaction_id] = [];
segment_ids_for_reactions[segment_obj.reaction_id].push(segment_obj.segment_id);
});
}
// find the reactions that should be deleted because they have no segments left
for (var reaction_id in segment_ids_for_reactions) {
var reaction = reactions[reaction_id],
these_ids = segment_ids_for_reactions[reaction_id],
has = true;
for (var segment_id in reaction.segments) {
if (these_ids.indexOf(segment_id)==-1) has = false;
}
if (has) these_reactions[reaction_id] = reaction;
}
return { segment_objs_w_segments: segment_objs_w_segments, reactions: these_reactions };
}
function new_text_label(coords, text) {
// make an label
var out = build.new_text_label(this.largest_ids, text, coords);
this.text_labels[out.id] = out.label;
var sel = this.draw_these_text_labels([out.id]);
// add to the search index
this.search_index.insert('l' + out.id, { 'name': text,
'data': { type: 'text_label',
text_label_id: out.id }});
return out.id;
}
function edit_text_label(text_label_id, new_value, should_draw) {
// save old value
var saved_value = this.text_labels[text_label_id].text,
edit_and_draw = function(new_val, should_draw) {
// set the new value
this.text_labels[text_label_id].text = new_val;
if (should_draw) this.draw_these_text_labels([text_label_id]);
// update in the search index
var record_id = 'l' + text_label_id,
found = this.search_index.remove(record_id);
if (!found)
console.warn('Could not find modified text label in search index');
this.search_index.insert(record_id, { 'name': new_val,
'data': { type: 'text_label',
text_label_id: text_label_id }});
}.bind(this);
// edit the label
edit_and_draw(new_value, should_draw);
// add to undo stack
this.undo_stack.push(function() {
edit_and_draw(saved_value, should_draw);
}, function () {
edit_and_draw(new_value, should_draw);
});
}
// -------------------------------------------------------------------------
// Zoom
function zoom_extent_nodes(margin) {
/** Zoom to fit all the nodes.
margin: optional argument to set the margins as a fraction of height.
Returns error if one is raised.
*/
this._zoom_extent(margin, 'nodes');
}
function zoom_extent_canvas(margin) {
/** Zoom to fit the canvas.
margin: optional argument to set the margins as a fraction of height.
Returns error if one is raised.
*/
this._zoom_extent(margin, 'canvas');
}
function _zoom_extent(margin, mode) {
/** Zoom to fit all the nodes.
margin: optional argument to set the margins.
mode: Values are 'nodes', 'canvas'.
Returns error if one is raised.
*/
// optional args
if (margin===undefined) margin = (mode=='nodes' ? 0.2 : 0);
if (mode===undefined) mode = 'canvas';
var new_zoom, new_pos,
size = this.get_size();
// scale margin to window size
margin = margin * size.height;
if (mode=='nodes') {
// get the extent of the nodes
var min = { x: null, y: null }, // TODO make infinity?
max = { x: null, y: null };
for (var node_id in this.nodes) {
var node = this.nodes[node_id];
if (min.x===null) min.x = node.x;
if (min.y===null) min.y = node.y;
if (max.x===null) max.x = node.x;
if (max.y===null) max.y = node.y;
min.x = Math.min(min.x, node.x);
min.y = Math.min(min.y, node.y);
max.x = Math.max(max.x, node.x);
max.y = Math.max(max.y, node.y);
}
// set the zoom
new_zoom = Math.min((size.width - margin*2) / (max.x - min.x),
(size.height - margin*2) / (max.y - min.y));
new_pos = { x: - (min.x * new_zoom) + margin + ((size.width - margin*2 - (max.x - min.x)*new_zoom) / 2),
y: - (min.y * new_zoom) + margin + ((size.height - margin*2 - (max.y - min.y)*new_zoom) / 2) };
} else if (mode=='canvas') {
// center the canvas
new_zoom = Math.min((size.width - margin*2) / (this.canvas.width),
(size.height - margin*2) / (this.canvas.height));
new_pos = { x: - (this.canvas.x * new_zoom) + margin + ((size.width - margin*2 - this.canvas.width*new_zoom) / 2),
y: - (this.canvas.y * new_zoom) + margin + ((size.height - margin*2 - this.canvas.height*new_zoom) / 2) };
} else {
return console.error('Did not recognize mode');
}
this.zoom_container.go_to(new_zoom, new_pos);
return null;
}
function get_size() {
return this.zoom_container.get_size();
}
function zoom_to_reaction(reaction_id) {
var reaction = this.reactions[reaction_id],
new_zoom = 0.5,
size = this.get_size(),
new_pos = { x: - reaction.label_x * new_zoom + size.width/2,
y: - reaction.label_y * new_zoom + size.height/2 };
this.zoom_container.go_to(new_zoom, new_pos);
}
function zoom_to_node(node_id) {
var node = this.nodes[node_id],
new_zoom = 0.5,
size = this.get_size(),
new_pos = { x: - node.label_x * new_zoom + size.width/2,
y: - node.label_y * new_zoom + size.height/2 };
this.zoom_container.go_to(new_zoom, new_pos);
}
function zoom_to_text_label(text_label_id) {
var text_label = this.text_labels[text_label_id],
new_zoom = 0.5,
size = this.get_size(),
new_pos = { x: - text_label.x * new_zoom + size.width/2,
y: - text_label.y * new_zoom + size.height/2 };
this.zoom_container.go_to(new_zoom, new_pos);
}
function highlight_reaction(reaction_id) {
this.highlight(this.sel.selectAll('#r'+reaction_id).selectAll('text'));
}
function highlight_node(node_id) {
this.highlight(this.sel.selectAll('#n'+node_id).selectAll('text'));
}
function highlight_text_label(text_label_id) {
this.highlight(this.sel.selectAll('#l'+text_label_id).selectAll('text'));
}
function highlight(sel) {
this.sel.selectAll('.highlight')
.classed('highlight', false);
if (sel !== null) {
sel.classed('highlight', true);
}
}
// -------------------------------------------------------------------------
// IO
function save() {
utils.download_json(this.map_for_export(), this.map_name);
}
function map_for_export() {
var out = [{ "map_name": this.map_name,
"map_id": this.map_id,
"map_description": this.map_description,
"homepage": "https://escher.github.io",
"schema": "https://escher.github.io/escher/jsonschema/1-0-0#"
},
{ reactions: utils.clone(this.reactions),
nodes: utils.clone(this.nodes),
text_labels: utils.clone(this.text_labels),
canvas: this.canvas.size_and_location() }
];
// remove extra data
for (var r_id in out[1].reactions) {
var reaction = out[1].reactions[r_id],
new_reaction = {};
['name', 'bigg_id','reversibility', 'label_x', 'label_y',
'gene_reaction_rule', 'genes', 'metabolites'
].forEach(function(attr) {
new_reaction[attr] = reaction[attr];
});
new_reaction['segments'] = {};
for (var s_id in reaction.segments) {
var segment = reaction.segments[s_id],
new_segment = {};
['from_node_id', 'to_node_id', 'b1', 'b2'
].forEach(function(attr) {
new_segment[attr] = segment[attr];
});
new_reaction['segments'][s_id] = new_segment;
}
out[1].reactions[r_id] = new_reaction;
}
for (var n_id in out[1].nodes) {
var node = out[1].nodes[n_id],
new_node = {},
attrs;
if (node.node_type == 'metabolite') {
attrs = ['node_type', 'x', 'y', 'bigg_id', 'name', 'label_x', 'label_y',
'node_is_primary'];
} else {
attrs = ['node_type', 'x', 'y'];
}
attrs.forEach(function(attr) {
new_node[attr] = node[attr];
});
out[1].nodes[n_id] = new_node;
}
for (var t_id in out[1].text_labels) {
var text_label = out[1].text_labels[t_id],
new_text_label = {},
attrs = ["x", "y", "text"];
attrs.forEach(function(attr) {
new_text_label[attr] = text_label[attr];
});
out[1].text_labels[t_id] = new_text_label;
}
// canvas
var canvas_el = out[1].canvas,
new_canvas_el = {},
attrs = ["x", "y", "width", "height"];
attrs.forEach(function(attr) {
new_canvas_el[attr] = canvas_el[attr];
});
out[1].canvas = new_canvas_el;
if (this.debug) {
d3.json('jsonschema/1-0-0', function(error, schema) {
if (error) throw new Error(error);
if (!tv4.validate(out, schema))
console.warn(tv4.error);
});
}
return out;
}
function save_svg() {
// run the before callback
this.callback_manager.run('before_svg_export');
// turn of zoom and translate so that illustrator likes the map
var window_scale = this.zoom_container.window_scale,
window_translate = this.zoom_container.window_translate,
canvas_size_and_loc = this.canvas.size_and_location(),
mouse_node_size_and_trans = { w: this.canvas.mouse_node.attr('width'),
h: this.canvas.mouse_node.attr('height'),
transform: this.canvas.mouse_node.attr('transform')};
this.zoom_container.go_to(1.0, {x: -canvas_size_and_loc.x, y: -canvas_size_and_loc.y}, false);
this.svg.attr('width', canvas_size_and_loc.width);
this.svg.attr('height', canvas_size_and_loc.height);
this.canvas.mouse_node.attr('width', '0px');
this.canvas.mouse_node.attr('height', '0px');
this.canvas.mouse_node.attr('transform', null);
// hide the segment control points
var hidden_sel = this.sel.selectAll('.multimarker-circle,.midmarker-circle,#canvas')
.style('visibility', 'hidden');
// do the epxort
utils.export_svg('saved_map', this.svg, true);
// revert everything
this.zoom_container.go_to(window_scale, window_translate, false);
this.svg.attr('width', null);
this.svg.attr('height', null);
this.canvas.mouse_node.attr('width', mouse_node_size_and_trans.w);
this.canvas.mouse_node.attr('height', mouse_node_size_and_trans.h);
this.canvas.mouse_node.attr('transform', mouse_node_size_and_trans.transform);
// unhide the segment control points
hidden_sel.style('visibility', null);
// run the after callback
this.callback_manager.run('after_svg_export');
}
});
define('Brush',["utils"], function(utils) {
/** Define a brush to select elements in a map.
Arguments
---------
selection: A d3 selection to place the brush in.
is_enabled: Whether to turn the brush on.
map: An instance of escher.Map.
insert_after: A d3 selector string to choose the svg element that the brush
will be inserted after. Often a canvas element (e.g. '.canvas-group').
*/
var Brush = utils.make_class();
Brush.prototype = { init: init,
toggle: toggle,
setup_selection_brush: setup_selection_brush };
return Brush;
// definitions
function init(selection, is_enabled, map, insert_after) {
this.brush_sel = selection.append('g')
.attr('id', 'brush-container');
var node = this.brush_sel.node(),
insert_before_node = selection.select(insert_after).node().nextSibling;
if (!(node===insert_before_node))
node.parentNode.insertBefore(node, insert_before_node);
this.enabled = is_enabled;
this.map = map;
};
function brush_is_enabled() {
/** Returns a boolean for the on/off status of the brush
*/
return this.map.sel.select('.brush').empty();
}
function toggle(on_off) {
/** Turn the brush on or off
*/
if (on_off===undefined) on_off = !this.enabled;
if (on_off) {
this.selection_brush = this.setup_selection_brush();
} else {
this.brush_sel.selectAll('.brush').remove();
}
}
function setup_selection_brush() {
var selection = this.brush_sel,
selectable_selection = this.map.sel.selectAll('#nodes,#text-labels'),
size_and_location = this.map.canvas.size_and_location(),
width = size_and_location.width,
height = size_and_location.height,
x = size_and_location.x,
y = size_and_location.y;
// clear existing brush
selection.selectAll('g').remove();
var brush_fn = d3.svg.brush()
.x(d3.scale.identity().domain([x, x+width]))
.y(d3.scale.identity().domain([y, y+height]))
.on("brush", function(key_manager) {
var shift_key_on = key_manager.held_keys.shift,
extent = d3.event.target.extent(),
selection;
if (shift_key_on) {
// when shift is pressed, ignore the currently selected nodes
selection = selectable_selection
.selectAll('.node:not(.selected),.text-label:not(.selected)');
} else {
// otherwise, brush all nodes
selection = selectable_selection
.selectAll('.node,.text-label');
}
selection.classed("selected", function(d) {
var sx = d.x, sy = d.y;
return extent[0][0] <= sx && sx < extent[1][0]
&& extent[0][1] <= sy && sy < extent[1][1];
});
}.bind(null, this.map.key_manager))
.on("brushend", function() {
d3.event.target.clear();
d3.select(this).call(d3.event.target);
}),
brush = selection.append("g")
.attr("class", "brush")
.call(brush_fn);
// turn off the mouse crosshair
selection.selectAll('.background')
.classed('cursor-grab', false)
.classed('cursor-grabbing', false)
.style('cursor', null);
return brush;
}
});
define('ui',["utils", "data_styles"], function(utils, data_styles) {
return { individual_button: individual_button,
radio_button_group: radio_button_group,
button_group: button_group,
dropdown_menu: dropdown_menu,
set_json_input_button: set_json_input_button,
set_json_or_csv_input_button: set_json_or_csv_input_button };
function individual_button(s, button) {
var b = s.append('button'),
c = b.append('span');
if ('id' in button) b.attr('id', button.id);
if ('classes' in button) b.attr('class', button.classes);
// text
if ('key_text' in button && 'text' in button && button.key_text !== null)
c.text(button.text + button.key_text);
else if ('text' in button)
c.text(button.text);
if ('icon' in button) c.classed(button.icon, true);
if ('key' in button) set_button(b, button.key);
// if ('tooltip' in button)
b.attr('title', button.tooltip);
}
function radio_button_group(s) {
var s2 = s.append('li')
.attr('class', 'btn-group-vertical')
.attr('data-toggle', 'buttons');
return { button: function(button) {
var b = s2.append("label")
.attr("class", "btn btn-default");
b.append('input').attr('type', 'radio');
var c = b.append("span");
if ('id' in button) b.attr('id', button.id);
// text
if ('key_text' in button && 'text' in button && button.key_text !== null)
c.text(button.text + button.key_text);
else if ('text' in button)
c.text(button.text);
if ('icon' in button) c.classed(button.icon, true);
if ('key' in button) set_button(b, button.key);
if ('tooltip' in button) b.attr('title', button.tooltip);
return this;
}};
}
function button_group(s) {
var s2 = s.attr('class', 'btn-group-vertical');
return { button: function(button) {
var b = s2.append("button")
.attr("class", "btn btn-default");
var c = b.append("span");
if ('id' in button) b.attr('id', button.id);
// text
if ('key_text' in button && 'text' in button && button.key_text !== null)
c.text(button.text + button.key_text);
else if ('text' in button)
c.text(button.text);
if ('icon' in button) c.classed(button.icon, true);
if ('key' in button) set_button(b, button.key);
if ('tooltip' in button) b.attr('title', button.tooltip);
return this;
}};
}
function dropdown_menu(s, name, pull_right) {
if (pull_right === undefined) pull_right = false;
var s2 = s.append('li')
.attr('class', 'dropdown');
s2.append('button').text(name+" ")
.attr('class', 'btn btn-link btn-sm dropdown-button')
.attr('data-toggle', 'dropdown')
.append('b').attr('class', 'caret');
var ul = s2.append('ul')
.attr('class', 'dropdown-menu')
.classed('pull-right', pull_right)
.attr('role', 'menu')
.attr('aria-labelledby', 'dLabel');
return {
dropdown: s2,
button: function(button) {
var li = ul.append("li")
.attr('role', 'presentation')
.datum(button),
link = li.append("a")
.attr('href', '#'),
icon = link.append('span')
.attr('class', 'dropdown-button-icon'),
text = link.append('span')
.attr('class', 'dropdown-button-text');
if ('id' in button) li.attr('id', button.id);
// text
if ('key_text' in button && 'text' in button && button.key_text !== null)
text.text(" "+button.text + button.key_text);
else if ('text' in button)
text.text(" "+button.text);
if ('icon' in button) icon.classed(button.icon, true);
if ('key' in button) {
set_button(link, button.key);
} else if ('input' in button) {
var input = button.input,
out = (input.accept_csv ?
set_json_or_csv_input_button(link, li, input.pre_fn,
input.fn, input.failure_fn) :
set_json_input_button(link, li, input.pre_fn,
input.fn, input.failure_fn));
if ('assign' in input && 'key' in input)
input.assign[input.key] = out;
}
return this;
},
divider: function() {
ul.append("li")
.attr('role', 'presentation')
.attr('class', 'divider');
return this;
}
};
}
function set_button(b, key) {
b.on("click", function() {
key.fn.call(key.target);
});
}
function set_json_input_button(b, s, pre_fn, post_fn, failure_fn) {
var input = s.append("input")
.attr("type", "file")
.style("display", "none")
.on("change", function() {
utils.load_json(this.files[0],
function(e, d) {
post_fn(e, d);
this.value = "";
}.bind(this),
pre_fn,
failure_fn);
});
b.on('click', function(e) {
input.node().click();
});
return function() { input.node().click(); };
}
function set_json_or_csv_input_button(b, s, pre_fn, post_fn, failure_fn) {
var input = s.append("input")
.attr("type", "file")
.style("display", "none")
.on("change", function() {
utils.load_json_or_csv(this.files[0],
data_styles.csv_converter,
function(e, d) {
post_fn(e, d);
this.value = "";
}.bind(this),
pre_fn,
failure_fn);
});
b.on('click', function(e) {
input.node().click();
});
return function() { input.node().click(); };
}
});
define('SearchBar',["utils", "CallbackManager"], function(utils, CallbackManager) {
/**
*/
var SearchBar = utils.make_class();
// instance methods
SearchBar.prototype = { init: init,
is_visible: is_visible,
toggle: toggle,
update: update,
next: next,
previous: previous };
return SearchBar;
// instance methods
function init(sel, search_index, map) {
var container = sel.attr('class', 'search-container')
.style('display', 'none');
this.input = container.append('input')
.attr('class', 'search-bar');
var group = container.append('div').attr('class', 'btn-group btn-group-sm');
group.append('button')
.attr("class", "btn btn-default")
.on('click', this.previous.bind(this))
.append('span').attr('class', "glyphicon glyphicon-chevron-left");
group.append('button')
.attr("class", "btn btn-default")
.on('click', this.next.bind(this))
.append('span').attr('class', "glyphicon glyphicon-chevron-right");
this.counter = container.append('div')
.attr('class', 'search-counter');
container.append('button')
.attr("class", "btn btn-sm btn-default close-button")
.on('click', function() {
this.toggle(false);
}.bind(this))
.append("span").attr("class", "glyphicon glyphicon-remove");
this.callback_manager = new CallbackManager();
this.selection = container;
this.map = map;
this.search_index = search_index;
this.current = 1;
this.results = null;
var on_input_fn = function(input) {
this.current = 1;
this.results = this.search_index.find(input.value);
this.update();
}.bind(this, this.input.node());
this.input.on('input', utils.debounce(on_input_fn, 200));
}
function is_visible() {
return this.selection.style('display') != 'none';
}
function toggle(on_off) {
if (on_off===undefined) this.is_active = !this.is_active;
else this.is_active = on_off;
if (this.is_active) {
this.selection.style('display', null);
this.counter.text("");
this.input.node().value = "";
this.input.node().focus();
// escape key
this.escape = this.map.key_manager
.add_escape_listener(function() {
this.toggle(false);
}.bind(this), 'settings');
// enter key
this.enter = this.map.key_manager
.add_enter_listener(function() {
this.next();
}.bind(this), 'settings');
// run the show callback
this.callback_manager.run('show');
} else {
this.map.highlight(null);
this.selection.style("display", "none");
this.results = null;
if (this.escape) this.escape.clear();
this.escape = null;
if (this.enter) this.enter.clear();
this.enter = null;
// run the hide callback
this.callback_manager.run('hide');
}
}
function update() {
if (this.results == null) {
this.counter.text("");
this.map.highlight(null);
} else if (this.results.length == 0) {
this.counter.text("0 / 0");
this.map.highlight(null);
} else {
this.counter.text(this.current + " / " + this.results.length);
var r = this.results[this.current - 1];
if (r.type=='reaction') {
this.map.zoom_to_reaction(r.reaction_id);
this.map.highlight_reaction(r.reaction_id);
} else if (r.type=='metabolite') {
this.map.zoom_to_node(r.node_id);
this.map.highlight_node(r.node_id);
} else if (r.type=='text_label') {
this.map.zoom_to_text_label(r.text_label_id);
this.map.highlight_text_label(r.text_label_id);
} else {
throw new Error('Bad search index data type: ' + r.type);
}
}
}
function next() {
if (this.results == null) return;
if (this.current==this.results.length)
this.current = 1;
else
this.current += 1;
this.update();
}
function previous() {
if (this.results == null) return;
if (this.current==1)
this.current = this.results.length;
else
this.current -= 1;
this.update();
}
});
define('Settings',["utils", "lib/bacon"], function(utils, bacon) {
/** A class to manage settings for a Map.
Arguments
---------
set_option: A function, fn(key), that returns the option value for the
key.
get_option: A function, fn(key, value), that sets the option for the key
and value.
conditional_options: The options to that are conditionally accepted when
changed. Changes can be abandoned by calling abandon_changes(), or accepted
by calling accept_changes().
*/
var Settings = utils.make_class();
// instance methods
Settings.prototype = { init: init,
set_conditional: set_conditional,
hold_changes: hold_changes,
abandon_changes: abandon_changes,
accept_changes: accept_changes };
return Settings;
// instance methods
function init(set_option, get_option, conditional_options) {
this.set_option = set_option;
this.get_option = get_option;
// manage accepting/abandoning changes
this.status_bus = new bacon.Bus();
// force an update of ui components
this.force_update_bus = new bacon.Bus();
// modify bacon.observable
bacon.Observable.prototype.convert_to_conditional_stream = _convert_to_conditional_stream;
bacon.Observable.prototype.force_update_with_bus = _force_update_with_bus;
// create the options
this.busses = {};
this.streams = {};
for (var i = 0, l = conditional_options.length; i < l; i++) {
var name = conditional_options[i],
out = _create_conditional_setting(name, get_option(name), set_option,
this.status_bus, this.force_update_bus);
this.busses[name] = out.bus;
this.streams[name] = out.stream;
}
}
function _convert_to_conditional_stream(status_stream) {
/** Hold on to event when hold_property is true, and only keep them
if accept_property is true (when hold_property becomes false).
*/
// true if hold is pressed
var is_not_hold_event = status_stream
.map(function(x) { return x=='hold'; })
.not()
.toProperty(true),
is_not_first_clear = status_stream
.scan(false, function(c, x) {
// first clear only
return (c==false && (x=='accepted' || x=='rejected'));
}).not(),
is_not_first_hold = status_stream
.scan(false, function(c, x) {
// first clear only
return (c==false && x=='hold');
}).not(),
combined = bacon.combineAsArray(this, status_stream),
held = combined
.scan([], function(c, x) {
if (x[1]=='hold') {
c.push(x[0]);
return c;
} else if (x[1]=='accept') {
return c;
} else if (x[1]=='reject') {
return [];
} else if (x[1]=='rejected' || x[1]=='accepted') {
return [x[0]];
} else {
throw Error('bad status ' + x[1]);
}
})
// don't pass in events until the end of a hold
.filter(is_not_hold_event)
// ignore the event when clear is passed
.filter(is_not_first_clear)
// ignore the event when hold is passed
.filter(is_not_first_hold)
.flatMap(function(ar) {
return bacon.fromArray(ar);
}),
unheld = this.filter(is_not_hold_event);
return unheld.merge(held);
}
function _force_update_with_bus(bus) {
return bacon
.combineAsArray(this, bus.toProperty(false))
.map(function(t) {
return t[0];
});
}
function _create_conditional_setting(name, initial_value, set_option,
status_bus, force_update_bus) {
// set up the bus
var bus = new bacon.Bus();
// make the event stream
var stream = bus
// conditionally accept changes
.convert_to_conditional_stream(status_bus)
// force updates
.force_update_with_bus(force_update_bus);
// get the latest
stream.onValue(function(v) {
set_option(name, v);
});
// push the initial value
bus.push(initial_value);
return { bus: bus, stream: stream };
}
function set_conditional(name, value) {
/** Set the value of a conditional setting, one that will only be
accepted if this.accept_changes() is called.
Arguments
---------
name: The option name
value: The new value
*/
if (!(name in this.busses))
throw new Error('Invalid setting name');
this.busses[name].push(value);
}
function hold_changes() {
this.status_bus.push('hold');
}
function abandon_changes() {
this.status_bus.push('reject');
this.status_bus.push('rejected');
this.force_update_bus.push(true);
}
function accept_changes() {
this.status_bus.push('accept');
this.status_bus.push('accepted');
}
});
define('ScaleEditor',["utils", "lib/bacon"], function(utils, bacon) {
/** An interactive UI to edit color and size scales.
Attributes
----------
sel: A d3 selection.
type: A type, that should be unique on the page.
settings: The Settings object.
*/
var ScaleEditor = utils.make_class();
// instance methods
ScaleEditor.prototype = { init: init,
update: update,
update_no_data: update_no_data,
_data_not_loaded: _data_not_loaded };
return ScaleEditor;
// instance methods
function init(sel, type, settings, get_data_statistics) {
// sels
var grad_id = 'grad' + type + this.unique_string;
this.w = 400;
this.h = 30;
this.x = 20;
this.input_width = 90;
this.input_height = 24;
var b = sel.append('div')
.attr('class', 'scale-editor');
// no data loaded
this.data_not_loaded = b.append('div')
.attr('class', 'data-not-loaded')
.text((type == 'reaction' ? 'Reaction and gene' : 'Metabolite') + ' data not loaded');
// label
this.input_label_group = b.append('div')
.attr('class', 'input-label-group');
// no data
var nd = b.append('div')
.style('top', this.input_height * 3 + 56 + 10 + 'px')
.attr('class', 'no-data');
nd.append('span').text('Styles for ' + type + 's with no data')
.attr('class', 'no-data-heading');
this.no_data_container = nd.append('div');
var c = b.append('div')
.attr('class', 'centered');
this.add_group = c.append('div');
this.trash_group = c.append('div')
.attr('class', 'trash-container');
var svg = c.append('svg')
.attr('class', 'scale-svg');
this.input_group = c.append('div')
.attr('class', 'input-container');
this.gradient = svg.append('defs')
.append('linearGradient')
.attr('id', grad_id);
svg.append('rect')
.attr('class', 'rect')
.attr('fill', 'url(#' + grad_id + ')')
.attr('width', this.w + 'px')
.attr('height', this.h + 'px')
.attr('x', this.x + 'px'),
this.pickers_group = svg.append('g');
// settings
this.type = type;
this.settings = settings;
this.get_data_statistics = get_data_statistics;
var unique_map_id = this.settings.get_option('unique_map_id');
this.unique_string = (unique_map_id === null ? '' : '.' + unique_map_id);
// collect data
this.no_data = {};
['color', 'size'].forEach(function(s) {
this.no_data[s] = null;
this.settings.streams[this.type + '_no_data_' + s].onValue(function(val) {
this.no_data[s] = val;
this.update_no_data();
}.bind(this));
}.bind(this));
this.settings.streams[type + '_scale'].onValue(function(scale) {
this.scale = scale;
this.update();
}.bind(this));
}
function update() {
var scale = this.scale,
stats = this.get_data_statistics()[this.type],
bar_w = 14,
bar_h = 35,
x_disp = this.x,
data_not_loaded = this._data_not_loaded();
// Must have max and min. Otherwise, assume that no data is loaded.
if (data_not_loaded) {
scale = [{ type: 'min', 'color': null, 'size': null },
{ type: 'max', 'color': null, 'size': null }];
stats = { 'min': 0, 'max': 1 };
}
var sc = d3.scale.linear()
.domain([0, this.w])
.range([stats.min, stats.max]),
sc_size = d3.scale.linear()
.domain([0, this.w])
.range([0, stats.max - stats.min]);
// ---------------------------------------------------------------------
// convenience functions
var bring_to_front = function(d, i) {
// bring an input set to the front
this.input_group.selectAll('.input-set').each(function(d2) {
d3.select(this).classed('selected-set', d === d2);
});
}.bind(this);
var get_this_val = function(d) {
return (d.type == 'value') ? d.value : stats[d.type];
};
var set_scale = function(scale) {
this.settings.set_conditional(this.type + '_scale', scale);
this.scale = scale;
this.update();
}.bind(this);
// ---------------------------------------------------------------------
// make the gradient
var sorted_domain = scale.map(function(d) {
return { frac: (get_this_val(d) - stats.min) / (stats.max - stats.min),
color: d.color };
}).filter(function(d) {
return (d.frac >= 0 && d.frac <= 1.0);
}).sort(function(a, b) {
return a.frac - b.frac;
});
var stops = this.gradient.selectAll('stop')
.data(sorted_domain);
stops.enter()
.append('stop');
stops.attr('offset', function(d) {
return d.frac * 100 + '%';
}).style('stop-color', function (d) {
return d.color === null ? '#F1ECFA' : d.color;
});
stops.exit().remove();
// ---------------------------------------------------------------------
// no data sign
this.data_not_loaded.style('visibility', (data_not_loaded ? null : 'hidden'));
// ---------------------------------------------------------------------
// make the pickers
var pickers = this.pickers_group
.selectAll('.picker')
.data(scale);
// drag
var drag = d3.behavior.drag();
drag.on('drag', function(d, i) {
// on drag, make it a value type
if (['value', 'min', 'max'].indexOf(scale[i].type) === -1) {
// get the current value and set it
scale[i].value = get_this_val(d);
scale[i].type = 'value';
}
// change the model on drag
var new_d = scale[i].value + sc_size(d3.event.dx),
buf = sc_size(bar_w + 2);
if (new_d > stats.max - buf) new_d = stats.max - buf;
if (new_d < stats.min + buf) new_d = stats.min + buf;
// round to 2 decimals
new_d = Math.floor(new_d * 100.0) / 100.0;
scale[i].value = new_d;
this.settings.set_conditional(this.type + '_scale', scale);
this.scale = scale;
this.update();
}.bind(this));
// enter
pickers.enter()
.append('g')
.attr('class', 'picker')
.style('cursor', 'pointer')
.append('rect');
// update
pickers.select('rect')
.attr('x', function(d, i) {
var val = get_this_val(d),
buf = bar_w + 2;
if (d.type == 'value' && val <= stats.min)
return sc.invert(stats.min) - (bar_w / 2) + x_disp - buf;
if (d.type == 'value' && val >= stats.max)
return sc.invert(stats.max) - (bar_w / 2) + x_disp + buf;
return sc.invert(val) - (bar_w / 2) + x_disp;
})
.attr('width', bar_w + 'px')
.attr('height', bar_h + 'px')
.call(drag)
.on('mousedown', bring_to_front);
// exit
pickers.exit().remove();
// ---------------------------------------------------------------------
// make the delete buttons
var trashes = this.trash_group.selectAll('span')
.data(scale);
// enter
trashes.enter()
.append('span');
// update
trashes.attr('class', function(d, i) {
if (d.type == 'min' || d.type == 'max')
return null;
return 'trash glyphicon glyphicon-trash';
}).style('left', function(d) {
return sc.invert(get_this_val(d)) - (bar_w / 2) + x_disp + 'px';
}).on('click', function (d, i) {
if (d.type == 'min' || d.type == 'max')
return;
scale = scale.slice(0, i).concat(scale.slice(i + 1));
this.settings.set_conditional(this.type + '_scale', scale);
this.scale = scale;
this.update();
}.bind(this));
// exit
trashes.exit().remove();
// ---------------------------------------------------------------------
// make the add button
var add = this.add_group.selectAll('.add')
.data(['add']);
// enter
add.enter()
.append('span')
.attr('class', 'add glyphicon glyphicon-plus');
// update
add.on('click', function (d) {
if (data_not_loaded) return;
var new_d = (stats.max + stats.min) / 2,
buf = sc_size(bar_w + 2),
last_ind = 0;
// try to make the new point not overlap
for (var j = 0, l = scale.length; j < l; j++) {
var th = get_this_val(scale[j]);
if (Math.abs(th - new_d) < buf) {
new_d = new_d + buf;
if (new_d > stats.max - buf) new_d = stats.max - buf;
if (new_d < stats.min + buf) new_d = stats.min + buf;
}
if (new_d > th)
last_ind = j;
}
// add
scale.push({ type: 'value',
value: new_d,
color: scale[last_ind].color,
size: scale[last_ind].size });
set_scale(scale);
}.bind(this));
// exit
add.exit().remove();
// ---------------------------------------------------------------------
// input labels
var labels = this.input_label_group.selectAll('.row-label')
.data(['Value:', 'Color:', 'Size:']);
// enter
labels.enter().append('div')
.attr('class', 'row-label')
.style('height', this.input_height + 'px')
.style('line-height', this.input_height + 'px');
// update
labels
.style('top', function(d, i) {
return 56 + (i * this.input_height) + 'px';
}.bind(this))
.text(function(d) { return d; });
// exit
labels.exit().remove();
// ---------------------------------------------------------------------
// inputs
var inputs = this.input_group.selectAll('.input-set')
.data(scale);
// enter
var i = inputs.enter()
.append('div')
.attr('class', 'input-set');
i.append('input')
.attr('class', 'domain-input')
.style('width', this.input_width + 'px');
// type picker
i.append('select')
.attr('class', 'domain-type-picker'),
// color input
i.append('input')
.attr('class', 'color-input')
.style('width', this.input_width + 'px');
i.append('input')
.attr('type', 'color')
.style('visibility', function() {
// hide the input if the HTML5 color picker is not supported
return (this.type == 'text') ? 'hidden' : null;
})
.attr('class', 'color-picker');
i.append('input')
.attr('class', 'size-input')
.style('width', this.input_width + 'px');
// update
inputs.style('height', this.input_height * 3 + 'px')
.style('width', this.input_width + 'px')
.style('left', function(d) {
var val = get_this_val(d),
buf = bar_w + 2,
l;
if (d.type == 'value' && val <= stats.min)
l = sc.invert(stats.min) - (bar_w / 2) + x_disp - buf;
else if (d.type == 'value' && val >= stats.max)
l = sc.invert(stats.max) - (bar_w / 2) + x_disp + buf;
else
l = sc.invert(val) - (bar_w / 2) + x_disp;
// don't go over the right edge of the bar
if (l + this.input_width > this.w + this.x)
l = l - this.input_width + (bar_w / 2);
return l + 'px';
}.bind(this))
.on('mousedown', bring_to_front);
var format = d3.format('.4g');
inputs.select('.domain-input')
.style('height', this.input_height + 'px')
.each(function (d, i) {
if (d.type == 'value') {
this.value = get_this_val(d);
this.disabled = false;
} else {
this.value = d.type + ' (' + format(get_this_val(d)) + ')';
this.disabled = true;
}
}).on('change', function(d, i) {
var buf = sc_size(bar_w + 2),
new_d = parseFloat(this.value);
scale[i].value = new_d;
set_scale(scale);
});
// update type picker
var select = inputs.select('.domain-type-picker'),
// get the function types, except min and max
stat_types = (['value'].concat(Object.keys(stats))
.filter(function(x) {
return x != 'min' && x != 'max';
})),
opts = select.selectAll('option').data(stat_types);
opts.enter().append('option');
opts.attr('value', function(d) { return d; })
.text(function(d) { return d; });
opts.exit().remove();
select.style('visibility', function(d) {
return (d.type == 'min' || d.type == 'max') ? 'hidden' : null;
})
.style('left', (this.input_width - 20) + 'px')
.style('width', '20px')
.each(function (d, i) {
var sind = 0;
d3.select(this).selectAll('option').each(function(_, i) {
if (this.value == d.type)
sind = i;
});
this.selectedIndex = sind;
}).on('change', function(d, i) {
// set the value to the current location
if (this.value == 'value')
scale[i].value = stats[d.type];
// switch to the new type
scale[i].type = this.value;
// reload
set_scale(scale);
});
// update color input
inputs.select('.color-input')
.style('height', this.input_height + 'px')
.style('top', this.input_height + 'px')
.each(function (d, i) {
this.value = (d.color === null ? '' : d.color);
this.disabled = (d.color === null);
}).on('change', function(d, i) {
scale[i].color = this.value;
set_scale(scale);
});
inputs.select('.color-picker')
.style('left', (this.input_width - this.input_height) + 'px')
.style('top', this.input_height + 'px')
.style('width', this.input_height + 'px')
.style('height', this.input_height + 'px')
.each(function (d, i) {
this.value = (d.color === null ? '#dddddd' : d.color);
this.disabled = (d.color === null);
}).on('change', function(d, i) {
scale[i].color = this.value;
set_scale(scale);
});
inputs.select('.size-input')
.style('height', this.input_height + 'px')
.style('top', this.input_height * 2 + 'px')
.each(function (d, i) {
this.value = (d.size === null ? '' : d.size);
this.disabled = (d.size === null);
}).on('change', function(d, i) {
scale[i].size = parseFloat(this.value);
set_scale(scale);
});
// exit
inputs.exit().remove();
}
function update_no_data() {
var no_data = this.no_data,
data_not_loaded = this._data_not_loaded(),
label_w = 40;
var ins = this.no_data_container
.selectAll('.input-group')
.data([['color', 'Color:'], ['size', 'Size:']]);
// enter
var t = ins.enter().append('div')
.attr('class', 'input-group');
t.append('span');
t.append('input');
t.append('input')
.attr('type', 'color')
.style('visibility', function(d) {
// hide the input if the HTML5 color picker is not supported,
// or if this is a size box
return (this.type == 'text' || d[0] != 'color') ? 'hidden' : null;
})
.attr('class', 'color-picker');
// update
ins.select('span')
.text(function(d) { return d[1]; })
.style('height', this.input_height + 'px')
.style('line-height', this.input_height + 'px')
.style('left', function(d, i) {
return ((label_w + this.input_width + 10) * i) + 'px';
}.bind(this));
var get_o = function(kind) {
return this.settings.get_option(this.type + '_no_data_' + kind);
}.bind(this);
ins.select('input')
.style('left', function(d, i) {
return (label_w + (label_w + this.input_width + 10) * i) + 'px';
}.bind(this))
.style('height', this.input_height + 'px')
.style('width', this.input_width + 'px')
.each(function(d) {
// initial value
this.value = data_not_loaded ? '' : no_data[d[0]];
this.disabled = data_not_loaded;
})
.on('change', function(d) {
var val = d3.event.target.value;
if (d[0] == 'size')
val = parseFloat(val);
this.no_data[d[0]] = val;
this.settings.set_conditional(this.type + '_no_data_' + d[0], val);
this.update_no_data();
}.bind(this));
ins.select('.color-picker')
.style('left', function(d, i) {
return ((label_w + this.input_width) * (i + 1) - this.input_height) + 'px';
}.bind(this))
.style('width', this.input_height + 'px')
.style('height', this.input_height + 'px')
.each(function (d, i) {
this.value = data_not_loaded ? '#dddddd' : no_data[d[0]];
this.disabled = data_not_loaded;
})
.on('change', function(d, i) {
var val = d3.event.target.value;
this.no_data[d[0]] = val;
this.settings.set_conditional(this.type + '_no_data_' + d[0], val);
this.update_no_data();
}.bind(this));
// exit
ins.exit().remove();
}
function _data_not_loaded() {
var stats = this.get_data_statistics()[this.type];
return (stats.max === null || stats.min === null);
}
});
define('SettingsMenu',["utils", "CallbackManager", "ScaleEditor"], function(utils, CallbackManager, ScaleEditor) {
/**
*/
var SettingsMenu = utils.make_class();
// instance methods
SettingsMenu.prototype = { init: init,
is_visible: is_visible,
toggle: toggle,
hold_changes: hold_changes,
abandon_changes: abandon_changes,
accept_changes: accept_changes,
style_gui: style_gui,
view_gui: view_gui };
return SettingsMenu;
// instance methods
function init(sel, settings, map, toggle_abs_and_apply_data) {
this.sel = sel;
this.settings = settings;
this.draw = false;
var unique_map_id = this.settings.get_option('unique_map_id');
this.unique_string = (unique_map_id === null ? '' : '.' + unique_map_id);
var background = sel.append('div')
.attr('class', 'settings-box-background')
.style('display', 'none'),
container = background.append('div')
.attr('class', 'settings-box-container')
.style('display', 'none');
// done button
container.append('button')
.attr("class", "btn btn-sm btn-default settings-button")
.on('click', function() {
this.accept_changes();
}.bind(this))
.append("span").attr("class", "glyphicon glyphicon-ok");
// quit button
container.append('button')
.attr("class", "btn btn-sm btn-default settings-button settings-button-close")
.on('click', function() {
this.abandon_changes();
}.bind(this))
.append("span").attr("class", "glyphicon glyphicon-remove");
var box = container.append('div')
.attr('class', 'settings-box');
// Tip
box.append('div')
.text('Tip: Hover over an option to see more details about it.')
.classed('settings-tip', true);
box.append('hr');
// view and build
box.append('div').text('View and build options')
.attr('class', 'settings-section-heading-large');
this.view_gui(box.append('div'));
// reactions
box.append('hr');
box.append('div')
.text('Reactions').attr('class', 'settings-section-heading-large');
var rse = new ScaleEditor(box.append('div'), 'reaction', this.settings,
map.get_data_statistics.bind(map));
map.callback_manager.set('calc_data_stats__reaction', function(changed) {
if (changed) {
rse.update();
rse.update_no_data();
}
});
box.append('div')
.text('Reaction or Gene data').attr('class', 'settings-section-heading');
this.style_gui(box.append('div'), 'reaction', function(on_off) {
if (toggle_abs_and_apply_data) {
toggle_abs_and_apply_data('reaction', on_off);
rse.update();
rse.update_no_data();
}
});
// metabolite data
box.append('hr');
box.append('div').text('Metabolites')
.attr('class', 'settings-section-heading-large');
var mse = new ScaleEditor(box.append('div'), 'metabolite', this.settings,
map.get_data_statistics.bind(map));
map.callback_manager.set('calc_data_stats__metabolite', function(changed) {
if (changed) {
mse.update();
mse.update_no_data();
}
});
box.append('div').text('Metabolite data')
.attr('class', 'settings-section-heading');
this.style_gui(box.append('div'), 'metabolite', function(on_off) {
if (toggle_abs_and_apply_data) {
toggle_abs_and_apply_data('metabolite', on_off);
mse.update();
mse.update_no_data();
}
});
this.callback_manager = new CallbackManager();
this.map = map;
this.selection = container;
this.background = background;
}
function is_visible() {
return this.selection.style('display') != 'none';
}
function toggle(on_off) {
if (on_off===undefined) on_off = !this.is_visible();
if (on_off) {
// hold changes until accepting/abandoning
this.hold_changes();
// show the menu
this.selection.style("display", "inline-block");
this.background.style("display", "block");
this.selection.select('input').node().focus();
// escape key
this.escape = this.map.key_manager
.add_escape_listener(function() {
this.abandon_changes();
}.bind(this), 'settings');
// enter key
this.enter = this.map.key_manager
.add_enter_listener(function() {
this.accept_changes();
}.bind(this), 'settings');
// run the show callback
this.callback_manager.run('show');
} else {
// draw on finish
if (this.draw) this.map.draw_everything();
// hide the menu
this.selection.style("display", "none");
this.background.style("display", "none");
if (this.escape) this.escape.clear();
if (this.enter) this.enter.clear();
this.escape = null;
this.enter = null;
// run the hide callback
this.callback_manager.run('hide');
}
}
function hold_changes() {
this.settings.hold_changes();
}
function abandon_changes() {
this.draw = false;
this.settings.abandon_changes();
this.toggle(false);
}
function accept_changes() {
this.sel.selectAll('input').each(function (s) {
this.blur();
});
this.draw = true;
this.settings.accept_changes();
this.toggle(false);
}
function style_gui(sel, type, abs_callback) {
/** A UI to edit style.
*/
var t = sel.append('table').attr('class', 'settings-table'),
settings = this.settings;
// styles
t.append('tr').call(function(r) {
r.append('td').text('Options:')
.attr('class', 'options-label')
.attr('title', ('Options for ' + type + ' data.'));
var cell = r.append('td');
var styles = [['Absolute value', 'abs',
('If checked, use the absolute value when ' +
'calculating colors and sizes of ' + type + 's on the map')],
['Size', 'size',
('If checked, then size the ' +
(type == 'metabolite' ? 'radius of metabolite circles ' : 'thickness of reaction lines ') +
'according to the value of the ' + type + ' data')],
['Color', 'color',
('If checked, then color the ' +
(type == 'metabolite' ? 'metabolite circles ' : 'reaction lines ') +
'according to the value of the ' + type + ' data')],
['Text (Show data in label)', 'text',
('If checked, then show data values in the ' + type + ' ' +
'labels')]],
style_cells = cell.selectAll('.option-group')
.data(styles),
s = style_cells.enter()
.append('label')
.attr('class', 'option-group');
// make the checkbox
var streams = [],
get_styles = function() {
var styles = [];
cell.selectAll('input')
.each(function(d) { if (this.checked) styles.push(d[1]); });
return styles;
};
s.append('input').attr('type', 'checkbox')
.on('change', function(d) {
settings.set_conditional(type + '_styles', get_styles());
if (d[1] == 'abs')
abs_callback(this.checked);
}).each(function(d) {
// subscribe to changes in the model
settings.streams[type + '_styles'].onValue(function(ar) {
// check the box if the style is present
this.checked = (ar.indexOf(d[1]) != -1);
}.bind(this));
});
s.append('span')
.text(function(d) { return d[0]; })
.attr('title', function(d) { return d[2]; });
});
// compare_style
t.append('tr').call(function(r) {
r.append('td')
.text('Comparison:')
.attr('class', 'options-label')
.attr('title', ('The function that will be used to compare ' +
'datasets, when paired data is loaded'));
var cell = r.append('td')
.attr('title', ('The function that will be used to compare ' +
'datasets, when paired data is loaded'));;
var styles = [['Fold Change', 'fold'],
['Log2(Fold Change)', 'log2_fold'],
['Difference', 'diff']],
style_cells = cell.selectAll('.option-group')
.data(styles),
s = style_cells.enter()
.append('label')
.attr('class', 'option-group');
// make the radio
s.append('input').attr('type', 'radio')
.attr('name', type + '_compare_style' + this.unique_string)
.attr('value', function(d) { return d[1]; })
.on('change', function() {
if (this.checked)
settings.set_conditional(type + '_compare_style', this.value);
})
.each(function() {
// subscribe to changes in the model
settings.streams[type + '_compare_style'].onValue(function(value) {
// check the box for the new value
this.checked = (this.value == value);
}.bind(this));
});
s.append('span')
.text(function(d) { return d[0]; });
}.bind(this));
// gene-specific settings
if (type=='reaction') {
var t = sel.append('table').attr('class', 'settings-table')
.attr('title', ('The function that will be used to evaluate ' +
'AND connections in gene reaction rules (AND ' +
'connections generally connect components of ' +
'an enzyme complex)'));
// and_method_in_gene_reaction_rule
t.append('tr').call(function(r) {
r.append('td')
.text('Method for evaluating AND:')
.attr('class', 'options-label-wide');
var cell = r.append('td');
var styles = [['Mean', 'mean'], ['Min', 'min']],
style_cells = cell.selectAll('.option-group')
.data(styles),
s = style_cells.enter()
.append('label')
.attr('class', 'option-group');
// make the radio
var name = 'and_method_in_gene_reaction_rule';
s.append('input').attr('type', 'radio')
.attr('name', name + this.unique_string)
.attr('value', function(d) { return d[1]; })
.on('change', function() {
if (this.checked)
settings.set_conditional(name, this.value);
})
.each(function() {
// subscribe to changes in the model
settings.streams[name].onValue(function(value) {
// check the box for the new value
this.checked = (this.value == value);
}.bind(this));
});
s.append('span')
.text(function(d) { return d[0]; });
}.bind(this));
}
}
function view_gui(s, option_name, string, options) {
// columns
var settings = this.settings;
var t = s.append('table').attr('class', 'settings-table');
t.append('tr').call(function(r) {
// identifiers
r.attr('title', ('The identifiers that are show in the reaction, ' +
'gene, and metabolite labels on the map.'));
r.append('td').text('Identifiers:')
.attr('class', 'options-label');
var cell = r.append('td');
var options = [['ID\'s', 'bigg_id'], ['Descriptive names', 'name']],
style_cells = cell.selectAll('.option-group')
.data(options),
s = style_cells.enter()
.append('label')
.attr('class', 'option-group');
// make the checkbox
var name = 'identifiers_on_map';
s.append('input').attr('type', 'radio')
.attr('name', name + this.unique_string)
.attr('value', function(d) { return d[1]; })
.on('change', function() {
if (this.checked)
settings.set_conditional(name, this.value);
})
.each(function() {
// subscribe to changes in the model
settings.streams[name].onValue(function(value) {
// check the box for the new value
this.checked = (this.value == value);
}.bind(this));
});
s.append('span').text(function(d) { return d[0]; });
}.bind(this));
var boolean_options = [
['scroll_behavior', 'Scroll to zoom (instead of scroll to pan)',
('If checked, then the scroll wheel and trackpad will control zoom ' +
'rather than pan.'), {'zoom': true, 'pan': false}],
['hide_secondary_metabolites', 'Hide secondary metabolites',
('If checked, then only the primary metabolites ' +
'will be displayed.')],
['show_gene_reaction_rules', 'Show gene reaction rules',
('If checked, then gene reaction rules will be displayed ' +
'below each reaction label. (Gene reaction rules are always ' +
'shown when gene data is loaded.)')],
['hide_all_labels', 'Hide reaction, gene, and metabolite labels',
('If checked, hide all reaction, gene, and metabolite labels')],
['allow_building_duplicate_reactions', 'Allow duplicate reactions',
('If checked, then allow duplicate reactions during model building.')],
['highlight_missing', 'Highlight reactions not in model',
('If checked, then highlight in red all the ' +
'reactions on the map that are not present in ' +
'the loaded model.')],
];
var opts = s.append('div').attr('class', 'settings-container')
.selectAll('.option-group')
.data(boolean_options);
// enter
var e = opts.enter()
.append('label')
.attr('class', 'option-group full-line');
e.append('input').attr('type', 'checkbox');
e.append('span');
// update
opts.attr('title', function(d) { return d[2]; });
opts.select('input')
.on('change', function(d) {
if (d.length >= 4) { // not a boolean setting
for (var key in d[3]) {
if (d[3][key] == this.checked) {
settings.set_conditional(d[0], key);
break;
}
}
} else { // boolean setting
settings.set_conditional(d[0], this.checked);
}
})
.each(function(d) {
settings.streams[d[0]].onValue(function(value) {
if (d.length >= 4) { // not a boolean setting
this.checked = d[3][value];
} else { // boolean setting
this.checked = value;
}
}.bind(this));
});
opts.select('span')
.text(function(d) { return d[1]; });
// exit
opts.exit().remove();
// message about text performance
s.append('div')
.style('margin-top', '16px')
.classed('settings-tip', true)
.text('Tip: To increase map performance, turn off text boxes (i.e. labels and gene reaction rules).');
}
});
define('TextEditInput',['utils', 'PlacedDiv', 'build'], function(utils, PlacedDiv, build) {
/**
*/
var TextEditInput = utils.make_class();
// instance methods
TextEditInput.prototype = { init: init,
setup_map_callbacks: setup_map_callbacks,
setup_zoom_callbacks: setup_zoom_callbacks,
is_visible: is_visible,
show: show,
hide: hide,
_accept_changes: _accept_changes,
_add_and_edit: _add_and_edit };
return TextEditInput;
// definitions
function init(selection, map, zoom_container) {
var div = selection.append('div')
.attr('id', 'text-edit-input');
this.placed_div = PlacedDiv(div, map);
this.placed_div.hide();
this.input = div.append('input');
this.map = map;
this.setup_map_callbacks(map);
this.zoom_container = zoom_container;
this.setup_zoom_callbacks(zoom_container);
}
function setup_map_callbacks(map) {
// input
map.callback_manager.set('edit_text_label.text_edit_input', function(target, coords) {
this.show(target, coords);
}.bind(this));
// new text_label
map.callback_manager.set('new_text_label.text_edit_input', function(coords) {
if (this.active_target !== null)
this._accept_changes(this.active_target.target);
this.hide();
this._add_and_edit(coords);
}.bind(this));
map.callback_manager.set('hide_text_label_editor.text_edit_input', function() {
this.hide();
}.bind(this));
}
function setup_zoom_callbacks(zoom_container) {
zoom_container.callback_manager.set('zoom.text_edit_input', function() {
if (this.active_target)
this._accept_changes(this.active_target.target);
this.hide();
}.bind(this));
zoom_container.callback_manager.set('go_to.text_edit_input', function() {
if (this.active_target)
this._accept_changes(this.active_target.target);
this.hide();
}.bind(this));
}
function is_visible() {
return this.placed_div.is_visible();
}
function show(target, coords) {
// save any existing edit
if (this.active_target) {
this._accept_changes(this.active_target.target);
}
// set the current target
this.active_target = { target: target,
coords: coords };
// set the new value
target.each(function(d) {
this.input.node().value = d.text;
}.bind(this));
// place the input
this.placed_div.place(coords);
this.input.node().focus();
// escape key
this.escape = this.map.key_manager
.add_escape_listener(function() {
this._accept_changes(target);
this.hide();
}.bind(this));
// enter key
this.enter = this.map.key_manager
.add_enter_listener(function(target) {
this._accept_changes(target);
this.hide();
}.bind(this, target));
}
function hide() {
// hide the input
this.placed_div.hide();
// clear the value
this.input.attr('value', '');
this.active_target = null;
// clear escape
if (this.escape)
this.escape.clear();
this.escape = null;
// clear enter
if (this.enter)
this.enter.clear();
this.enter = null;
// turn off click listener
// this.map.sel.on('click.', null);
}
function _accept_changes(target) {
if (this.input.node().value == '') {
// delete the label
target.each(function(d) {
var selected = {};
selected[d.text_label_id] = this.map.text_labels[d.text_label_id];
this.map.delete_selectable({}, selected, true);
}.bind(this));
} else {
// set the text
var text_label_ids = [];
target.each(function(d) {
this.map.edit_text_label(d.text_label_id, this.input.node().value, true);
text_label_ids.push(d.text_label_id);
}.bind(this));
}
}
function _add_and_edit(coords) {
// make an empty label
var text_label_id = this.map.new_text_label(coords, '');
// apply the cursor to the new label
var sel = this.map.sel.select('#text-labels').selectAll('.text-label')
.filter(function(d) { return d.text_label_id == text_label_id; });
sel.select('text').classed('edit-text-cursor', true);
this.show(sel, coords);
}
});
define('QuickJump',['utils'], function(utils) {
/** A QuickJump menu to move between maps.
Arguments
---------
sel: The d3 selection of an html node to place the menu inside.
options: An array of map names to jump to.
load_callback: A callback function that accepts two arguments: map_name,
and another callback which returns true or false for success or failure
(callback purgatory).
*/
var QuickJump = utils.make_class();
// instance methods
QuickJump.prototype = { init: init,
reset_selection: reset_selection,
replace_state_for_map_name: replace_state_for_map_name };
return QuickJump;
// instance methods
function init(sel, load_callback) {
// set up the menu
var select_sel = sel.append('select')
.attr('id', 'quick-jump-menu')
.attr('class', 'form-control');
this.selector = select_sel;
// get the options to show
var url_comp = utils.parse_url_components(window),
current = ('map_name' in url_comp) ? url_comp.map_name : null,
quick_jump_path = ('quick_jump_path' in url_comp) ? url_comp.quick_jump_path : null,
options = ('quick_jump' in url_comp) ? url_comp.quick_jump : [],
default_value = '— Jump to map —',
view_options = [default_value].concat(options);
if (current !== null) {
view_options = view_options.filter(function(o) {
return o != current;
});
}
select_sel.selectAll('option')
.data(view_options)
.enter()
.append('option')
.text(function(d) {
// works whether or not a '.' is present
return d.split('.').slice(-1)[0];
});
// only show if there are options
select_sel.style('display', view_options.length > 1 ? 'block' : 'none');
// on selection
var change_map = function(map_name) {
load_callback(map_name, quick_jump_path, function(success) {
if (success)
this.replace_state_for_map_name(map_name);
else
this.reset_selection();
}.bind(this));
}.bind(this);
select_sel.on('change', function() {
// get the new map
var map_name = this.options[this.selectedIndex].__data__;
change_map(map_name);
});
}
function reset_selection() {
this.selector.node().selectedIndex = 0;
}
function replace_state_for_map_name(map_name) {
/** Just changes the url to match the new map name. Does not actually
manage the HTML5 history.
*/
// update the url with the new map
var url = window.location.href
.replace(/(map_name=)([^&]+)(&|$)/, '$1' + map_name + '$3');
window.history.replaceState('Not implemented', '', url);
}
});
define('Builder',['utils', 'BuildInput', 'ZoomContainer', 'Map', 'CobraModel', 'Brush', 'CallbackManager', 'ui', 'SearchBar', 'Settings', 'SettingsMenu', 'TextEditInput', 'QuickJump', 'data_styles'], function(utils, BuildInput, ZoomContainer, Map, CobraModel, Brush, CallbackManager, ui, SearchBar, Settings, SettingsMenu, TextEditInput, QuickJump, data_styles) {
/** For documentation of this class, see docs/javascript_api.rst
*/
var Builder = utils.make_class();
Builder.prototype = { init: init,
load_map: load_map,
load_model: load_model,
_set_mode: _set_mode,
view_mode: view_mode,
build_mode: build_mode,
brush_mode: brush_mode,
zoom_mode: zoom_mode,
rotate_mode: rotate_mode,
text_mode: text_mode,
set_reaction_data: set_reaction_data,
set_metabolite_data: set_metabolite_data,
set_gene_data: set_gene_data,
_update_data: _update_data,
_toggle_direction_buttons: _toggle_direction_buttons,
_setup_menu: _setup_menu,
_setup_simple_zoom_buttons: _setup_simple_zoom_buttons,
_setup_status: _setup_status,
_setup_quick_jump: _setup_quick_jump,
_setup_modes: _setup_modes,
_get_keys: _get_keys,
_setup_confirm_before_exit: _setup_confirm_before_exit };
return Builder;
// definitions
function init(map_data, model_data, embedded_css, selection, options) {
// default sel
if (!selection)
selection = d3.select('body').append('div');
if (!options)
options = {};
this.map_data = map_data;
this.model_data = model_data;
this.embedded_css = embedded_css;
this.selection = selection;
// apply this object as data for the selection
this.selection.datum(this);
// set defaults
this.options = utils.set_options(options, {
// view options
menu: 'all',
scroll_behavior: 'pan',
enable_editing: true,
enable_keys: true,
enable_search: true,
fill_screen: false,
zoom_to_element: null,
// map, model, and styles
starting_reaction: null,
never_ask_before_quit: false,
unique_map_id: null,
primary_metabolite_radius: 20,
secondary_metabolite_radius: 10,
marker_radius: 5,
gene_font_size: 18,
hide_secondary_metabolites: false,
show_gene_reaction_rules: false,
hide_all_labels: false,
// applied data
// reaction
reaction_data: null,
reaction_styles: ['color', 'size', 'text'],
reaction_compare_style: 'log2_fold',
reaction_scale: [{ type: 'min', color: '#c8c8c8', size: 12 },
{ type: 'median', color: '#9696ff', size: 20 },
{ type: 'max', color: '#ff0000', size: 25 }],
reaction_no_data_color: '#dcdcdc',
reaction_no_data_size: 8,
// gene
gene_data: null,
and_method_in_gene_reaction_rule: 'mean',
// metabolite
metabolite_data: null,
metabolite_styles: ['color', 'size', 'text'],
metabolite_compare_style: 'log2_fold',
metabolite_scale: [ { type: 'min', color: '#fffaf0', size: 20 },
{ type: 'median', color: '#f1c470', size: 30 },
{ type: 'max', color: '#800000', size: 40 } ],
metabolite_no_data_color: '#ffffff',
metabolite_no_data_size: 10,
// View and build options
identifiers_on_map: 'bigg_id',
highlight_missing: false,
allow_building_duplicate_reactions: false,
// Callbacks
first_load_callback: null
}, {
primary_metabolite_radius: true,
secondary_metabolite_radius: true,
marker_radius: true,
gene_font_size: true,
reaction_no_data_size: true,
metabolite_no_data_size: true
});
// check the location
if (utils.check_for_parent_tag(this.selection, 'svg')) {
throw new Error('Builder cannot be placed within an svg node '+
'becuase UI elements are html-based.');
}
// Initialize the settings
var set_option = function(option, new_value) {
this.options[option] = new_value;
}.bind(this),
get_option = function(option) {
return this.options[option];
}.bind(this),
// the options that are erased when the settings menu is canceled
conditional_options = ['hide_secondary_metabolites', 'show_gene_reaction_rules',
'hide_all_labels', 'scroll_behavior', 'reaction_styles',
'reaction_compare_style', 'reaction_scale',
'reaction_no_data_color', 'reaction_no_data_size',
'and_method_in_gene_reaction_rule', 'metabolite_styles',
'metabolite_compare_style', 'metabolite_scale',
'metabolite_no_data_color', 'metabolite_no_data_size',
'identifiers_on_map', 'highlight_missing',
'allow_building_duplicate_reactions',];
this.settings = new Settings(set_option, get_option, conditional_options);
// check the scales have max and min
['reaction_scale', 'metabolite_scale'].forEach(function(name) {
this.settings.streams[name].onValue(function(val) {
['min', 'max'].forEach(function(type) {
var has = val.reduce(function(has_found, scale_el) {
return has_found || (scale_el.type == type);
}, false);
if (!has) {
val.push({ type: type, color: '#ffffff', size: 10 });
this.settings.set_conditional(name, val);
}
}.bind(this));
}.bind(this));
}.bind(this));
// TODO warn about repeated types in the scale
// set up this callback manager
this.callback_manager = CallbackManager();
if (this.options.first_load_callback !== null)
this.callback_manager.set('first_load', this.options.first_load_callback);
// load the model, map, and update data in both
this.load_model(this.model_data, false);
this.load_map(this.map_data, false);
this._update_data(true, true);
// setting callbacks
// TODO enable atomic updates. Right now, every time
// the menu closes, everything is drawn.
this.settings.status_bus
.onValue(function(x) {
if (x == 'accepted') {
this._update_data(true, true, ['reaction', 'metabolite'], false);
if (this.zoom_container !== null) {
var new_behavior = this.settings.get_option('scroll_behavior');
this.zoom_container.update_scroll_behavior(new_behavior);
}
if (this.map !== null) {
this.map.draw_all_nodes(false);
this.map.draw_all_reactions(true, false);
}
}
}.bind(this));
this.callback_manager.run('first_load', this);
}
// Definitions
function load_model(model_data, should_update_data) {
/** For documentation of this function, see docs/javascript_api.rst.
*/
if (should_update_data === undefined)
should_update_data = true;
// Check the cobra model
if (model_data === null)
this.cobra_model = null;
else
this.cobra_model = CobraModel.from_cobra_json(model_data);
if (this.map) {
this.map.cobra_model = this.cobra_model;
if (should_update_data)
this._update_data(true, false);
if (this.settings.get_option('highlight_missing'))
this.map.draw_all_reactions(false, false);
}
this.callback_manager.run('load_model', null, model_data, should_update_data);
}
function load_map(map_data, should_update_data) {
/** For documentation of this function, see docs/javascript_api.rst
*/
if (should_update_data === undefined)
should_update_data = true;
// Begin with some definitions
var selectable_mousedown_enabled = true,
shift_key_on = false;
// remove the old builder
utils.remove_child_nodes(this.selection);
// set up the svg
var svg = utils.setup_svg(this.selection, false,
this.options.fill_screen);
// se up the zoom container
this.zoom_container = new ZoomContainer(svg, this.selection,
this.options.scroll_behavior);
var zoomed_sel = this.zoom_container.zoomed_sel;
if (map_data!==null) {
// import map
this.map = Map.from_data(map_data,
svg,
this.embedded_css,
zoomed_sel,
this.zoom_container,
this.settings,
this.cobra_model,
this.options.enable_search);
this.zoom_container.reset();
} else {
// new map
this.map = new Map(svg,
this.embedded_css,
zoomed_sel,
this.zoom_container,
this.settings,
this.cobra_model,
null,
this.options.enable_search);
}
// set the data for the map
if (should_update_data)
this._update_data(false, true);
// set up the reaction input with complete.ly
this.build_input = BuildInput(this.selection, this.map,
this.zoom_container, this.settings);
// set up the text edit input
this.text_edit_input = TextEditInput(this.selection, this.map,
this.zoom_container);
// set up the Brush
this.brush = new Brush(zoomed_sel, false, this.map, '.canvas-group');
this.map.canvas.callback_manager.set('resize', function() {
this.brush.toggle(true);
}.bind(this));
// set up the modes
this._setup_modes(this.map, this.brush, this.zoom_container);
var s = this.selection
.append('div').attr('class', 'search-menu-container')
.append('div').attr('class', 'search-menu-container-inline'),
menu_div = s.append('div'),
search_bar_div = s.append('div'),
button_div = this.selection.append('div');
// set up the search bar
this.search_bar = SearchBar(search_bar_div, this.map.search_index,
this.map);
// set up the hide callbacks
this.search_bar.callback_manager.set('show', function() {
this.settings_bar.toggle(false);
}.bind(this));
// set up the settings
var settings_div = this.selection.append('div');
this.settings_bar = SettingsMenu(settings_div, this.settings, this.map,
function(type, on_off) {
// temporarily set the abs type, for
// previewing it in the Settings
// menu
var o = this.options[type + '_styles'];
if (on_off && o.indexOf('abs') == -1)
o.push('abs');
else if (!on_off) {
var i = o.indexOf('abs');
if (i != -1)
this.options[type + '_styles'] = o.slice(0, i).concat(o.slice(i + 1));
}
this._update_data(false, true, type);
}.bind(this));
this.settings_bar.callback_manager.set('show', function() {
this.search_bar.toggle(false);
}.bind(this));
// set up key manager
var keys = this._get_keys(this.map, this.zoom_container,
this.search_bar, this.settings_bar,
this.options.enable_editing);
this.map.key_manager.assigned_keys = keys;
// tell the key manager about the reaction input and search bar
this.map.key_manager.input_list = [this.build_input, this.search_bar,
this.settings_bar, this.text_edit_input];
// make sure the key manager remembers all those changes
this.map.key_manager.update();
// turn it on/off
this.map.key_manager.toggle(this.options.enable_keys);
// set up menu and status bars
if (this.options.menu=='all') {
this._setup_menu(menu_div, button_div, this.map, this.zoom_container, this.map.key_manager, keys,
this.options.enable_editing, this.options.enable_keys);
} else if (this.options.menu=='zoom') {
this._setup_simple_zoom_buttons(button_div, keys);
}
// setup selection box
if (this.options.zoom_to_element) {
var type = this.options.zoom_to_element.type,
element_id = this.options.zoom_to_element.id;
if (typeof type === 'undefined' || ['reaction', 'node'].indexOf(type) == -1)
throw new Error('zoom_to_element type must be "reaction" or "node"');
if (typeof element_id === 'undefined')
throw new Error('zoom_to_element must include id');
if (type == 'reaction')
this.map.zoom_to_reaction(element_id);
else if (type == 'node')
this.map.zoom_to_node(element_id);
} else if (map_data !== null) {
this.map.zoom_extent_canvas();
} else {
if (this.options.starting_reaction !== null && this.cobra_model !== null) {
// Draw default reaction if no map is provided
var size = this.zoom_container.get_size();
var start_coords = { x: size.width / 2,
y: size.height / 4 };
this.map.new_reaction_from_scratch(this.options.starting_reaction, start_coords, 90);
this.map.zoom_extent_nodes();
} else {
this.map.zoom_extent_canvas();
}
}
// status in both modes
var status = this._setup_status(this.selection, this.map);
// set up quick jump
this._setup_quick_jump(this.selection);
// start in zoom mode for builder, view mode for viewer
if (this.options.enable_editing)
this.zoom_mode();
else
this.view_mode();
// confirm before leaving the page
if (this.options.enable_editing)
this._setup_confirm_before_exit();
// draw
this.map.draw_everything();
}
function _set_mode(mode) {
this.search_bar.toggle(false);
// input
this.build_input.toggle(mode=='build');
this.build_input.direction_arrow.toggle(mode=='build');
if (this.options.menu=='all' && this.options.enable_editing)
this._toggle_direction_buttons(mode=='build');
// brush
this.brush.toggle(mode=='brush');
// zoom
this.zoom_container.toggle_zoom(mode=='zoom' || mode=='view');
// resize canvas
this.map.canvas.toggle_resize(mode=='zoom' || mode=='brush');
// Behavior. Be careful of the order becuase rotation and
// toggle_selectable_drag both use Behavior.selectable_drag.
if (mode == 'rotate') {
this.map.behavior.toggle_selectable_drag(false); // before toggle_rotation_mode
this.map.behavior.toggle_rotation_mode(true);
} else {
this.map.behavior.toggle_rotation_mode(mode=='rotate'); // before toggle_selectable_drag
this.map.behavior.toggle_selectable_drag(mode=='brush');
}
this.map.behavior.toggle_selectable_click(mode=='build' || mode=='brush');
this.map.behavior.toggle_label_drag(mode=='brush');
this.map.behavior.toggle_label_mousedown(mode=='brush');
this.map.behavior.toggle_text_label_edit(mode=='text');
this.map.behavior.toggle_bezier_drag(mode=='brush');
// edit selections
if (mode=='view' || mode=='text')
this.map.select_none();
if (mode=='rotate')
this.map.deselect_text_labels();
this.map.draw_everything();
}
function view_mode() {
/** For documentation of this function, see docs/javascript_api.rst.
*/
this.callback_manager.run('view_mode');
this._set_mode('view');
}
function build_mode() {
/** For documentation of this function, see docs/javascript_api.rst.
*/
this.callback_manager.run('build_mode');
this._set_mode('build');
}
function brush_mode() {
/** For documentation of this function, see docs/javascript_api.rst.
*/
this.callback_manager.run('brush_mode');
this._set_mode('brush');
}
function zoom_mode() {
/** For documentation of this function, see docs/javascript_api.rst.
*/
this.callback_manager.run('zoom_mode');
this._set_mode('zoom');
}
function rotate_mode() {
/** For documentation of this function, see docs/javascript_api.rst.
*/
this.callback_manager.run('rotate_mode');
this._set_mode('rotate');
}
function text_mode() {
/** For documentation of this function, see docs/javascript_api.rst.
*/
this.callback_manager.run('text_mode');
this._set_mode('text');
}
function set_reaction_data(data) {
/** For documentation of this function, see docs/javascript_api.rst.
*/
this.options.reaction_data = data;
this._update_data(true, true, 'reaction');
this.map.set_status('');
}
function set_gene_data(data, clear_gene_reaction_rules) {
/** For documentation of this function, see docs/javascript_api.rst.
*/
if (clear_gene_reaction_rules) // default undefined
this.settings.set_conditional('show_gene_reaction_rules', false);
this.options.gene_data = data;
this._update_data(true, true, 'reaction');
this.map.set_status('');
}
function set_metabolite_data(data) {
/** For documentation of this function, see docs/javascript_api.rst.
*/
this.options.metabolite_data = data;
this._update_data(true, true, 'metabolite');
this.map.set_status('');
}
function _update_data(update_model, update_map, kind, should_draw) {
/** Set data and settings for the model.
Arguments
---------
update_model: (Boolean) Update data for the model.
update_map: (Boolean) Update data for the map.
kind: (Optional, Default: all) An array defining which data is being
updated that can include any of: ['reaction', 'metabolite'].
should_draw: (Optional, Default: true) Whether to redraw the update
sections of the map.
*/
// defaults
if (kind === undefined)
kind = ['reaction', 'metabolite'];
if (should_draw === undefined)
should_draw = true;
var update_metabolite_data = (kind.indexOf('metabolite') != -1),
update_reaction_data = (kind.indexOf('reaction') != -1),
met_data_object,
reaction_data_object,
gene_data_object;
// -------------------
// First map, and draw
// metabolite data
if (update_metabolite_data && update_map && this.map !== null) {
met_data_object = data_styles.import_and_check(this.options.metabolite_data,
'metabolite_data');
this.map.apply_metabolite_data_to_map(met_data_object);
if (should_draw)
this.map.draw_all_nodes(false);
}
// reaction data
if (update_reaction_data) {
if (this.options.reaction_data !== null && update_map && this.map !== null) {
reaction_data_object = data_styles.import_and_check(this.options.reaction_data,
'reaction_data');
this.map.apply_reaction_data_to_map(reaction_data_object);
if (should_draw)
this.map.draw_all_reactions(false, false);
} else if (this.options.gene_data !== null && update_map && this.map !== null) {
gene_data_object = make_gene_data_object(this.options.gene_data,
this.cobra_model, this.map);
this.map.apply_gene_data_to_map(gene_data_object);
if (should_draw)
this.map.draw_all_reactions(false, false);
} else if (update_map && this.map !== null) {
// clear the data
this.map.apply_reaction_data_to_map(null);
if (should_draw)
this.map.draw_all_reactions(false, false);
}
}
// ----------------------------------------------------------------
// Then the model, after drawing. Delay by 5ms so the the map draws
// first.
// if this function runs again, cancel the previous model update
if (this.update_model_timer)
window.clearTimeout(this.update_model_timer);
var delay = 5;
this.update_model_timer = window.setTimeout(function() {
// metabolite_data
if (update_metabolite_data && update_model && this.cobra_model !== null) {
// if we haven't already made this
if (!met_data_object)
met_data_object = data_styles.import_and_check(this.options.metabolite_data,
'metabolite_data');
this.cobra_model.apply_metabolite_data(met_data_object,
this.options.metabolite_styles,
this.options.metabolite_compare_style);
}
// reaction data
if (update_reaction_data) {
if (this.options.reaction_data !== null && update_model && this.cobra_model !== null) {
// if we haven't already made this
if (!reaction_data_object)
reaction_data_object = data_styles.import_and_check(this.options.reaction_data,
'reaction_data');
this.cobra_model.apply_reaction_data(reaction_data_object,
this.options.reaction_styles,
this.options.reaction_compare_style);
} else if (this.options.gene_data !== null && update_model && this.cobra_model !== null) {
if (!gene_data_object)
gene_data_object = make_gene_data_object(this.options.gene_data,
this.cobra_model, this.map);
this.cobra_model.apply_gene_data(gene_data_object,
this.options.reaction_styles,
this.options.identifiers_on_map,
this.options.reaction_compare_style,
this.options.and_method_in_gene_reaction_rule);
} else if (update_model && this.cobra_model !== null) {
// clear the data
this.cobra_model.apply_reaction_data(null,
this.options.reaction_styles,
this.options.reaction_compare_style);
}
}
// callback
this.callback_manager.run('update_data', null, update_model, update_map, kind, should_draw);
}.bind(this), delay);
// definitions
function make_gene_data_object(gene_data, cobra_model, map) {
var all_reactions = {};
if (cobra_model !== null)
utils.extend(all_reactions, cobra_model.reactions);
// extend, overwrite
if (map !== null)
utils.extend(all_reactions, map.reactions, true);
// this object has reaction keys and values containing associated genes
return data_styles.import_and_check(gene_data, 'gene_data', all_reactions);
}
}
function _setup_menu(menu_selection, button_selection, map, zoom_container,
key_manager, keys, enable_editing, enable_keys) {
var menu = menu_selection.attr('id', 'menu')
.append('ul')
.attr('class', 'nav nav-pills');
// map dropdown
ui.dropdown_menu(menu, 'Map')
.button({ key: keys.save,
text: 'Save map JSON',
key_text: (enable_keys ? ' (Ctrl+S)' : null) })
.button({ text: 'Load map JSON',
key_text: (enable_keys ? ' (Ctrl+O)' : null),
input: { assign: key_manager.assigned_keys.load,
key: 'fn',
fn: load_map_for_file.bind(this),
pre_fn: function() {
map.set_status('Loading map ...');
},
failure_fn: function() {
map.set_status('');
}}
})
.button({ key: keys.save_svg,
text: 'Export as SVG',
key_text: (enable_keys ? ' (Ctrl+Shift+S)' : null) })
.button({ key: keys.clear_map,
text: 'Clear map' });
// model dropdown
var model_menu = ui.dropdown_menu(menu, 'Model')
.button({ text: 'Load COBRA model JSON',
key_text: (enable_keys ? ' (Ctrl+M)' : null),
input: { assign: key_manager.assigned_keys.load_model,
key: 'fn',
fn: load_model_for_file.bind(this),
pre_fn: function() {
map.set_status('Loading model ...');
},
failure_fn: function() {
map.set_status('');
} }
})
.button({ key: keys.clear_model,
text: 'Clear model' });
// disable the clear button
var disable_model_clear = function() {
model_menu.dropdown.selectAll('li')
.classed('escher-disabled', function(d) {
if (d.text == 'Clear model' && this.cobra_model === null)
return true;
return null;
}.bind(this));
}.bind(this);
disable_model_clear();
this.callback_manager.set('load_model', disable_model_clear);
// data dropdown
var data_menu = ui.dropdown_menu(menu, 'Data')
.button({ input: { assign: key_manager.assigned_keys.load_reaction_data,
key: 'fn',
fn: load_reaction_data_for_file.bind(this),
accept_csv: true,
pre_fn: function() {
map.set_status('Loading reaction data ...');
},
failure_fn: function() {
map.set_status('');
}},
text: 'Load reaction data' })
.button({ key: keys.clear_reaction_data,
text: 'Clear reaction data' })
.divider()
.button({ input: { fn: load_gene_data_for_file.bind(this),
accept_csv: true,
pre_fn: function() {
map.set_status('Loading gene data ...');
},
failure_fn: function() {
map.set_status('');
}},
text: 'Load gene data' })
.button({ key: keys.clear_gene_data,
text: 'Clear gene data' })
.divider()
.button({ input: { fn: load_metabolite_data_for_file.bind(this),
accept_csv: true,
pre_fn: function() {
map.set_status('Loading metabolite data ...');
},
failure_fn: function() {
map.set_status('');
}},
text: 'Load metabolite data' })
.button({ key: keys.clear_metabolite_data,
text: 'Clear metabolite data' });
// update the buttons
var disable_clears = function() {
data_menu.dropdown.selectAll('li')
.classed('escher-disabled', function(d) {
if (!d) return null;
if (d.text == 'Clear reaction data' && this.options.reaction_data === null)
return true;
if (d.text == 'Clear gene data' && this.options.gene_data === null)
return true;
if (d.text == 'Clear metabolite data' && this.options.metabolite_data === null)
return true;
return null;
}.bind(this));
}.bind(this);
disable_clears();
this.callback_manager.set('update_data', disable_clears);
// edit dropdown
var edit_menu = ui.dropdown_menu(menu, 'Edit', true);
if (enable_editing) {
edit_menu
.button({ key: keys.zoom_mode,
id: 'zoom-mode-menu-button',
text: 'Pan mode',
key_text: (enable_keys ? ' (Z)' : null) })
.button({ key: keys.brush_mode,
id: 'brush-mode-menu-button',
text: 'Select mode',
key_text: (enable_keys ? ' (V)' : null) })
.button({ key: keys.build_mode,
id: 'build-mode-menu-button',
text: 'Add reaction mode',
key_text: (enable_keys ? ' (N)' : null) })
.button({ key: keys.rotate_mode,
id: 'rotate-mode-menu-button',
text: 'Rotate mode',
key_text: (enable_keys ? ' (R)' : null) })
.button({ key: keys.text_mode,
id: 'text-mode-menu-button',
text: 'Text mode',
key_text: (enable_keys ? ' (T)' : null) })
.divider()
.button({ key: keys.delete,
text: 'Delete',
key_text: (enable_keys ? ' (Del)' : null) })
.button({ key: keys.undo,
text: 'Undo',
key_text: (enable_keys ? ' (Ctrl+Z)' : null) })
.button({ key: keys.redo,
text: 'Redo',
key_text: (enable_keys ? ' (Ctrl+Shift+Z)' : null) })
.button({ key: keys.toggle_primary,
text: 'Toggle primary/secondary',
key_text: (enable_keys ? ' (P)' : null) })
.button({ key: keys.cycle_primary,
text: 'Rotate reactant locations',
key_text: (enable_keys ? ' (C)' : null) })
.button({ key: keys.select_all,
text: 'Select all',
key_text: (enable_keys ? ' (Ctrl+A)' : null) })
.button({ key: keys.select_none,
text: 'Select none',
key_text: (enable_keys ? ' (Ctrl+Shift+A)' : null) })
.button({ key: keys.invert_selection,
text: 'Invert selection' });
} else {
edit_menu.button({ key: keys.view_mode,
id: 'view-mode-menu-button',
text: 'View mode' });
}
// view dropdown
var view_menu = ui.dropdown_menu(menu, 'View', true)
.button({ key: keys.zoom_in,
text: 'Zoom in',
key_text: (enable_keys ? ' (Ctrl and +)' : null) })
.button({ key: keys.zoom_out,
text: 'Zoom out',
key_text: (enable_keys ? ' (Ctrl and -)' : null) })
.button({ key: keys.extent_nodes,
text: 'Zoom to nodes',
key_text: (enable_keys ? ' (Ctrl+0)' : null) })
.button({ key: keys.extent_canvas,
text: 'Zoom to canvas',
key_text: (enable_keys ? ' (Ctrl+1)' : null) })
.button({ key: keys.search,
text: 'Find',
key_text: (enable_keys ? ' (Ctrl+F)' : null) });
if (enable_editing) {
view_menu.button({ key: keys.toggle_beziers,
id: 'bezier-button',
text: 'Show control points',
key_text: (enable_keys ? ' (B)' : null) });
map.callback_manager
.set('toggle_beziers.button', function(on_off) {
menu.select('#bezier-button').select('.dropdown-button-text')
.text((on_off ? 'Hide' : 'Show') +
' control points' +
(enable_keys ? ' (B)' : ''));
});
}
view_menu.divider()
.button({ key: keys.show_settings,
text: 'Settings',
key_text: (enable_keys ? ' (Ctrl+,)' : null) });
// help
menu.append('a')
.attr('class', 'help-button')
.attr('target', '#')
.attr('href', 'https://escher.readthedocs.org')
.text('?');
var button_panel = button_selection.append('ul')
.attr('class', 'nav nav-pills nav-stacked')
.attr('id', 'button-panel');
// buttons
ui.individual_button(button_panel.append('li'),
{ key: keys.zoom_in,
icon: 'glyphicon glyphicon-plus-sign',
classes: 'btn btn-default',
tooltip: 'Zoom in',
key_text: (enable_keys ? ' (Ctrl and +)' : null) });
ui.individual_button(button_panel.append('li'),
{ key: keys.zoom_out,
icon: 'glyphicon glyphicon-minus-sign',
classes: 'btn btn-default',
tooltip: 'Zoom out',
key_text: (enable_keys ? ' (Ctrl and -)' : null) });
ui.individual_button(button_panel.append('li'),
{ key: keys.extent_canvas,
icon: 'glyphicon glyphicon-resize-full',
classes: 'btn btn-default',
tooltip: 'Zoom to canvas',
key_text: (enable_keys ? ' (Ctrl+1)' : null) });
// mode buttons
if (enable_editing) {
ui.radio_button_group(button_panel.append('li'))
.button({ key: keys.zoom_mode,
id: 'zoom-mode-button',
icon: 'glyphicon glyphicon-move',
tooltip: 'Pan mode',
key_text: (enable_keys ? ' (Z)' : null) })
.button({ key: keys.brush_mode,
id: 'brush-mode-button',
icon: 'glyphicon glyphicon-hand-up',
tooltip: 'Select mode',
key_text: (enable_keys ? ' (V)' : null) })
.button({ key: keys.build_mode,
id: 'build-mode-button',
icon: 'glyphicon glyphicon-plus',
tooltip: 'Add reaction mode',
key_text: (enable_keys ? ' (N)' : null) })
.button({ key: keys.rotate_mode,
id: 'rotate-mode-button',
icon: 'glyphicon glyphicon-repeat',
tooltip: 'Rotate mode',
key_text: (enable_keys ? ' (R)' : null) })
.button({ key: keys.text_mode,
id: 'text-mode-button',
icon: 'glyphicon glyphicon-font',
tooltip: 'Text mode',
key_text: (enable_keys ? ' (T)' : null) });
// arrow buttons
this.direction_buttons = button_panel.append('li');
var o = ui.button_group(this.direction_buttons)
.button({ key: keys.direction_arrow_left,
icon: 'glyphicon glyphicon-arrow-left',
tooltip: 'Direction arrow (←)' })
.button({ key: keys.direction_arrow_right,
icon: 'glyphicon glyphicon-arrow-right',
tooltip: 'Direction arrow (→)' })
.button({ key: keys.direction_arrow_up,
icon: 'glyphicon glyphicon-arrow-up',
tooltip: 'Direction arrow (↑)' })
.button({ key: keys.direction_arrow_down,
icon: 'glyphicon glyphicon-arrow-down',
tooltip: 'Direction arrow (↓)' });
}
// set up mode callbacks
var select_button = function(id) {
// toggle the button
$(this.selection.node()).find('#' + id)
.button('toggle');
// menu buttons
var ids = ['zoom-mode-menu-button', 'brush-mode-menu-button',
'build-mode-menu-button', 'rotate-mode-menu-button',
'view-mode-menu-button', 'text-mode-menu-button'];
ids.forEach(function(this_id) {
var b_id = this_id.replace('-menu', '');
this.selection.select('#' + this_id)
.select('span')
.classed('glyphicon', b_id == id)
.classed('glyphicon-ok', b_id == id);
}.bind(this));
};
this.callback_manager.set('zoom_mode', select_button.bind(this, 'zoom-mode-button'));
this.callback_manager.set('brush_mode', select_button.bind(this, 'brush-mode-button'));
this.callback_manager.set('build_mode', select_button.bind(this, 'build-mode-button'));
this.callback_manager.set('rotate_mode', select_button.bind(this, 'rotate-mode-button'));
this.callback_manager.set('view_mode', select_button.bind(this, 'view-mode-button'));
this.callback_manager.set('text_mode', select_button.bind(this, 'text-mode-button'));
// definitions
function load_map_for_file(error, map_data) {
/** Load a map. This reloads the whole builder.
*/
if (error) {
console.warn(error);
this.map.set_status('Error loading map: ' + error, 2000);
return;
}
try {
check_map(map_data);
this.load_map(map_data);
this.map.set_status('Loaded map ' + map_data[0].map_name, 3000);
} catch (e) {
console.warn(e);
this.map.set_status('Error loading map: ' + e, 2000);
}
// definitions
function check_map(data) {
/** Perform a quick check to make sure the map is mostly valid.
*/
if (!('map_id' in data[0] && 'reactions' in data[1] &&
'nodes' in data[1] && 'canvas' in data[1]))
throw new Error('Bad map data.');
}
}
function load_model_for_file(error, data) {
/** Load a cobra model. Redraws the whole map if the
highlight_missing option is true.
*/
if (error) {
console.warn(error);
this.map.set_status('Error loading model: ' + error, 2000);
return;
}
try {
this.load_model(data, true);
this.build_input.toggle(false);
if ('id' in data)
this.map.set_status('Loaded model ' + data.id, 3000);
else
this.map.set_status('Loaded model (no model id)', 3000);
} catch (e) {
console.warn(e);
this.map.set_status('Error loading model: ' + e, 2000);
}
}
function load_reaction_data_for_file(error, data) {
if (error) {
console.warn(error);
this.map.set_status('Could not parse file as JSON or CSV', 2000);
return;
}
// turn off gene data
if (data !== null)
this.set_gene_data(null);
this.set_reaction_data(data);
}
function load_metabolite_data_for_file(error, data) {
if (error) {
console.warn(error);
this.map.set_status('Could not parse file as JSON or CSV', 2000);
return;
}
this.set_metabolite_data(data);
}
function load_gene_data_for_file(error, data) {
if (error) {
console.warn(error);
this.map.set_status('Could not parse file as JSON or CSV', 2000);
return;
}
// turn off reaction data
if (data !== null)
this.set_reaction_data(null);
// turn on gene_reaction_rules
this.settings.set_conditional('show_gene_reaction_rules', true);
this.set_gene_data(data);
}
}
function _setup_simple_zoom_buttons(button_selection, keys) {
var button_panel = button_selection.append('div')
.attr('id', 'simple-button-panel');
// buttons
ui.individual_button(button_panel.append('div'),
{ key: keys.zoom_in,
text: '+',
classes: 'simple-button',
tooltip: 'Zoom in (Ctrl +)' });
ui.individual_button(button_panel.append('div'),
{ key: keys.zoom_out,
text: '–',
classes: 'simple-button',
tooltip: 'Zoom out (Ctrl -)' });
ui.individual_button(button_panel.append('div'),
{ key: keys.extent_canvas,
text: '↔',
classes: 'simple-button',
tooltip: 'Zoom to canvas (Ctrl 1)' });
}
function _toggle_direction_buttons(on_off) {
if (on_off===undefined)
on_off = !this.direction_buttons.style('visibility')=='visible';
this.direction_buttons.style('visibility', on_off ? 'visible' : 'hidden');
}
function _setup_status(selection, map) {
var status_bar = selection.append('div').attr('id', 'status');
map.callback_manager.set('set_status', function(status) {
status_bar.text(status);
});
return status_bar;
}
function _setup_quick_jump(selection) {
// function to load a map
var load_fn = function(new_map_name, quick_jump_path, callback) {
if (this.options.enable_editing && !this.options.never_ask_before_quit) {
if (!(confirm(('You will lose any unsaved changes.\n\n' +
'Are you sure you want to switch maps?')))) {
if (callback) callback(false);
return;
}
}
this.map.set_status('Loading map ' + new_map_name + ' ...');
var url = utils.name_to_url(new_map_name, quick_jump_path);
d3.json(url, function(error, data) {
if (error) {
console.warn('Could not load data: ' + error);
if (callback) callback(false);
}
// run callback before load_map so the new map has the correct
// quick_jump menu
if (callback) callback(true);
// now reload
this.load_map(data);
this.map.set_status('');
}.bind(this));
}.bind(this);
// make the quick jump object
this.quick_jump = QuickJump(selection, load_fn);
}
function _setup_modes(map, brush, zoom_container) {
// set up zoom+pan and brush modes
var was_enabled = {};
map.callback_manager.set('start_rotation', function() {
was_enabled.brush = brush.enabled;
brush.toggle(false);
was_enabled.zoom = zoom_container.zoom_on;
zoom_container.toggle_zoom(false);
was_enabled.selectable_mousedown = map.behavior.selectable_mousedown!=null;
map.behavior.toggle_selectable_click(false);
was_enabled.label_mousedown = map.behavior.label_mousedown!=null;
map.behavior.toggle_label_mousedown(false);
});
map.callback_manager.set('end_rotation', function() {
brush.toggle(was_enabled.brush);
zoom_container.toggle_zoom(was_enabled.zoom);
map.behavior.toggle_selectable_click(was_enabled.selectable_mousedown);
map.behavior.toggle_label_mousedown(was_enabled.label_mousedown);
was_enabled = {};
});
}
function _get_keys(map, zoom_container, search_bar, settings_bar, enable_editing) {
var keys = {
save: { key: 83, modifiers: { control: true }, // ctrl-s
target: map,
fn: map.save },
save_svg: { key: 83, modifiers: { control: true, shift: true },
target: map,
fn: map.save_svg },
load: { key: 79, modifiers: { control: true }, // ctrl-o
fn: null }, // defined by button
clear_map: { fn: this.map.clear_map.bind(this.map) },
load_model: { key: 77, modifiers: { control: true }, // ctrl-m
fn: null }, // defined by button
clear_model: { fn: this.load_model.bind(this, null, true) },
load_reaction_data: { fn: null }, // defined by button
clear_reaction_data: { target: this,
fn: function() { this.set_reaction_data(null); }},
load_metabolite_data: { fn: null }, // defined by button
clear_metabolite_data: { target: this,
fn: function() { this.set_metabolite_data(null); }},
load_gene_data: { fn: null }, // defined by button
clear_gene_data: { fn: function() {
this.set_gene_data(null, true);
}.bind(this)},
zoom_in: { key: 187, modifiers: { control: true }, // ctrl +
target: zoom_container,
fn: zoom_container.zoom_in },
zoom_out: { key: 189, modifiers: { control: true }, // ctrl -
target: zoom_container,
fn: zoom_container.zoom_out },
extent_nodes: { key: 48, modifiers: { control: true }, // ctrl-0
target: map,
fn: map.zoom_extent_nodes },
extent_canvas: { key: 49, modifiers: { control: true }, // ctrl-1
target: map,
fn: map.zoom_extent_canvas },
search: { key: 70, modifiers: { control: true }, // ctrl-f
fn: search_bar.toggle.bind(search_bar, true) },
view_mode: { fn: this.view_mode.bind(this),
ignore_with_input: true },
show_settings: { key: 188, modifiers: { control: true }, // Ctrl ,
fn: settings_bar.toggle.bind(settings_bar) }
};
if (enable_editing) {
utils.extend(keys, {
build_mode: { key: 78, // n
fn: this.build_mode.bind(this),
ignore_with_input: true },
zoom_mode: { key: 90, // z
fn: this.zoom_mode.bind(this),
ignore_with_input: true },
brush_mode: { key: 86, // v
fn: this.brush_mode.bind(this),
ignore_with_input: true },
rotate_mode: { key: 82, // r
fn: this.rotate_mode.bind(this),
ignore_with_input: true },
text_mode: { key: 84, // t
fn: this.text_mode.bind(this),
ignore_with_input: true },
toggle_beziers: { key: 66,
target: map,
fn: map.toggle_beziers,
ignore_with_input: true }, // b
delete: { key: 8, modifiers: { control: true }, // ctrl-backspace
target: map,
fn: map.delete_selected,
ignore_with_input: true },
delete_del: { key: 46, modifiers: { control: false }, // Del
target: map,
fn: map.delete_selected,
ignore_with_input: true },
toggle_primary: { key: 80, // p
target: map,
fn: map.toggle_selected_node_primary,
ignore_with_input: true },
cycle_primary: { key: 67, // c
target: map,
fn: map.cycle_primary_node,
ignore_with_input: true },
direction_arrow_right: { key: 39, // right
fn: this.build_input.direction_arrow.right
.bind(this.build_input.direction_arrow),
ignore_with_input: true },
direction_arrow_down: { key: 40, // down
fn: this.build_input.direction_arrow.down
.bind(this.build_input.direction_arrow),
ignore_with_input: true },
direction_arrow_left: { key: 37, // left
fn: this.build_input.direction_arrow.left
.bind(this.build_input.direction_arrow),
ignore_with_input: true },
direction_arrow_up: { key: 38, // up
fn: this.build_input.direction_arrow.up
.bind(this.build_input.direction_arrow),
ignore_with_input: true },
undo: { key: 90, modifiers: { control: true },
target: map.undo_stack,
fn: map.undo_stack.undo },
redo: { key: 90, modifiers: { control: true, shift: true },
target: map.undo_stack,
fn: map.undo_stack.redo },
select_all: { key: 65, modifiers: { control: true }, // Ctrl Shift a
fn: map.select_all.bind(map) },
select_none: { key: 65, modifiers: { control: true, shift: true }, // Ctrl Shift a
fn: map.select_none.bind(map) },
invert_selection: { fn: map.invert_selection.bind(map) }
});
}
return keys;
}
function _setup_confirm_before_exit() {
/** Ask if the user wants to exit the page (to avoid unplanned refresh).
*/
window.onbeforeunload = function(e) {
// If we haven't been passed the event get the window.event
e = e || window.event;
return (this.options.never_ask_before_quit ? null :
'You will lose any unsaved changes.');
}.bind(this);
}
});
define('DataMenu',["utils"], function(utils) {
return function(options) {
var o = utils.set_options(options, {
selection: null,
getdatafiles: null,
datafiles: null,
update_callback: null,
target: null});
if (o.selection===null)
throw new Error('No selection provided for DataMenu');
// setup dropdown menu
// Append menu if it doesn't exist
var menu = o.selection.select('.data-menu');
if (menu.empty()) {
menu = o.selection.append('div')
.attr('class','data-menu');
}
var select_sel = menu.append('form')
.append('select').attr('class','dropdown-menu');
if (o.getdatafiles) {
if (o.datafiles) {
console.warn('DataMenu: getdatafiles option overrides datafiles');
}
d3.json(o.getdatafiles, function(error, d) {
// returns json object: { data: [file0, file1, ...] }
if (error) {
return console.warn(error);
} else {
load_with_files(o.target, d.data, select_sel, o.update_callback, o.selection);
}
return null;
});
} else if (o.datafiles) {
load_with_files(o.target, o.datafiles, select_sel, o.update_callback, o.selection);
} else {
console.warn('DataMenu: No datafiles given');
}
return { update: update };
// definitions
function load_with_files(t, files, select_sel, update_callback, selection) {
//when it changes
select_sel.node().addEventListener("change", function() {
load_datafile(t, this.value, selection, update_callback);
}, false);
var file = files[0];
update(files, select_sel);
load_datafile(t, file, selection, update_callback);
};
function load_datafile(t, this_file, selection, callback) {
utils.load_the_file(t, this_file, function(error, data) {
if (error) {
return console.warn(error);
selection.append('error loading');
o.data = null;
} else {
o.data = data;
if (callback) {
callback(data);
}
}
});
};
function update(list, select_sel) {
// update select element with d3 selection /select_sel/ to have options
// given by /list/
// TODO remove paths from file list
select_sel.selectAll(".menu-option")
.data(list)
.enter()
.append('option')
.attr('value', function (d) { return d; } )
.text(function (d) { return d; } );
// TODO set value to default_filename_index
select_sel.node().focus();
};
function get_data() {
return o.data;
};
};
});
define('static',["utils"], function(utils) {
return { load_map_model_from_url: load_map_model_from_url };
function load_map_model_from_url(map_download_url, model_download_url,
local_index, options, callback) {
var opt = utils.parse_url_components(window, options),
to_load = [],
load_map = function (fn) { fn(null); },
load_model = function (fn) { fn(null); };
if (opt.map_name) {
var map_path = _get_path('map', opt.map_name,
local_index, map_download_url);
if (map_path) {
load_map = function (fn) {
d3.json(map_path, function(error, data) {
if (error) console.warn(error);
fn(data);
});
};
}
}
if (opt.model_name) {
var model_path = _get_path('model', opt.model_name,
local_index, model_download_url);
if (model_path) {
load_model = function (fn) {
d3.json(model_path, function(error, data) {
if (error) console.warn(error);
fn(data);
});
};
}
}
load_map(function(map_data) {
load_model(function(model_data) {
callback(map_data, model_data, options);
});
});
}
function _get_path(kind, name, index, url) {
var match = index[kind+'s'].filter(function(x) {
return x[kind+'_name'] == name;
});
if (match.length == 0)
throw new Error('Bad ' + kind + ' ' + name);
return (url + encodeURIComponent(match[0].organism) +
'/' + encodeURIComponent(match[0][kind+'_name'])) + '.json';
}
});
define('main',['Builder', 'Map', 'Behavior', 'KeyManager', 'DataMenu', 'UndoStack', 'CobraModel', 'utils', 'SearchIndex', 'Settings', 'data_styles', 'ui', 'static'],
function(bu, mp, bh, km, dm, us, cm, ut, si, se, ds, ui, st) {
return { Builder: bu,
Map: mp,
Behavior: bh,
KeyManager: km,
DataMenu: dm,
UndoStack: us,
CobraModel: cm,
utils: ut,
SearchIndex: si,
Settings: se,
data_styles: ds,
ui: ui,
static: st };
});
//The modules for your project will be inlined above
//this snippet. Ask almond to synchronously require the
//module value for 'main' here and return it as the
//value to use for the public API for the built file.
return require('main');
}));
|
var baseIteratee = require('./_baseIteratee'),
basePickBy = require('./_basePickBy');
/**
* The opposite of `_.pickBy`; this method creates an object composed of
* the own and inherited enumerable properties of `object` that `predicate`
* doesn't return truthy for. The predicate is invoked with two arguments:
* (value, key).
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {Function|Object|string} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omitBy(object, _.isNumber);
* // => { 'b': '2' }
*/
function omitBy(object, predicate) {
predicate = baseIteratee(predicate);
return basePickBy(object, function(value, key) {
return !predicate(value, key);
});
}
module.exports = omitBy;
|
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.ChimeePlayer=t()}(this,function(){"use strict";var commonjsGlobal="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function unwrapExports(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function createCommonjsModule(e,t){return e(t={exports:{}},t.exports),t.exports}var toString={}.toString,_cof=function(e){return toString.call(e).slice(8,-1)},_iobject=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==_cof(e)?e.split(""):Object(e)},_defined=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e},_toIobject=function(e){return _iobject(_defined(e))},f={}.propertyIsEnumerable,_objectPie={f:f},_propertyDesc=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},_isObject=function(e){return"object"==typeof e?null!==e:"function"==typeof e},_toPrimitive=function(e,t){if(!_isObject(e))return e;var r,i;if(t&&"function"==typeof(r=e.toString)&&!_isObject(i=r.call(e)))return i;if("function"==typeof(r=e.valueOf)&&!_isObject(i=r.call(e)))return i;if(!t&&"function"==typeof(r=e.toString)&&!_isObject(i=r.call(e)))return i;throw TypeError("Can't convert object to primitive value")},hasOwnProperty={}.hasOwnProperty,_has=function(e,t){return hasOwnProperty.call(e,t)},_fails=function(e){try{return!!e()}catch(e){return!0}},_descriptors=!_fails(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),_global=createCommonjsModule(function(e){var t=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=t)}),document$1=_global.document,is=_isObject(document$1)&&_isObject(document$1.createElement),_domCreate=function(e){return is?document$1.createElement(e):{}},_ie8DomDefine=!_descriptors&&!_fails(function(){return 7!=Object.defineProperty(_domCreate("div"),"a",{get:function(){return 7}}).a}),gOPD=Object.getOwnPropertyDescriptor,f$1=_descriptors?gOPD:function(e,t){if(e=_toIobject(e),t=_toPrimitive(t,!0),_ie8DomDefine)try{return gOPD(e,t)}catch(e){}if(_has(e,t))return _propertyDesc(!_objectPie.f.call(e,t),e[t])},_objectGopd={f:f$1},_core=createCommonjsModule(function(e){var t=e.exports={version:"2.5.3"};"number"==typeof __e&&(__e=t)}),_core_1=_core.version,_aFunction=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e},_ctx=function(e,t,r){if(_aFunction(e),void 0===t)return e;switch(r){case 1:return function(r){return e.call(t,r)};case 2:return function(r,i){return e.call(t,r,i)};case 3:return function(r,i,n){return e.call(t,r,i,n)}}return function(){return e.apply(t,arguments)}},_anObject=function(e){if(!_isObject(e))throw TypeError(e+" is not an object!");return e},dP=Object.defineProperty,f$2=_descriptors?Object.defineProperty:function(e,t,r){if(_anObject(e),t=_toPrimitive(t,!0),_anObject(r),_ie8DomDefine)try{return dP(e,t,r)}catch(e){}if("get"in r||"set"in r)throw TypeError("Accessors not supported!");return"value"in r&&(e[t]=r.value),e},_objectDp={f:f$2},_hide=_descriptors?function(e,t,r){return _objectDp.f(e,t,_propertyDesc(1,r))}:function(e,t,r){return e[t]=r,e},PROTOTYPE="prototype",$export=function(e,t,r){var i,n,o,a=e&$export.F,s=e&$export.G,u=e&$export.S,c=e&$export.P,l=e&$export.B,d=e&$export.W,f=s?_core:_core[t]||(_core[t]={}),h=f[PROTOTYPE],p=s?_global:u?_global[t]:(_global[t]||{})[PROTOTYPE];for(i in s&&(r=t),r)(n=!a&&p&&void 0!==p[i])&&i in f||(o=n?p[i]:r[i],f[i]=s&&"function"!=typeof p[i]?r[i]:l&&n?_ctx(o,_global):d&&p[i]==o?function(e){var t=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,r)}return new e(t,r,i)}return e.apply(this,arguments)};return t[PROTOTYPE]=e[PROTOTYPE],t}(o):c&&"function"==typeof o?_ctx(Function.call,o):o,c&&((f.virtual||(f.virtual={}))[i]=o,e&$export.R&&h&&!h[i]&&_hide(h,i,o)))};$export.F=1,$export.G=2,$export.S=4,$export.P=8,$export.B=16,$export.W=32,$export.U=64,$export.R=128;var _export=$export,_objectSap=function(e,t){var r=(_core.Object||{})[e]||Object[e],i={};i[e]=t(r),_export(_export.S+_export.F*_fails(function(){r(1)}),"Object",i)},$getOwnPropertyDescriptor=_objectGopd.f;_objectSap("getOwnPropertyDescriptor",function(){return function(e,t){return $getOwnPropertyDescriptor(_toIobject(e),t)}});var $Object=_core.Object,getOwnPropertyDescriptor=function(e,t){return $Object.getOwnPropertyDescriptor(e,t)},getOwnPropertyDescriptor$1=createCommonjsModule(function(e){e.exports={default:getOwnPropertyDescriptor,__esModule:!0}}),_Object$getOwnPropertyDescriptor=unwrapExports(getOwnPropertyDescriptor$1),ceil=Math.ceil,floor=Math.floor,_toInteger=function(e){return isNaN(e=+e)?0:(e>0?floor:ceil)(e)},_stringAt=function(e){return function(t,r){var i,n,o=String(_defined(t)),a=_toInteger(r),s=o.length;return a<0||a>=s?e?"":void 0:(i=o.charCodeAt(a))<55296||i>56319||a+1===s||(n=o.charCodeAt(a+1))<56320||n>57343?e?o.charAt(a):i:e?o.slice(a,a+2):n-56320+(i-55296<<10)+65536}},_library=!0,_redefine=_hide,_iterators={},min=Math.min,_toLength=function(e){return e>0?min(_toInteger(e),9007199254740991):0},max=Math.max,min$1=Math.min,_toAbsoluteIndex=function(e,t){return(e=_toInteger(e))<0?max(e+t,0):min$1(e,t)},_arrayIncludes=function(e){return function(t,r,i){var n,o=_toIobject(t),a=_toLength(o.length),s=_toAbsoluteIndex(i,a);if(e&&r!=r){for(;a>s;)if((n=o[s++])!=n)return!0}else for(;a>s;s++)if((e||s in o)&&o[s]===r)return e||s||0;return!e&&-1}},SHARED="__core-js_shared__",store=_global[SHARED]||(_global[SHARED]={}),_shared=function(e){return store[e]||(store[e]={})},id=0,px=Math.random(),_uid=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++id+px).toString(36))},shared=_shared("keys"),_sharedKey=function(e){return shared[e]||(shared[e]=_uid(e))},arrayIndexOf=_arrayIncludes(!1),IE_PROTO=_sharedKey("IE_PROTO"),_objectKeysInternal=function(e,t){var r,i=_toIobject(e),n=0,o=[];for(r in i)r!=IE_PROTO&&_has(i,r)&&o.push(r);for(;t.length>n;)_has(i,r=t[n++])&&(~arrayIndexOf(o,r)||o.push(r));return o},_enumBugKeys="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),_objectKeys=Object.keys||function(e){return _objectKeysInternal(e,_enumBugKeys)},_objectDps=_descriptors?Object.defineProperties:function(e,t){_anObject(e);for(var r,i=_objectKeys(t),n=i.length,o=0;n>o;)_objectDp.f(e,r=i[o++],t[r]);return e},document$2=_global.document,_html=document$2&&document$2.documentElement,IE_PROTO$1=_sharedKey("IE_PROTO"),Empty=function(){},PROTOTYPE$1="prototype",createDict=function(){var e,t=_domCreate("iframe"),r=_enumBugKeys.length;for(t.style.display="none",_html.appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),createDict=e.F;r--;)delete createDict[PROTOTYPE$1][_enumBugKeys[r]];return createDict()},_objectCreate=Object.create||function(e,t){var r;return null!==e?(Empty[PROTOTYPE$1]=_anObject(e),r=new Empty,Empty[PROTOTYPE$1]=null,r[IE_PROTO$1]=e):r=createDict(),void 0===t?r:_objectDps(r,t)},_wks=createCommonjsModule(function(e){var t=_shared("wks"),r=_global.Symbol,i="function"==typeof r;(e.exports=function(e){return t[e]||(t[e]=i&&r[e]||(i?r:_uid)("Symbol."+e))}).store=t}),def=_objectDp.f,TAG=_wks("toStringTag"),_setToStringTag=function(e,t,r){e&&!_has(e=r?e:e.prototype,TAG)&&def(e,TAG,{configurable:!0,value:t})},IteratorPrototype={};_hide(IteratorPrototype,_wks("iterator"),function(){return this});var _iterCreate=function(e,t,r){e.prototype=_objectCreate(IteratorPrototype,{next:_propertyDesc(1,r)}),_setToStringTag(e,t+" Iterator")},_toObject=function(e){return Object(_defined(e))},IE_PROTO$2=_sharedKey("IE_PROTO"),ObjectProto=Object.prototype,_objectGpo=Object.getPrototypeOf||function(e){return e=_toObject(e),_has(e,IE_PROTO$2)?e[IE_PROTO$2]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?ObjectProto:null},ITERATOR=_wks("iterator"),BUGGY=!([].keys&&"next"in[].keys()),FF_ITERATOR="@@iterator",KEYS="keys",VALUES="values",returnThis=function(){return this},_iterDefine=function(e,t,r,i,n,o,a){_iterCreate(r,t,i);var s,u,c,l=function(e){if(!BUGGY&&e in p)return p[e];switch(e){case KEYS:case VALUES:return function(){return new r(this,e)}}return function(){return new r(this,e)}},d=t+" Iterator",f=n==VALUES,h=!1,p=e.prototype,m=p[ITERATOR]||p[FF_ITERATOR]||n&&p[n],v=!BUGGY&&m||l(n),g=n?f?l("entries"):v:void 0,y="Array"==t&&p.entries||m;if(y&&(c=_objectGpo(y.call(new e)))!==Object.prototype&&c.next&&(_setToStringTag(c,d,!0),_library||_has(c,ITERATOR)||_hide(c,ITERATOR,returnThis)),f&&m&&m.name!==VALUES&&(h=!0,v=function(){return m.call(this)}),_library&&!a||!BUGGY&&!h&&p[ITERATOR]||_hide(p,ITERATOR,v),_iterators[t]=v,_iterators[d]=returnThis,n)if(s={values:f?v:l(VALUES),keys:o?v:l(KEYS),entries:g},a)for(u in s)u in p||_redefine(p,u,s[u]);else _export(_export.P+_export.F*(BUGGY||h),t,s);return s},$at=_stringAt(!0);_iterDefine(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,r=this._i;return r>=t.length?{value:void 0,done:!0}:(e=$at(t,r),this._i+=e.length,{value:e,done:!1})});var _iterStep=function(e,t){return{value:t,done:!!e}},es6_array_iterator=_iterDefine(Array,"Array",function(e,t){this._t=_toIobject(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,r=this._i++;return!e||r>=e.length?(this._t=void 0,_iterStep(1)):_iterStep(0,"keys"==t?r:"values"==t?e[r]:[r,e[r]])},"values");_iterators.Arguments=_iterators.Array;for(var TO_STRING_TAG=_wks("toStringTag"),DOMIterables="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),i=0;i<DOMIterables.length;i++){var NAME=DOMIterables[i],Collection=_global[NAME],proto=Collection&&Collection.prototype;proto&&!proto[TO_STRING_TAG]&&_hide(proto,TO_STRING_TAG,NAME),_iterators[NAME]=_iterators.Array}var _redefineAll=function(e,t,r){for(var i in t)r&&e[i]?e[i]=t[i]:_hide(e,i,t[i]);return e},_anInstance=function(e,t,r,i){if(!(e instanceof t)||void 0!==i&&i in e)throw TypeError(r+": incorrect invocation!");return e},_iterCall=function(e,t,r,i){try{return i?t(_anObject(r)[0],r[1]):t(r)}catch(t){var n=e.return;throw void 0!==n&&_anObject(n.call(e)),t}},ITERATOR$1=_wks("iterator"),ArrayProto=Array.prototype,_isArrayIter=function(e){return void 0!==e&&(_iterators.Array===e||ArrayProto[ITERATOR$1]===e)},TAG$1=_wks("toStringTag"),ARG="Arguments"==_cof(function(){return arguments}()),tryGet=function(e,t){try{return e[t]}catch(e){}},_classof=function(e){var t,r,i;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=tryGet(t=Object(e),TAG$1))?r:ARG?_cof(t):"Object"==(i=_cof(t))&&"function"==typeof t.callee?"Arguments":i},ITERATOR$2=_wks("iterator"),core_getIteratorMethod=_core.getIteratorMethod=function(e){if(void 0!=e)return e[ITERATOR$2]||e["@@iterator"]||_iterators[_classof(e)]},_forOf=createCommonjsModule(function(e){var t={},r={},i=e.exports=function(e,i,n,o,a){var s,u,c,l,d=a?function(){return e}:core_getIteratorMethod(e),f=_ctx(n,o,i?2:1),h=0;if("function"!=typeof d)throw TypeError(e+" is not iterable!");if(_isArrayIter(d)){for(s=_toLength(e.length);s>h;h++)if((l=i?f(_anObject(u=e[h])[0],u[1]):f(e[h]))===t||l===r)return l}else for(c=d.call(e);!(u=c.next()).done;)if((l=_iterCall(c,f,u.value,i))===t||l===r)return l};i.BREAK=t,i.RETURN=r}),SPECIES=_wks("species"),_setSpecies=function(e){var t="function"==typeof _core[e]?_core[e]:_global[e];_descriptors&&t&&!t[SPECIES]&&_objectDp.f(t,SPECIES,{configurable:!0,get:function(){return this}})},_meta=createCommonjsModule(function(e){var t=_uid("meta"),r=_objectDp.f,i=0,n=Object.isExtensible||function(){return!0},o=!_fails(function(){return n(Object.preventExtensions({}))}),a=function(e){r(e,t,{value:{i:"O"+ ++i,w:{}}})},s=e.exports={KEY:t,NEED:!1,fastKey:function(e,r){if(!_isObject(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!_has(e,t)){if(!n(e))return"F";if(!r)return"E";a(e)}return e[t].i},getWeak:function(e,r){if(!_has(e,t)){if(!n(e))return!0;if(!r)return!1;a(e)}return e[t].w},onFreeze:function(e){return o&&s.NEED&&n(e)&&!_has(e,t)&&a(e),e}}}),_meta_1=_meta.KEY,_meta_2=_meta.NEED,_meta_3=_meta.fastKey,_meta_4=_meta.getWeak,_meta_5=_meta.onFreeze,_validateCollection=function(e,t){if(!_isObject(e)||e._t!==t)throw TypeError("Incompatible receiver, "+t+" required!");return e},dP$1=_objectDp.f,fastKey=_meta.fastKey,SIZE=_descriptors?"_s":"size",getEntry=function(e,t){var r,i=fastKey(t);if("F"!==i)return e._i[i];for(r=e._f;r;r=r.n)if(r.k==t)return r},_collectionStrong={getConstructor:function(e,t,r,i){var n=e(function(e,o){_anInstance(e,n,t,"_i"),e._t=t,e._i=_objectCreate(null),e._f=void 0,e._l=void 0,e[SIZE]=0,void 0!=o&&_forOf(o,r,e[i],e)});return _redefineAll(n.prototype,{clear:function(){for(var e=_validateCollection(this,t),r=e._i,i=e._f;i;i=i.n)i.r=!0,i.p&&(i.p=i.p.n=void 0),delete r[i.i];e._f=e._l=void 0,e[SIZE]=0},delete:function(e){var r=_validateCollection(this,t),i=getEntry(r,e);if(i){var n=i.n,o=i.p;delete r._i[i.i],i.r=!0,o&&(o.n=n),n&&(n.p=o),r._f==i&&(r._f=n),r._l==i&&(r._l=o),r[SIZE]--}return!!i},forEach:function(e){_validateCollection(this,t);for(var r,i=_ctx(e,arguments.length>1?arguments[1]:void 0,3);r=r?r.n:this._f;)for(i(r.v,r.k,this);r&&r.r;)r=r.p},has:function(e){return!!getEntry(_validateCollection(this,t),e)}}),_descriptors&&dP$1(n.prototype,"size",{get:function(){return _validateCollection(this,t)[SIZE]}}),n},def:function(e,t,r){var i,n,o=getEntry(e,t);return o?o.v=r:(e._l=o={i:n=fastKey(t,!0),k:t,v:r,p:i=e._l,n:void 0,r:!1},e._f||(e._f=o),i&&(i.n=o),e[SIZE]++,"F"!==n&&(e._i[n]=o)),e},getEntry:getEntry,setStrong:function(e,t,r){_iterDefine(e,t,function(e,r){this._t=_validateCollection(e,t),this._k=r,this._l=void 0},function(){for(var e=this._k,t=this._l;t&&t.r;)t=t.p;return this._t&&(this._l=t=t?t.n:this._t._f)?_iterStep(0,"keys"==e?t.k:"values"==e?t.v:[t.k,t.v]):(this._t=void 0,_iterStep(1))},r?"entries":"values",!r,!0),_setSpecies(t)}},_isArray=Array.isArray||function(e){return"Array"==_cof(e)},SPECIES$1=_wks("species"),_arraySpeciesConstructor=function(e){var t;return _isArray(e)&&("function"!=typeof(t=e.constructor)||t!==Array&&!_isArray(t.prototype)||(t=void 0),_isObject(t)&&null===(t=t[SPECIES$1])&&(t=void 0)),void 0===t?Array:t},_arraySpeciesCreate=function(e,t){return new(_arraySpeciesConstructor(e))(t)},_arrayMethods=function(e,t){var r=1==e,i=2==e,n=3==e,o=4==e,a=6==e,s=5==e||a,u=t||_arraySpeciesCreate;return function(t,c,l){for(var d,f,h=_toObject(t),p=_iobject(h),m=_ctx(c,l,3),v=_toLength(p.length),g=0,y=r?u(t,v):i?u(t,0):void 0;v>g;g++)if((s||g in p)&&(f=m(d=p[g],g,h),e))if(r)y[g]=f;else if(f)switch(e){case 3:return!0;case 5:return d;case 6:return g;case 2:y.push(d)}else if(o)return!1;return a?-1:n||o?o:y}},dP$2=_objectDp.f,each=_arrayMethods(0),_collection=function(e,t,r,i,n,o){var a=_global[e],s=a,u=n?"set":"add",c=s&&s.prototype,l={};return _descriptors&&"function"==typeof s&&(o||c.forEach&&!_fails(function(){(new s).entries().next()}))?(s=t(function(t,r){_anInstance(t,s,e,"_c"),t._c=new a,void 0!=r&&_forOf(r,n,t[u],t)}),each("add,clear,delete,forEach,get,has,set,keys,values,entries,toJSON".split(","),function(e){var t="add"==e||"set"==e;e in c&&(!o||"clear"!=e)&&_hide(s.prototype,e,function(r,i){if(_anInstance(this,s,e),!t&&o&&!_isObject(r))return"get"==e&&void 0;var n=this._c[e](0===r?0:r,i);return t?this:n})}),o||dP$2(s.prototype,"size",{get:function(){return this._c.size}})):(s=i.getConstructor(t,e,n,u),_redefineAll(s.prototype,r),_meta.NEED=!0),_setToStringTag(s,e),l[e]=s,_export(_export.G+_export.W+_export.F,l),o||i.setStrong(s,e,n),s},MAP="Map",es6_map=_collection(MAP,function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},{get:function(e){var t=_collectionStrong.getEntry(_validateCollection(this,MAP),e);return t&&t.v},set:function(e,t){return _collectionStrong.def(_validateCollection(this,MAP),0===e?0:e,t)}},_collectionStrong,!0),_arrayFromIterable=function(e,t){var r=[];return _forOf(e,!1,r.push,r,t),r},_collectionToJson=function(e){return function(){if(_classof(this)!=e)throw TypeError(e+"#toJSON isn't generic");return _arrayFromIterable(this)}};_export(_export.P+_export.R,"Map",{toJSON:_collectionToJson("Map")});var _setCollectionOf=function(e){_export(_export.S,e,{of:function(){for(var e=arguments.length,t=new Array(e);e--;)t[e]=arguments[e];return new this(t)}})};_setCollectionOf("Map");var _setCollectionFrom=function(e){_export(_export.S,e,{from:function(e){var t,r,i,n,o=arguments[1];return _aFunction(this),(t=void 0!==o)&&_aFunction(o),void 0==e?new this:(r=[],t?(i=0,n=_ctx(o,arguments[2],2),_forOf(e,!1,function(e){r.push(n(e,i++))})):_forOf(e,!1,r.push,r),new this(r))}})};_setCollectionFrom("Map");var map=_core.Map,map$1=createCommonjsModule(function(e){e.exports={default:map,__esModule:!0}}),_Map=unwrapExports(map$1),_createProperty=function(e,t,r){t in e?_objectDp.f(e,t,_propertyDesc(0,r)):e[t]=r},ITERATOR$3=_wks("iterator"),SAFE_CLOSING=!1;try{var riter=[7][ITERATOR$3]();riter.return=function(){SAFE_CLOSING=!0}}catch(e){}var _iterDetect=function(e,t){if(!t&&!SAFE_CLOSING)return!1;var r=!1;try{var i=[7],n=i[ITERATOR$3]();n.next=function(){return{done:r=!0}},i[ITERATOR$3]=function(){return n},e(i)}catch(e){}return r};_export(_export.S+_export.F*!_iterDetect(function(e){}),"Array",{from:function(e){var t,r,i,n,o=_toObject(e),a="function"==typeof this?this:Array,s=arguments.length,u=s>1?arguments[1]:void 0,c=void 0!==u,l=0,d=core_getIteratorMethod(o);if(c&&(u=_ctx(u,s>2?arguments[2]:void 0,2)),void 0==d||a==Array&&_isArrayIter(d))for(r=new a(t=_toLength(o.length));t>l;l++)_createProperty(r,l,c?u(o[l],l):o[l]);else for(n=d.call(o),r=new a;!(i=n.next()).done;l++)_createProperty(r,l,c?_iterCall(n,u,[i.value,l],!0):i.value);return r.length=l,r}});var from=_core.Array.from,from$1=createCommonjsModule(function(e){e.exports={default:from,__esModule:!0}}),_Array$from=unwrapExports(from$1),toConsumableArray=createCommonjsModule(function(e,t){t.__esModule=!0;var r,i=(r=from$1)&&r.__esModule?r:{default:r};t.default=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return(0,i.default)(e)}}),_toConsumableArray=unwrapExports(toConsumableArray),SPECIES$2=_wks("species"),_speciesConstructor=function(e,t){var r,i=_anObject(e).constructor;return void 0===i||void 0==(r=_anObject(i)[SPECIES$2])?t:_aFunction(r)},_invoke=function(e,t,r){var i=void 0===r;switch(t.length){case 0:return i?e():e.call(r);case 1:return i?e(t[0]):e.call(r,t[0]);case 2:return i?e(t[0],t[1]):e.call(r,t[0],t[1]);case 3:return i?e(t[0],t[1],t[2]):e.call(r,t[0],t[1],t[2]);case 4:return i?e(t[0],t[1],t[2],t[3]):e.call(r,t[0],t[1],t[2],t[3])}return e.apply(r,t)},process=_global.process,setTask=_global.setImmediate,clearTask=_global.clearImmediate,MessageChannel=_global.MessageChannel,Dispatch=_global.Dispatch,counter=0,queue={},ONREADYSTATECHANGE="onreadystatechange",defer,channel,port,run=function(){var e=+this;if(queue.hasOwnProperty(e)){var t=queue[e];delete queue[e],t()}},listener=function(e){run.call(e.data)};setTask&&clearTask||(setTask=function(e){for(var t=[],r=1;arguments.length>r;)t.push(arguments[r++]);return queue[++counter]=function(){_invoke("function"==typeof e?e:Function(e),t)},defer(counter),counter},clearTask=function(e){delete queue[e]},"process"==_cof(process)?defer=function(e){process.nextTick(_ctx(run,e,1))}:Dispatch&&Dispatch.now?defer=function(e){Dispatch.now(_ctx(run,e,1))}:MessageChannel?(channel=new MessageChannel,port=channel.port2,channel.port1.onmessage=listener,defer=_ctx(port.postMessage,port,1)):_global.addEventListener&&"function"==typeof postMessage&&!_global.importScripts?(defer=function(e){_global.postMessage(e+"","*")},_global.addEventListener("message",listener,!1)):defer=ONREADYSTATECHANGE in _domCreate("script")?function(e){_html.appendChild(_domCreate("script"))[ONREADYSTATECHANGE]=function(){_html.removeChild(this),run.call(e)}}:function(e){setTimeout(_ctx(run,e,1),0)});var _task={set:setTask,clear:clearTask},macrotask=_task.set,Observer=_global.MutationObserver||_global.WebKitMutationObserver,process$1=_global.process,Promise$1=_global.Promise,isNode="process"==_cof(process$1),_microtask=function(){var e,t,r,i=function(){var i,n;for(isNode&&(i=process$1.domain)&&i.exit();e;){n=e.fn,e=e.next;try{n()}catch(i){throw e?r():t=void 0,i}}t=void 0,i&&i.enter()};if(isNode)r=function(){process$1.nextTick(i)};else if(!Observer||_global.navigator&&_global.navigator.standalone)if(Promise$1&&Promise$1.resolve){var n=Promise$1.resolve();r=function(){n.then(i)}}else r=function(){macrotask.call(_global,i)};else{var o=!0,a=document.createTextNode("");new Observer(i).observe(a,{characterData:!0}),r=function(){a.data=o=!o}}return function(i){var n={fn:i,next:void 0};t&&(t.next=n),e||(e=n,r()),t=n}};function PromiseCapability(e){var t,r;this.promise=new e(function(e,i){if(void 0!==t||void 0!==r)throw TypeError("Bad Promise constructor");t=e,r=i}),this.resolve=_aFunction(t),this.reject=_aFunction(r)}var f$3=function(e){return new PromiseCapability(e)},_newPromiseCapability={f:f$3},_perform=function(e){try{return{e:!1,v:e()}}catch(e){return{e:!0,v:e}}},_promiseResolve=function(e,t){if(_anObject(e),_isObject(t)&&t.constructor===e)return t;var r=_newPromiseCapability.f(e);return(0,r.resolve)(t),r.promise},task=_task.set,microtask=_microtask(),PROMISE="Promise",TypeError$1=_global.TypeError,process$2=_global.process,$Promise=_global[PROMISE],isNode$1="process"==_classof(process$2),empty=function(){},Internal,newGenericPromiseCapability,OwnPromiseCapability,Wrapper,newPromiseCapability=newGenericPromiseCapability=_newPromiseCapability.f,USE_NATIVE=!!function(){try{var e=$Promise.resolve(1),t=(e.constructor={})[_wks("species")]=function(e){e(empty,empty)};return(isNode$1||"function"==typeof PromiseRejectionEvent)&&e.then(empty)instanceof t}catch(e){}}(),isThenable=function(e){var t;return!(!_isObject(e)||"function"!=typeof(t=e.then))&&t},notify=function(e,t){if(!e._n){e._n=!0;var r=e._c;microtask(function(){for(var i=e._v,n=1==e._s,o=0,a=function(t){var r,o,a=n?t.ok:t.fail,s=t.resolve,u=t.reject,c=t.domain;try{a?(n||(2==e._h&&onHandleUnhandled(e),e._h=1),!0===a?r=i:(c&&c.enter(),r=a(i),c&&c.exit()),r===t.promise?u(TypeError$1("Promise-chain cycle")):(o=isThenable(r))?o.call(r,s,u):s(r)):u(i)}catch(e){u(e)}};r.length>o;)a(r[o++]);e._c=[],e._n=!1,t&&!e._h&&onUnhandled(e)})}},onUnhandled=function(e){task.call(_global,function(){var t,r,i,n=e._v,o=isUnhandled(e);if(o&&(t=_perform(function(){isNode$1?process$2.emit("unhandledRejection",n,e):(r=_global.onunhandledrejection)?r({promise:e,reason:n}):(i=_global.console)&&i.error&&i.error("Unhandled promise rejection",n)}),e._h=isNode$1||isUnhandled(e)?2:1),e._a=void 0,o&&t.e)throw t.v})},isUnhandled=function(e){return 1!==e._h&&0===(e._a||e._c).length},onHandleUnhandled=function(e){task.call(_global,function(){var t;isNode$1?process$2.emit("rejectionHandled",e):(t=_global.onrejectionhandled)&&t({promise:e,reason:e._v})})},$reject=function(e){var t=this;t._d||(t._d=!0,(t=t._w||t)._v=e,t._s=2,t._a||(t._a=t._c.slice()),notify(t,!0))},$resolve=function(e){var t,r=this;if(!r._d){r._d=!0,r=r._w||r;try{if(r===e)throw TypeError$1("Promise can't be resolved itself");(t=isThenable(e))?microtask(function(){var i={_w:r,_d:!1};try{t.call(e,_ctx($resolve,i,1),_ctx($reject,i,1))}catch(e){$reject.call(i,e)}}):(r._v=e,r._s=1,notify(r,!1))}catch(e){$reject.call({_w:r,_d:!1},e)}}};USE_NATIVE||($Promise=function(e){_anInstance(this,$Promise,PROMISE,"_h"),_aFunction(e),Internal.call(this);try{e(_ctx($resolve,this,1),_ctx($reject,this,1))}catch(e){$reject.call(this,e)}},Internal=function(e){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},Internal.prototype=_redefineAll($Promise.prototype,{then:function(e,t){var r=newPromiseCapability(_speciesConstructor(this,$Promise));return r.ok="function"!=typeof e||e,r.fail="function"==typeof t&&t,r.domain=isNode$1?process$2.domain:void 0,this._c.push(r),this._a&&this._a.push(r),this._s&¬ify(this,!1),r.promise},catch:function(e){return this.then(void 0,e)}}),OwnPromiseCapability=function(){var e=new Internal;this.promise=e,this.resolve=_ctx($resolve,e,1),this.reject=_ctx($reject,e,1)},_newPromiseCapability.f=newPromiseCapability=function(e){return e===$Promise||e===Wrapper?new OwnPromiseCapability(e):newGenericPromiseCapability(e)}),_export(_export.G+_export.W+_export.F*!USE_NATIVE,{Promise:$Promise}),_setToStringTag($Promise,PROMISE),_setSpecies(PROMISE),Wrapper=_core[PROMISE],_export(_export.S+_export.F*!USE_NATIVE,PROMISE,{reject:function(e){var t=newPromiseCapability(this);return(0,t.reject)(e),t.promise}}),_export(_export.S+_export.F*(_library||!USE_NATIVE),PROMISE,{resolve:function(e){return _promiseResolve(_library&&this===Wrapper?$Promise:this,e)}}),_export(_export.S+_export.F*!(USE_NATIVE&&_iterDetect(function(e){$Promise.all(e).catch(empty)})),PROMISE,{all:function(e){var t=this,r=newPromiseCapability(t),i=r.resolve,n=r.reject,o=_perform(function(){var r=[],o=0,a=1;_forOf(e,!1,function(e){var s=o++,u=!1;r.push(void 0),a++,t.resolve(e).then(function(e){u||(u=!0,r[s]=e,--a||i(r))},n)}),--a||i(r)});return o.e&&n(o.v),r.promise},race:function(e){var t=this,r=newPromiseCapability(t),i=r.reject,n=_perform(function(){_forOf(e,!1,function(e){t.resolve(e).then(r.resolve,i)})});return n.e&&i(n.v),r.promise}}),_export(_export.P+_export.R,"Promise",{finally:function(e){var t=_speciesConstructor(this,_core.Promise||_global.Promise),r="function"==typeof e;return this.then(r?function(r){return _promiseResolve(t,e()).then(function(){return r})}:e,r?function(r){return _promiseResolve(t,e()).then(function(){throw r})}:e)}}),_export(_export.S,"Promise",{try:function(e){var t=_newPromiseCapability.f(this),r=_perform(e);return(r.e?t.reject:t.resolve)(r.v),t.promise}});var promise=_core.Promise,promise$1=createCommonjsModule(function(e){e.exports={default:promise,__esModule:!0}}),_Promise=unwrapExports(promise$1),classCallCheck=createCommonjsModule(function(e,t){t.__esModule=!0,t.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}}),_classCallCheck=unwrapExports(classCallCheck);_export(_export.S+_export.F*!_descriptors,"Object",{defineProperty:_objectDp.f});var $Object$1=_core.Object,defineProperty=function(e,t,r){return $Object$1.defineProperty(e,t,r)},defineProperty$1=createCommonjsModule(function(e){e.exports={default:defineProperty,__esModule:!0}}),_Object$defineProperty=unwrapExports(defineProperty$1),createClass=createCommonjsModule(function(e,t){t.__esModule=!0;var r,i=(r=defineProperty$1)&&r.__esModule?r:{default:r};t.default=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),(0,i.default)(e,n.key,n)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}()}),_createClass=unwrapExports(createClass),f$4=_wks,_wksExt={f:f$4},iterator=_wksExt.f("iterator"),iterator$1=createCommonjsModule(function(e){e.exports={default:iterator,__esModule:!0}});unwrapExports(iterator$1);var defineProperty$2=_objectDp.f,_wksDefine=function(e){var t=_core.Symbol||(_core.Symbol=_library?{}:_global.Symbol||{});"_"==e.charAt(0)||e in t||defineProperty$2(t,e,{value:_wksExt.f(e)})},f$5=Object.getOwnPropertySymbols,_objectGops={f:f$5},_enumKeys=function(e){var t=_objectKeys(e),r=_objectGops.f;if(r)for(var i,n=r(e),o=_objectPie.f,a=0;n.length>a;)o.call(e,i=n[a++])&&t.push(i);return t},hiddenKeys=_enumBugKeys.concat("length","prototype"),f$6=Object.getOwnPropertyNames||function(e){return _objectKeysInternal(e,hiddenKeys)},_objectGopn={f:f$6},gOPN=_objectGopn.f,toString$1={}.toString,windowNames="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],getWindowNames=function(e){try{return gOPN(e)}catch(e){return windowNames.slice()}},f$7=function(e){return windowNames&&"[object Window]"==toString$1.call(e)?getWindowNames(e):gOPN(_toIobject(e))},_objectGopnExt={f:f$7},META=_meta.KEY,gOPD$1=_objectGopd.f,dP$3=_objectDp.f,gOPN$1=_objectGopnExt.f,$Symbol=_global.Symbol,$JSON=_global.JSON,_stringify=$JSON&&$JSON.stringify,PROTOTYPE$2="prototype",HIDDEN=_wks("_hidden"),TO_PRIMITIVE=_wks("toPrimitive"),isEnum={}.propertyIsEnumerable,SymbolRegistry=_shared("symbol-registry"),AllSymbols=_shared("symbols"),OPSymbols=_shared("op-symbols"),ObjectProto$1=Object[PROTOTYPE$2],USE_NATIVE$1="function"==typeof $Symbol,QObject=_global.QObject,setter=!QObject||!QObject[PROTOTYPE$2]||!QObject[PROTOTYPE$2].findChild,setSymbolDesc=_descriptors&&_fails(function(){return 7!=_objectCreate(dP$3({},"a",{get:function(){return dP$3(this,"a",{value:7}).a}})).a})?function(e,t,r){var i=gOPD$1(ObjectProto$1,t);i&&delete ObjectProto$1[t],dP$3(e,t,r),i&&e!==ObjectProto$1&&dP$3(ObjectProto$1,t,i)}:dP$3,wrap=function(e){var t=AllSymbols[e]=_objectCreate($Symbol[PROTOTYPE$2]);return t._k=e,t},isSymbol=USE_NATIVE$1&&"symbol"==typeof $Symbol.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof $Symbol},$defineProperty=function(e,t,r){return e===ObjectProto$1&&$defineProperty(OPSymbols,t,r),_anObject(e),t=_toPrimitive(t,!0),_anObject(r),_has(AllSymbols,t)?(r.enumerable?(_has(e,HIDDEN)&&e[HIDDEN][t]&&(e[HIDDEN][t]=!1),r=_objectCreate(r,{enumerable:_propertyDesc(0,!1)})):(_has(e,HIDDEN)||dP$3(e,HIDDEN,_propertyDesc(1,{})),e[HIDDEN][t]=!0),setSymbolDesc(e,t,r)):dP$3(e,t,r)},$defineProperties=function(e,t){_anObject(e);for(var r,i=_enumKeys(t=_toIobject(t)),n=0,o=i.length;o>n;)$defineProperty(e,r=i[n++],t[r]);return e},$create=function(e,t){return void 0===t?_objectCreate(e):$defineProperties(_objectCreate(e),t)},$propertyIsEnumerable=function(e){var t=isEnum.call(this,e=_toPrimitive(e,!0));return!(this===ObjectProto$1&&_has(AllSymbols,e)&&!_has(OPSymbols,e))&&(!(t||!_has(this,e)||!_has(AllSymbols,e)||_has(this,HIDDEN)&&this[HIDDEN][e])||t)},$getOwnPropertyDescriptor$1=function(e,t){if(e=_toIobject(e),t=_toPrimitive(t,!0),e!==ObjectProto$1||!_has(AllSymbols,t)||_has(OPSymbols,t)){var r=gOPD$1(e,t);return!r||!_has(AllSymbols,t)||_has(e,HIDDEN)&&e[HIDDEN][t]||(r.enumerable=!0),r}},$getOwnPropertyNames=function(e){for(var t,r=gOPN$1(_toIobject(e)),i=[],n=0;r.length>n;)_has(AllSymbols,t=r[n++])||t==HIDDEN||t==META||i.push(t);return i},$getOwnPropertySymbols=function(e){for(var t,r=e===ObjectProto$1,i=gOPN$1(r?OPSymbols:_toIobject(e)),n=[],o=0;i.length>o;)!_has(AllSymbols,t=i[o++])||r&&!_has(ObjectProto$1,t)||n.push(AllSymbols[t]);return n};USE_NATIVE$1||($Symbol=function(){if(this instanceof $Symbol)throw TypeError("Symbol is not a constructor!");var e=_uid(arguments.length>0?arguments[0]:void 0),t=function(r){this===ObjectProto$1&&t.call(OPSymbols,r),_has(this,HIDDEN)&&_has(this[HIDDEN],e)&&(this[HIDDEN][e]=!1),setSymbolDesc(this,e,_propertyDesc(1,r))};return _descriptors&&setter&&setSymbolDesc(ObjectProto$1,e,{configurable:!0,set:t}),wrap(e)},_redefine($Symbol[PROTOTYPE$2],"toString",function(){return this._k}),_objectGopd.f=$getOwnPropertyDescriptor$1,_objectDp.f=$defineProperty,_objectGopn.f=_objectGopnExt.f=$getOwnPropertyNames,_objectPie.f=$propertyIsEnumerable,_objectGops.f=$getOwnPropertySymbols,_descriptors&&!_library&&_redefine(ObjectProto$1,"propertyIsEnumerable",$propertyIsEnumerable,!0),_wksExt.f=function(e){return wrap(_wks(e))}),_export(_export.G+_export.W+_export.F*!USE_NATIVE$1,{Symbol:$Symbol});for(var es6Symbols="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),j=0;es6Symbols.length>j;)_wks(es6Symbols[j++]);for(var wellKnownSymbols=_objectKeys(_wks.store),k=0;wellKnownSymbols.length>k;)_wksDefine(wellKnownSymbols[k++]);_export(_export.S+_export.F*!USE_NATIVE$1,"Symbol",{for:function(e){return _has(SymbolRegistry,e+="")?SymbolRegistry[e]:SymbolRegistry[e]=$Symbol(e)},keyFor:function(e){if(!isSymbol(e))throw TypeError(e+" is not a symbol!");for(var t in SymbolRegistry)if(SymbolRegistry[t]===e)return t},useSetter:function(){setter=!0},useSimple:function(){setter=!1}}),_export(_export.S+_export.F*!USE_NATIVE$1,"Object",{create:$create,defineProperty:$defineProperty,defineProperties:$defineProperties,getOwnPropertyDescriptor:$getOwnPropertyDescriptor$1,getOwnPropertyNames:$getOwnPropertyNames,getOwnPropertySymbols:$getOwnPropertySymbols}),$JSON&&_export(_export.S+_export.F*(!USE_NATIVE$1||_fails(function(){var e=$Symbol();return"[null]"!=_stringify([e])||"{}"!=_stringify({a:e})||"{}"!=_stringify(Object(e))})),"JSON",{stringify:function(e){for(var t,r,i=[e],n=1;arguments.length>n;)i.push(arguments[n++]);if(r=t=i[1],(_isObject(t)||void 0!==e)&&!isSymbol(e))return _isArray(t)||(t=function(e,t){if("function"==typeof r&&(t=r.call(this,e,t)),!isSymbol(t))return t}),i[1]=t,_stringify.apply($JSON,i)}}),$Symbol[PROTOTYPE$2][TO_PRIMITIVE]||_hide($Symbol[PROTOTYPE$2],TO_PRIMITIVE,$Symbol[PROTOTYPE$2].valueOf),_setToStringTag($Symbol,"Symbol"),_setToStringTag(Math,"Math",!0),_setToStringTag(_global.JSON,"JSON",!0),_wksDefine("asyncIterator"),_wksDefine("observable");var symbol=_core.Symbol,symbol$1=createCommonjsModule(function(e){e.exports={default:symbol,__esModule:!0}});unwrapExports(symbol$1);var _typeof_1=createCommonjsModule(function(e,t){t.__esModule=!0;var r=o(iterator$1),i=o(symbol$1),n="function"==typeof i.default&&"symbol"==typeof r.default?function(e){return typeof e}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":typeof e};function o(e){return e&&e.__esModule?e:{default:e}}t.default="function"==typeof i.default&&"symbol"===n(r.default)?function(e){return void 0===e?"undefined":n(e)}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":void 0===e?"undefined":n(e)}}),_typeof=unwrapExports(_typeof_1);_objectSap("keys",function(){return function(e){return _objectKeys(_toObject(e))}});var keys=_core.Object.keys,keys$1=createCommonjsModule(function(e){e.exports={default:keys,__esModule:!0}}),_Object$keys=unwrapExports(keys$1),floor$1=Math.floor,_isInteger=function(e){return!_isObject(e)&&isFinite(e)&&floor$1(e)===e};_export(_export.S,"Number",{isInteger:_isInteger});var isInteger=_core.Number.isInteger,isInteger$1=createCommonjsModule(function(e){e.exports={default:isInteger,__esModule:!0}}),_Number$isInteger=unwrapExports(isInteger$1),_stringWs="\t\n\v\f\r \u2028\u2029\ufeff",space="["+_stringWs+"]",non="
",ltrim=RegExp("^"+space+space+"*"),rtrim=RegExp(space+space+"*$"),exporter=function(e,t,r){var i={},n=_fails(function(){return!!_stringWs[e]()||non[e]()!=non}),o=i[e]=n?t(trim):_stringWs[e];r&&(i[r]=o),_export(_export.P+_export.F*n,"String",i)},trim=exporter.trim=function(e,t){return e=String(_defined(e)),1&t&&(e=e.replace(ltrim,"")),2&t&&(e=e.replace(rtrim,"")),e},_stringTrim=exporter,$parseFloat=_global.parseFloat,$trim=_stringTrim.trim,_parseFloat=1/$parseFloat(_stringWs+"-0")!=-1/0?function(e){var t=$trim(String(e),3),r=$parseFloat(t);return 0===r&&"-"==t.charAt(0)?-0:r}:$parseFloat;_export(_export.S+_export.F*(Number.parseFloat!=_parseFloat),"Number",{parseFloat:_parseFloat});var _parseFloat$1=parseFloat,_parseFloat$2=createCommonjsModule(function(e){e.exports={default:_parseFloat$1,__esModule:!0}}),_Number$parseFloat=unwrapExports(_parseFloat$2);function defined(e){return void 0!==e}function isVoid(e){return void 0===e||null===e}function isArray(e){return Array.isArray(e)}function isFunction(e){return"function"==typeof e}function isObject(e){return Object(e)===e&&"[object Object]"===String(e)&&!isFunction(e)&&!isArray(e)}function isNumber(e){return"number"==typeof e}function isNumeric(e){return!isArray(e)&&e-_Number$parseFloat(e)+1>=0}function isInteger$2(e){return _Number$isInteger(e)}function isEmpty(e){return isArray(e)?0===e.length:isObject(e)?0===_Object$keys(e).length:!e}function isEvent(e){return e instanceof Event||(e&&e.originalEvent)instanceof Event}function isBlob(e){return e instanceof Blob}function isFile(e){return isBlob(e)&&isString(e.name)}function isDate(e){return"[object Date]"===Object.prototype.toString.call(e)}function isString(e){return"string"==typeof e||e instanceof String}function isBoolean(e){return"boolean"==typeof e}function isPromise(e){return!!e&&("object"===(void 0===e?"undefined":_typeof(e))||"function"==typeof e)&&"function"==typeof e.then}function isPrimitive(e){return isVoid(e)||isBoolean(e)||isString(e)||isNumber(e)}function isUrl(e){return isString(e)&&!!e.match(/^((https?|ftp|rtsp|mms):\/\/)(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6}|localhost)(:[0-9]{1,4})?((\/?)|(\/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+\/?)$/i)}function isNode$2(e){return!!("object"===("undefined"==typeof Node?"undefined":_typeof(Node))?e instanceof Node:e&&"object"===(void 0===e?"undefined":_typeof(e))&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName)}function isElement(e){return!!("object"===("undefined"==typeof HTMLElement?"undefined":_typeof(HTMLElement))?e instanceof HTMLElement:e&&"object"===(void 0===e?"undefined":_typeof(e))&&null!==e&&1===e.nodeType&&"string"==typeof e.nodeName)}function isChildNode(e,t){return!(!isNode$2(e)||!isNode$2(t))&&t.parentNode===e}function isPosterityNode(e,t){if(!isNode$2(e)||!isNode$2(t))return!1;for(;t.parentNode;)if((t=t.parentNode)===e)return!0;return!1}function isHTMLString(e){return/<[^>]+?>/.test(e)}function isError(e){return e instanceof Error}function isRegExp(e){return e instanceof RegExp}function formatter(e,t){if(!isString(e))throw new TypeError("Log's method only acccept string as argument, but not "+e+" in "+(void 0===e?"undefined":_typeof(e)));return isString(t)?"["+(e=Log$1.FORCE_GLOBAL_TAG?Log$1.GLOBAL_TAG:e||Log$1.GLOBAL_TAG)+"] > "+t:"["+Log$1.GLOBAL_TAG+"] > "+e}var Log$1=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"error",value:function(t,r){e.ENABLE_ERROR&&(console.error||console.warn||console.log)(formatter(t,r))}},{key:"info",value:function(t,r){e.ENABLE_INFO&&(console.info||console.log)(formatter(t,r))}},{key:"warn",value:function(t,r){e.ENABLE_WARN&&(console.warn||console.log)(formatter(t,r))}},{key:"debug",value:function(t,r){e.ENABLE_DEBUG&&(console.debug||console.log)(formatter(t,r))}},{key:"verbose",value:function(t,r){e.ENABLE_VERBOSE&&console.log(formatter(t,r))}}]),e}();Log$1.GLOBAL_TAG="chimee",Log$1.FORCE_GLOBAL_TAG=!1,Log$1.ENABLE_ERROR=!0,Log$1.ENABLE_INFO=!0,Log$1.ENABLE_WARN=!0,Log$1.ENABLE_DEBUG=!0,Log$1.ENABLE_VERBOSE=!0;var uaParser=createCommonjsModule(function(e,t){!function(r,i){var n="model",o="name",a="type",s="vendor",u="version",c="mobile",l="tablet",d={extend:function(e,t){var r={};for(var i in e)t[i]&&t[i].length%2==0?r[i]=t[i].concat(e[i]):r[i]=e[i];return r},has:function(e,t){return"string"==typeof e&&-1!==t.toLowerCase().indexOf(e.toLowerCase())},lowerize:function(e){return e.toLowerCase()},major:function(e){return"string"==typeof e?e.replace(/[^\d\.]/g,"").split(".")[0]:void 0},trim:function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}},f={rgx:function(e,t){for(var r,i,n,o,a,s,u=0;u<t.length&&!a;){var c=t[u],l=t[u+1];for(r=i=0;r<c.length&&!a;)if(a=c[r++].exec(e))for(n=0;n<l.length;n++)s=a[++i],"object"==typeof(o=l[n])&&o.length>0?2==o.length?"function"==typeof o[1]?this[o[0]]=o[1].call(this,s):this[o[0]]=o[1]:3==o.length?"function"!=typeof o[1]||o[1].exec&&o[1].test?this[o[0]]=s?s.replace(o[1],o[2]):void 0:this[o[0]]=s?o[1].call(this,s,o[2]):void 0:4==o.length&&(this[o[0]]=s?o[3].call(this,s.replace(o[1],o[2])):void 0):this[o]=s||void 0;u+=2}},str:function(e,t){for(var r in t)if("object"==typeof t[r]&&t[r].length>0){for(var i=0;i<t[r].length;i++)if(d.has(t[r][i],e))return"?"===r?void 0:r}else if(d.has(t[r],e))return"?"===r?void 0:r;return e}},h={browser:{oldsafari:{version:{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}}},device:{amazon:{model:{"Fire Phone":["SD","KF"]}},sprint:{model:{"Evo Shift 4G":"7373KT"},vendor:{HTC:"APA",Sprint:"Sprint"}}},os:{windows:{version:{ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2000:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"}}}},p={browser:[[/(opera\smini)\/([\w\.-]+)/i,/(opera\s[mobiletab]+).+version\/([\w\.-]+)/i,/(opera).+version\/([\w\.]+)/i,/(opera)[\/\s]+([\w\.]+)/i],[o,u],[/(opios)[\/\s]+([\w\.]+)/i],[[o,"Opera Mini"],u],[/\s(opr)\/([\w\.]+)/i],[[o,"Opera"],u],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]+)*/i,/(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?([\w\.]*)/i,/(?:ms|\()(ie)\s([\w\.]+)/i,/(rekonq)\/([\w\.]+)*/i,/(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser)\/([\w\.-]+)/i],[o,u],[/(trident).+rv[:\s]([\w\.]+).+like\sgecko/i],[[o,"IE"],u],[/(edge)\/((\d+)?[\w\.]+)/i],[o,u],[/(yabrowser)\/([\w\.]+)/i],[[o,"Yandex"],u],[/(puffin)\/([\w\.]+)/i],[[o,"Puffin"],u],[/((?:[\s\/])uc?\s?browser|(?:juc.+)ucweb)[\/\s]?([\w\.]+)/i],[[o,"UCBrowser"],u],[/(comodo_dragon)\/([\w\.]+)/i],[[o,/_/g," "],u],[/(micromessenger)\/([\w\.]+)/i],[[o,"WeChat"],u],[/(QQ)\/([\d\.]+)/i],[o,u],[/m?(qqbrowser)[\/\s]?([\w\.]+)/i],[o,u],[/xiaomi\/miuibrowser\/([\w\.]+)/i],[u,[o,"MIUI Browser"]],[/;fbav\/([\w\.]+);/i],[u,[o,"Facebook"]],[/headlesschrome(?:\/([\w\.]+)|\s)/i],[u,[o,"Chrome Headless"]],[/\swv\).+(chrome)\/([\w\.]+)/i],[[o,/(.+)/,"$1 WebView"],u],[/((?:oculus|samsung)browser)\/([\w\.]+)/i],[[o,/(.+(?:g|us))(.+)/,"$1 $2"],u],[/android.+version\/([\w\.]+)\s+(?:mobile\s?safari|safari)*/i],[u,[o,"Android Browser"]],[/(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i],[o,u],[/(dolfin)\/([\w\.]+)/i],[[o,"Dolphin"],u],[/((?:android.+)crmo|crios)\/([\w\.]+)/i],[[o,"Chrome"],u],[/(coast)\/([\w\.]+)/i],[[o,"Opera Coast"],u],[/fxios\/([\w\.-]+)/i],[u,[o,"Firefox"]],[/version\/([\w\.]+).+?mobile\/\w+\s(safari)/i],[u,[o,"Mobile Safari"]],[/version\/([\w\.]+).+?(mobile\s?safari|safari)/i],[u,o],[/webkit.+?(gsa)\/([\w\.]+).+?(mobile\s?safari|safari)(\/[\w\.]+)/i],[[o,"GSA"],u],[/webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i],[o,[u,f.str,h.browser.oldsafari.version]],[/(konqueror)\/([\w\.]+)/i,/(webkit|khtml)\/([\w\.]+)/i],[o,u],[/(navigator|netscape)\/([\w\.-]+)/i],[[o,"Netscape"],u],[/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i,/(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/([\w\.-]+)/i,/(mozilla)\/([\w\.]+).+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir)[\/\s]?([\w\.]+)/i,/(links)\s\(([\w\.]+)/i,/(gobrowser)\/?([\w\.]+)*/i,/(ice\s?browser)\/v?([\w\._]+)/i,/(mosaic)[\/\s]([\w\.]+)/i],[o,u]],cpu:[[/(?:(amd|x(?:(?:86|64)[_-])?|wow|win)64)[;\)]/i],[["architecture","amd64"]],[/(ia32(?=;))/i],[["architecture",d.lowerize]],[/((?:i[346]|x)86)[;\)]/i],[["architecture","ia32"]],[/windows\s(ce|mobile);\sppc;/i],[["architecture","arm"]],[/((?:ppc|powerpc)(?:64)?)(?:\smac|;|\))/i],[["architecture",/ower/,"",d.lowerize]],[/(sun4\w)[;\)]/i],[["architecture","sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|arm(?:64|(?=v\d+;))|(?=atmel\s)avr|(?:irix|mips|sparc)(?:64)?(?=;)|pa-risc)/i],[["architecture",d.lowerize]]],device:[[/\((ipad|playbook);[\w\s\);-]+(rim|apple)/i],[n,s,[a,l]],[/applecoremedia\/[\w\.]+ \((ipad)/],[n,[s,"Apple"],[a,l]],[/(apple\s{0,1}tv)/i],[[n,"Apple TV"],[s,"Apple"]],[/(archos)\s(gamepad2?)/i,/(hp).+(touchpad)/i,/(hp).+(tablet)/i,/(kindle)\/([\w\.]+)/i,/\s(nook)[\w\s]+build\/(\w+)/i,/(dell)\s(strea[kpr\s\d]*[\dko])/i],[s,n,[a,l]],[/(kf[A-z]+)\sbuild\/[\w\.]+.*silk\//i],[n,[s,"Amazon"],[a,l]],[/(sd|kf)[0349hijorstuw]+\sbuild\/[\w\.]+.*silk\//i],[[n,f.str,h.device.amazon.model],[s,"Amazon"],[a,c]],[/\((ip[honed|\s\w*]+);.+(apple)/i],[n,s,[a,c]],[/\((ip[honed|\s\w*]+);/i],[n,[s,"Apple"],[a,c]],[/(blackberry)[\s-]?(\w+)/i,/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[\s_-]?([\w-]+)*/i,/(hp)\s([\w\s]+\w)/i,/(asus)-?(\w+)/i],[s,n,[a,c]],[/\(bb10;\s(\w+)/i],[n,[s,"BlackBerry"],[a,c]],[/android.+(transfo[prime\s]{4,10}\s\w+|eeepc|slider\s\w+|nexus 7|padfone)/i],[n,[s,"Asus"],[a,l]],[/(sony)\s(tablet\s[ps])\sbuild\//i,/(sony)?(?:sgp.+)\sbuild\//i],[[s,"Sony"],[n,"Xperia Tablet"],[a,l]],[/android.+\s([c-g]\d{4}|so[-l]\w+)\sbuild\//i],[n,[s,"Sony"],[a,c]],[/\s(ouya)\s/i,/(nintendo)\s([wids3u]+)/i],[s,n,[a,"console"]],[/android.+;\s(shield)\sbuild/i],[n,[s,"Nvidia"],[a,"console"]],[/(playstation\s[34portablevi]+)/i],[n,[s,"Sony"],[a,"console"]],[/(sprint\s(\w+))/i],[[s,f.str,h.device.sprint.vendor],[n,f.str,h.device.sprint.model],[a,c]],[/(lenovo)\s?(S(?:5000|6000)+(?:[-][\w+]))/i],[s,n,[a,l]],[/(htc)[;_\s-]+([\w\s]+(?=\))|\w+)*/i,/(zte)-(\w+)*/i,/(alcatel|geeksphone|lenovo|nexian|panasonic|(?=;\s)sony)[_\s-]?([\w-]+)*/i],[s,[n,/_/g," "],[a,c]],[/(nexus\s9)/i],[n,[s,"HTC"],[a,l]],[/d\/huawei([\w\s-]+)[;\)]/i,/(nexus\s6p)/i],[n,[s,"Huawei"],[a,c]],[/(microsoft);\s(lumia[\s\w]+)/i],[s,n,[a,c]],[/[\s\(;](xbox(?:\sone)?)[\s\);]/i],[n,[s,"Microsoft"],[a,"console"]],[/(kin\.[onetw]{3})/i],[[n,/\./g," "],[s,"Microsoft"],[a,c]],[/\s(milestone|droid(?:[2-4x]|\s(?:bionic|x2|pro|razr))?(:?\s4g)?)[\w\s]+build\//i,/mot[\s-]?(\w+)*/i,/(XT\d{3,4}) build\//i,/(nexus\s6)/i],[n,[s,"Motorola"],[a,c]],[/android.+\s(mz60\d|xoom[\s2]{0,2})\sbuild\//i],[n,[s,"Motorola"],[a,l]],[/hbbtv\/\d+\.\d+\.\d+\s+\([\w\s]*;\s*(\w[^;]*);([^;]*)/i],[[s,d.trim],[n,d.trim],[a,"smarttv"]],[/hbbtv.+maple;(\d+)/i],[[n,/^/,"SmartTV"],[s,"Samsung"],[a,"smarttv"]],[/\(dtv[\);].+(aquos)/i],[n,[s,"Sharp"],[a,"smarttv"]],[/android.+((sch-i[89]0\d|shw-m380s|gt-p\d{4}|gt-n\d+|sgh-t8[56]9|nexus 10))/i,/((SM-T\w+))/i],[[s,"Samsung"],n,[a,l]],[/smart-tv.+(samsung)/i],[s,[a,"smarttv"],n],[/((s[cgp]h-\w+|gt-\w+|galaxy\snexus|sm-\w[\w\d]+))/i,/(sam[sung]*)[\s-]*(\w+-?[\w-]*)*/i,/sec-((sgh\w+))/i],[[s,"Samsung"],n,[a,c]],[/sie-(\w+)*/i],[n,[s,"Siemens"],[a,c]],[/(maemo|nokia).*(n900|lumia\s\d+)/i,/(nokia)[\s_-]?([\w-]+)*/i],[[s,"Nokia"],n,[a,c]],[/android\s3\.[\s\w;-]{10}(a\d{3})/i],[n,[s,"Acer"],[a,l]],[/android.+([vl]k\-?\d{3})\s+build/i],[n,[s,"LG"],[a,l]],[/android\s3\.[\s\w;-]{10}(lg?)-([06cv9]{3,4})/i],[[s,"LG"],n,[a,l]],[/(lg) netcast\.tv/i],[s,n,[a,"smarttv"]],[/(nexus\s[45])/i,/lg[e;\s\/-]+(\w+)*/i,/android.+lg(\-?[\d\w]+)\s+build/i],[n,[s,"LG"],[a,c]],[/android.+(ideatab[a-z0-9\-\s]+)/i],[n,[s,"Lenovo"],[a,l]],[/linux;.+((jolla));/i],[s,n,[a,c]],[/((pebble))app\/[\d\.]+\s/i],[s,n,[a,"wearable"]],[/android.+;\s(oppo)\s?([\w\s]+)\sbuild/i],[s,n,[a,c]],[/crkey/i],[[n,"Chromecast"],[s,"Google"]],[/android.+;\s(glass)\s\d/i],[n,[s,"Google"],[a,"wearable"]],[/android.+;\s(pixel c)\s/i],[n,[s,"Google"],[a,l]],[/android.+;\s(pixel xl|pixel)\s/i],[n,[s,"Google"],[a,c]],[/android.+(\w+)\s+build\/hm\1/i,/android.+(hm[\s\-_]*note?[\s_]*(?:\d\w)?)\s+build/i,/android.+(mi[\s\-_]*(?:one|one[\s_]plus|note lte)?[\s_]*(?:\d\w)?)\s+build/i,/android.+(redmi[\s\-_]*(?:note)?(?:[\s_]*[\w\s]+)?)\s+build/i],[[n,/_/g," "],[s,"Xiaomi"],[a,c]],[/android.+(mi[\s\-_]*(?:pad)?(?:[\s_]*[\w\s]+)?)\s+build/i],[[n,/_/g," "],[s,"Xiaomi"],[a,l]],[/android.+;\s(m[1-5]\snote)\sbuild/i],[n,[s,"Meizu"],[a,l]],[/android.+a000(1)\s+build/i],[n,[s,"OnePlus"],[a,c]],[/android.+[;\/]\s*(RCT[\d\w]+)\s+build/i],[n,[s,"RCA"],[a,l]],[/android.+[;\/]\s*(Venue[\d\s]*)\s+build/i],[n,[s,"Dell"],[a,l]],[/android.+[;\/]\s*(Q[T|M][\d\w]+)\s+build/i],[n,[s,"Verizon"],[a,l]],[/android.+[;\/]\s+(Barnes[&\s]+Noble\s+|BN[RT])(V?.*)\s+build/i],[[s,"Barnes & Noble"],n,[a,l]],[/android.+[;\/]\s+(TM\d{3}.*\b)\s+build/i],[n,[s,"NuVision"],[a,l]],[/android.+[;\/]\s*(zte)?.+(k\d{2})\s+build/i],[[s,"ZTE"],n,[a,l]],[/android.+[;\/]\s*(gen\d{3})\s+build.*49h/i],[n,[s,"Swiss"],[a,c]],[/android.+[;\/]\s*(zur\d{3})\s+build/i],[n,[s,"Swiss"],[a,l]],[/android.+[;\/]\s*((Zeki)?TB.*\b)\s+build/i],[n,[s,"Zeki"],[a,l]],[/(android).+[;\/]\s+([YR]\d{2}x?.*)\s+build/i,/android.+[;\/]\s+(Dragon[\-\s]+Touch\s+|DT)(.+)\s+build/i],[[s,"Dragon Touch"],n,[a,l]],[/android.+[;\/]\s*(NS-?.+)\s+build/i],[n,[s,"Insignia"],[a,l]],[/android.+[;\/]\s*((NX|Next)-?.+)\s+build/i],[n,[s,"NextBook"],[a,l]],[/android.+[;\/]\s*(Xtreme\_?)?(V(1[045]|2[015]|30|40|60|7[05]|90))\s+build/i],[[s,"Voice"],n,[a,c]],[/android.+[;\/]\s*(LVTEL\-?)?(V1[12])\s+build/i],[[s,"LvTel"],n,[a,c]],[/android.+[;\/]\s*(V(100MD|700NA|7011|917G).*\b)\s+build/i],[n,[s,"Envizen"],[a,l]],[/android.+[;\/]\s*(Le[\s\-]+Pan)[\s\-]+(.*\b)\s+build/i],[s,n,[a,l]],[/android.+[;\/]\s*(Trio[\s\-]*.*)\s+build/i],[n,[s,"MachSpeed"],[a,l]],[/android.+[;\/]\s*(Trinity)[\-\s]*(T\d{3})\s+build/i],[s,n,[a,l]],[/android.+[;\/]\s*TU_(1491)\s+build/i],[n,[s,"Rotor"],[a,l]],[/android.+(KS(.+))\s+build/i],[n,[s,"Amazon"],[a,l]],[/android.+(Gigaset)[\s\-]+(Q.+)\s+build/i],[s,n,[a,l]],[/\s(tablet|tab)[;\/]/i,/\s(mobile)(?:[;\/]|\ssafari)/i],[[a,d.lowerize],s,n],[/(android.+)[;\/].+build/i],[n,[s,"Generic"]]],engine:[[/windows.+\sedge\/([\w\.]+)/i],[u,[o,"EdgeHTML"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i,/(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i,/(icab)[\/\s]([23]\.[\d\.]+)/i],[o,u],[/rv\:([\w\.]+).*(gecko)/i],[u,o]],os:[[/microsoft\s(windows)\s(vista|xp)/i],[o,u],[/(windows)\snt\s6\.2;\s(arm)/i,/(windows\sphone(?:\sos)*)[\s\/]?([\d\.\s]+\w)*/i,/(windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i],[o,[u,f.str,h.os.windows.version]],[/(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i],[[o,"Windows"],[u,f.str,h.os.windows.version]],[/\((bb)(10);/i],[[o,"BlackBerry"],u],[/(blackberry)\w*\/?([\w\.]+)*/i,/(tizen)[\/\s]([\w\.]+)/i,/(android|webos|palm\sos|qnx|bada|rim\stablet\sos|meego|contiki)[\/\s-]?([\w\.]+)*/i,/linux;.+(sailfish);/i],[o,u],[/(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i],[[o,"Symbian"],u],[/\((series40);/i],[o],[/mozilla.+\(mobile;.+gecko.+firefox/i],[[o,"Firefox OS"],u],[/(nintendo|playstation)\s([wids34portablevu]+)/i,/(mint)[\/\s\(]?(\w+)*/i,/(mageia|vectorlinux)[;\s]/i,/(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|(?=\s)arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus)[\/\s-]?(?!chrom)([\w\.-]+)*/i,/(hurd|linux)\s?([\w\.]+)*/i,/(gnu)\s?([\w\.]+)*/i],[o,u],[/(cros)\s[\w]+\s([\w\.]+\w)/i],[[o,"Chromium OS"],u],[/(sunos)\s?([\w\.]+\d)*/i],[[o,"Solaris"],u],[/\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i],[o,u],[/(haiku)\s(\w+)/i],[o,u],[/cfnetwork\/.+darwin/i,/ip[honead]+(?:.*os\s([\w]+)\slike\smac|;\sopera)/i],[[u,/_/g,"."],[o,"iOS"]],[/(mac\sos\sx)\s?([\w\s\.]+\w)*/i,/(macintosh|mac(?=_powerpc)\s)/i],[[o,"Mac OS"],[u,/_/g,"."]],[/((?:open)?solaris)[\/\s-]?([\w\.]+)*/i,/(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i,/(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms)/i,/(unix)\s?([\w\.]+)*/i],[o,u]]},m=function(e,t){if("object"==typeof e&&(t=e,e=void 0),!(this instanceof m))return new m(e,t).getResult();var i=e||(r&&r.navigator&&r.navigator.userAgent?r.navigator.userAgent:""),n=t?d.extend(p,t):p;return this.getBrowser=function(){var e={name:void 0,version:void 0};return f.rgx.call(e,i,n.browser),e.major=d.major(e.version),e},this.getCPU=function(){var e={architecture:void 0};return f.rgx.call(e,i,n.cpu),e},this.getDevice=function(){var e={vendor:void 0,model:void 0,type:void 0};return f.rgx.call(e,i,n.device),e},this.getEngine=function(){var e={name:void 0,version:void 0};return f.rgx.call(e,i,n.engine),e},this.getOS=function(){var e={name:void 0,version:void 0};return f.rgx.call(e,i,n.os),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return i},this.setUA=function(e){return i=e,this},this};m.VERSION="0.7.17",m.BROWSER={NAME:o,MAJOR:"major",VERSION:u},m.CPU={ARCHITECTURE:"architecture"},m.DEVICE={MODEL:n,VENDOR:s,TYPE:a,CONSOLE:"console",MOBILE:c,SMARTTV:"smarttv",TABLET:l,WEARABLE:"wearable",EMBEDDED:"embedded"},m.ENGINE={NAME:o,VERSION:u},m.OS={NAME:o,VERSION:u},e.exports&&(t=e.exports=m),t.UAParser=m;var v=r&&(r.jQuery||r.Zepto);if(void 0!==v){var g=new m;v.ua=g.getResult(),v.ua.get=function(){return g.getUA()},v.ua.set=function(e){g.setUA(e);var t=g.getResult();for(var r in t)v.ua[r]=t[r]}}}("object"==typeof window?window:commonjsGlobal)}),uaParser_1=uaParser.UAParser;function genTraversalHandler(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e,t,r){e[t]=r};return function r(i,n,o){if(isArray(i)||isObject(i)){for(var a in n=isPrimitive(n)?isObject(i)?{}:[]:n,i)t(n,a,r(i[a],n[a],a));return n}return e(i,n,o)}}var _deepAssign=genTraversalHandler(function(e){return e});function deepClone(e){if(isPrimitive(e))throw new TypeError("deepClone only accept non primitive type");return _deepAssign(e)}function deepAssign(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(t.length<2)throw new Error("deepAssign accept two and more argument");for(var i=t.length-1;i>-1;i--)if(isPrimitive(t[i]))throw new TypeError("deepAssign only accept non primitive type");var n=t.shift();return t.forEach(function(e){return _deepAssign(e,n)}),n}function camelize(e,t){return e.replace(/(^|[^a-zA-Z]+)([a-zA-Z])/g,function(e,r,i,n){return t||0!==n?i.toUpperCase():i.toLowerCase()})}function hypenate(e){return camelize(e).replace(/([A-Z])/g,function(e){return"-"+e.toLowerCase()})}function bind(e,t){return e.bind?e.bind(t):e.apply?function(){for(var r=arguments.length,i=Array(r),n=0;n<r;n++)i[n]=arguments[n];return e.apply(t,i)}:function(){for(var r=arguments.length,i=Array(r),n=0;n<r;n++)i[n]=arguments[n];return e.call.apply(e,[t].concat(_toConsumableArray(i)))}}function uuid(){return S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()}function S4(){return(65536*(1+Math.random())|0).toString(16).substring(1)}function getDeepProperty(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=r.throwError,n=void 0!==i&&i,o=r.backup;if(isString(t)&&(t=t.split(".")),!isArray(t))throw new TypeError("keys of getDeepProperty must be string or Array<string>");for(var a=[],s=e,u=0,c=t.length;u<c;u++){var l=t[u];if(isVoid(s)){if(n)throw new Error("obj"+(a.length>0?"."+a.join("."):" itself")+" is "+s);return o}s=s[l],a.push(l)}return s}var inBrowser="undefined"!=typeof window&&"[object Object]"!==Object.prototype.toString.call(window);function makeArray(e){return _Array$from(e)}function transObjectAttrIntoArray(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e,t){return+e-+t};return _Object$keys(e).sort(t).reduce(function(t,r){return t.concat(e[r])},[])}function runRejectableQueue(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return new _Promise(function(t,i){!function n(o){if(!(o>=e.length)){var a=isFunction(e[o])?e[o].apply(e,_toConsumableArray(r)):e[o];return!1===a?i("stop"):_Promise.resolve(a).then(function(){return n(o+1)}).catch(function(e){return i(e||"stop")})}t()}(0)})}function runStoppableQueue(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return function t(i){return i>=e.length||!1!==(isFunction(e[i])?e[i].apply(e,_toConsumableArray(r)):e[i])&&t(++i)}(0)}var raf=inBrowser&&(window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||window.oRequestAnimationFrame)||function(e){return setTimeout(e,17)},caf=inBrowser&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame||window.webkitCancelAnimationFrame||window.webkitCancelRequestAnimationFrame||window.msCancelAnimationFrame||window.oCancelAnimationFrame)||function(e){clearTimeout(e)};function strRepeat(e,t){var r=t,i=(e=""+(e||"")).length;return(((t=(t||i)-i)>0?e.repeat?"0".repeat(t):new Array(t+1).join("0"):"")+e).slice(0,r)}function formatTime(e){var t=Math.floor(e/3600);e=Math.floor(e%3600);var r=strRepeat(Math.floor(e/60),2),i=strRepeat(e=Math.floor(e%60),2);return t>=1?t+":"+r+":"+i:r+":"+i}function formatDate(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new Date,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"yyyy-MM-dd hh:mm:ss.i",r=e.getFullYear().toString(),i={M:e.getMonth()+1,d:e.getDate(),h:e.getHours(),m:e.getMinutes(),s:e.getSeconds(),i:e.getMilliseconds()};t=t.replace(/(y+)/gi,function(e,t){return r.substr(4-Math.min(4,t.length))});var n=function(e){t=t.replace(new RegExp("("+e+"+)","g"),function(t,r){return(i[e]<10&&r.length>1?"0":"")+i[e]})};for(var o in i)n(o);return t}function getLocalStorage(e){try{return window.localStorage.getItem(e)}catch(r){try{var t=document.cookie.match(new RegExp("(^| )"+e+"=([^;]*)(;|$)"));return isArray(t)?unescape(t[2]):""}catch(e){return""}}}function setLocalStorage(e,t){try{window.localStorage.setItem(e,t)}catch(i){var r=new Date;r.setTime(r.getTime()+2592e7);try{document.cookie=e+"="+escape(t)+";expires="+r.toUTCString()+";path=/;"}catch(e){console.error(e)}}}var $assign=Object.assign,_objectAssign=!$assign||_fails(function(){var e={},t={},r=Symbol(),i="abcdefghijklmnopqrst";return e[r]=7,i.split("").forEach(function(e){t[e]=e}),7!=$assign({},e)[r]||Object.keys($assign({},t)).join("")!=i})?function(e,t){for(var r=_toObject(e),i=arguments.length,n=1,o=_objectGops.f,a=_objectPie.f;i>n;)for(var s,u=_iobject(arguments[n++]),c=o?_objectKeys(u).concat(o(u)):_objectKeys(u),l=c.length,d=0;l>d;)a.call(u,s=c[d++])&&(r[s]=u[s]);return r}:$assign;_export(_export.S+_export.F,"Object",{assign:_objectAssign});var assign=_core.Object.assign,assign$1=createCommonjsModule(function(e){e.exports={default:assign,__esModule:!0}}),_Object$assign=unwrapExports(assign$1);_export(_export.S,"Object",{create:_objectCreate});var $Object$2=_core.Object,create=function(e,t){return $Object$2.create(e,t)},create$1=createCommonjsModule(function(e){e.exports={default:create,__esModule:!0}}),_Object$create=unwrapExports(create$1),_evtListenerCache=_Object$create(null);function getEvtTypeCache(e,t){var r=e.__evt_id;r||(Object.defineProperty(e,"__evt_id",{writable:!0,enumerable:!1,configurable:!0}),r=e.__evt_id=++_evtListenerCache.count);var i=r+"_"+t,n=_evtListenerCache[i];return n||(n=_evtListenerCache[i]=[]),n}function emitEventCache(e,t,r){var i=_Object$create(null);i.type=t,i.target=e,r&&_Object$assign(i,isObject(r)?r:{data:r}),getEvtTypeCache(e,t).forEach(function(t){(t[1]||t[0]).apply(e,[i])})}function addEventCache(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments[4];isFunction(i)&&!n&&(n=i,i=void 0);var o=[r,void 0,i];i&&!n&&(n=function(){removeEventCache(e,t,r,i);for(var n=arguments.length,o=Array(n),a=0;a<n;a++)o[a]=arguments[a];r.apply(e,o)}),n&&(o[1]=n),getEvtTypeCache(e,t).push(o)}function removeEventCache(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=getEvtTypeCache(e,t);if(r||i){var o=-1,a=void 0;return n.find(function(e,t){if((!r||e[0]===r)&&(!i||e[2]))return o=t,a=e[1],!0}),-1!==o&&n.splice(o,1),a}n.length=0}_evtListenerCache.count=0;var CustEvent=function(){function e(t,r){var i=this;if(_classCallCheck(this,e),Object.defineProperty(this,"__target",{writable:!0,enumerable:!1,configurable:!0}),this.__target=this,t){if("object"!==(void 0===t?"undefined":_typeof(t)))throw new Error("CusEvent target are not object");this.__target=t,r&&["on","once","off","emit"].forEach(function(e){t[e]=i[e]})}}return _createClass(e,[{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return addEventCache(this.__target,e,t,r),this}},{key:"once",value:function(e,t){return this.on(e,t,!0)}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return removeEventCache(this.__target,e,t,r),this}},{key:"emit",value:function(e,t){return emitEventCache(this.__target,e,{data:t}),this}}]),e}(),_divEl=inBrowser?document.createElement("div"):{},_textAttrName="innerText";"textContent"in _divEl&&(_textAttrName="textContent");var _arrPrototype=Array.prototype;function getAttr(e,t){return e.getAttribute(t)}function setAttr(e,t,r){void 0===r?e.removeAttribute(t):e.setAttribute(t,r)}function addClassName(e,t){if(t&&(t=t.trim())){var r=t.split(/\s+/);if(e.classList)r.forEach(function(t){return e.classList.add(t)});else{var i=" "+(e.className||"")+" ";r.forEach(function(e){-1===i.indexOf(" "+e+" ")&&(i+=" "+e)}),e.className=i.trim()}}}function removeClassName(e,t){if(t&&(t=t.trim())){var r=t.split(/\s+/);if(e.classList)r.forEach(function(t){return e.classList.remove(t)});else{var i=" "+e.className+" ";r.forEach(function(e){for(var t=" "+e+" ";-1!==i.indexOf(t);)i=i.replace(t," ")}),e.className=i.trim()}}}function hasClassName(e,t){return new RegExp("(?:^|\\s)"+t+"(?=\\s|$)").test(e.className)}var supportsPassive=!1;try{var opts=Object.defineProperty({},"passive",{get:function(){supportsPassive=!0}});inBrowser&&window.addEventListener("test",null,opts)}catch(e){console.error(e)}function removeEvent(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments.length>4&&void 0!==arguments[4]&&arguments[4];if(void 0!==n&&!isBoolean(n)&&supportsPassive&&(n={passive:!0}),i){var o=removeEventCache(e,t+"_once",r);o&&(r=o)}e.removeEventListener(t,r,n)}function addEvent(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments.length>4&&void 0!==arguments[4]&&arguments[4];if(void 0!==n&&!isBoolean(n)&&supportsPassive&&(n={passive:!0}),i){var o=r;addEventCache(e,t+"_once",o,r=function(){for(var a=arguments.length,s=Array(a),u=0;u<a;u++)s[u]=arguments[u];o.apply(this,s),removeEvent(e,t,r,i,n)})}e.addEventListener(t,r,n)}function addDelegate(e,t,r,i){var n=arguments.length>4&&void 0!==arguments[4]&&arguments[4];void 0!==n&&!isBoolean(n)&&supportsPassive&&(n={passive:!0});var o=function(r){var n=findParents(r.target||r.srcElement,e,!0),o=query(t,e,!0),a=void 0;o.find?a=o.find(function(e){return n.find(function(t){return e===t})}):o.forEach(function(e){return!a&&n.forEach(function(t){a||e!==t||(a=t)})}),a&&i.apply(a,arguments)};addEventCache(e,r+"_delegate_"+t,i,o),e.addEventListener(r,o,n)}function removeDelegate(e,t,r,i){var n=arguments.length>4&&void 0!==arguments[4]&&arguments[4];void 0!==n&&!isBoolean(n)&&supportsPassive&&(n={passive:!0});var o=removeEventCache(e,r+"_delegate_"+t,i);o&&e.removeEventListener(r,o,n)}function getStyle(e,t){return(e.currentStyle||document.defaultView.getComputedStyle(e,null))[t]||e.style[t]}function setStyle(e,t,r){if(isObject(t))for(var i in t)setStyle(e,i,t[i]);else e.style[t]=r}function query(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document,r=arguments[2],i=t.querySelectorAll(e);return r?_Array$from(i):i}function removeEl(e){e.parentNode.removeChild(e)}function findParents(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=arguments[2],i=arguments[3],n=[];for(r&&n.push(e);e&&e.parentNode!==t;)(e=e.parentNode)&&n.push(e);return i&&n.push(t),n}var NodeWrap=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document;_classCallCheck(this,e);this.selector=t;var i=void 0;t&&t.constructor===NodeList?i=makeArray(t):isArray(t)?i=t:isString(t)?0===t.indexOf("<")?(_divEl.innerHTML=t,i=query("*",_divEl,!0)):i=query(t,r,!0):i=[t],_Object$assign(this,i),this.length=i.length}return _createClass(e,[{key:"each",value:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return _arrPrototype.forEach.apply(this,t),this}},{key:"push",value:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return _arrPrototype.push.apply(this,t),this}},{key:"splice",value:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return $(_arrPrototype.splice.apply(this,t))}},{key:"find",value:function(e){var t=[];this.each(function(r){t=t.concat(query(e,r,!0))});var r=$(t);return r.parent=this,r.selector=e,r}},{key:"append",value:function(e){var t=$(e),r=this[0];return t.each(function(e){return r.appendChild(e)}),this}},{key:"appendTo",value:function(e){return $(e).append(this),this}},{key:"text",value:function(e){return 0===arguments.length?this[0][_textAttrName]:this.each(function(t){t[_textAttrName]=e})}},{key:"html",value:function(e){return 0===arguments.length?this[0].innerHTML:this.each(function(t){t.innerHTML=e})}},{key:"attr",value:function(e,t){return 1===arguments.length?getAttr(this[0],e):this.each(function(r){return setAttr(r,e,t)})}},{key:"data",value:function(e,t){return 0===arguments.length?this[0].dataset||{}:1===arguments.length?(this[0].dataset||{})[e]:this.each(function(r){(r.dataset||(r.dataset={}))[e]=t})}},{key:"css",value:function(e,t){return 1!==arguments.length||isObject(e)?this.each(function(r){return setStyle(r,e,t)}):getStyle(this[0],e)}},{key:"addClass",value:function(e){return this.each(function(t){return addClassName(t,e)})}},{key:"removeClass",value:function(e){return this.each(function(t){return removeClassName(t,e)})}},{key:"hasClass",value:function(e){return hasClassName(this[0],e)}},{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return this.each(function(n){return addEvent(n,e,t,r,i)})}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return this.each(function(n){return removeEvent(n,e,t,r,i)})}},{key:"delegate",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return this.each(function(n){return addDelegate(n,e,t,r,i)})}},{key:"undelegate",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return this.each(function(n){return removeDelegate(n,e,t,r,i)})}},{key:"remove",value:function(){return this.each(function(e){return removeEl(e)})}}]),e}();function $(e,t){return e.constructor===NodeWrap?e:new NodeWrap(e,t)}var Reflect=_global.Reflect,_ownKeys=Reflect&&Reflect.ownKeys||function(e){var t=_objectGopn.f(_anObject(e)),r=_objectGops.f;return r?t.concat(r(e)):t};_export(_export.S,"Object",{getOwnPropertyDescriptors:function(e){for(var t,r,i=_toIobject(e),n=_objectGopd.f,o=_ownKeys(i),a={},s=0;o.length>s;)void 0!==(r=n(i,t=o[s++]))&&_createProperty(a,t,r);return a}});var getOwnPropertyDescriptors=_core.Object.getOwnPropertyDescriptors,getOwnPropertyDescriptors$1=createCommonjsModule(function(e){e.exports={default:getOwnPropertyDescriptors,__esModule:!0}}),_Object$getOwnPropertyDescriptors=unwrapExports(getOwnPropertyDescriptors$1),getOwnPropertySymbols=_core.Object.getOwnPropertySymbols,getOwnPropertySymbols$1=createCommonjsModule(function(e){e.exports={default:getOwnPropertySymbols,__esModule:!0}}),_Object$getOwnPropertySymbols=unwrapExports(getOwnPropertySymbols$1);_objectSap("getOwnPropertyNames",function(){return _objectGopnExt.f});var $Object$3=_core.Object,getOwnPropertyNames=function(e){return $Object$3.getOwnPropertyNames(e)},getOwnPropertyNames$1=createCommonjsModule(function(e){e.exports={default:getOwnPropertyNames,__esModule:!0}}),_Object$getOwnPropertyNames=unwrapExports(getOwnPropertyNames$1);function bind$1(e,t){return e.bind?e.bind(t):e.apply?function(){for(var r=arguments.length,i=Array(r),n=0;n<r;n++)i[n]=arguments[n];return e.apply(t,i)}:function(){for(var r=arguments.length,i=Array(r),n=0;n<r;n++)i[n]=arguments[n];return e.call.apply(e,[t].concat(_toConsumableArray(i)))}}function getDeepProperty$1(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=r.throwError,n=void 0!==i&&i,o=r.backup;if(isString(t)&&(t=t.split(".")),!isArray(t))throw new TypeError("keys of getDeepProperty must be string or Array<string>");for(var a=[],s=e,u=0,c=t.length;u<c;u++){var l=t[u];if(isVoid(s)){if(n)throw new Error("obj"+(a.length>0?"."+a.join("."):" itself")+" is "+s);return o}s=s[l],a.push(l)}return s}var ITERATOR$4=_wks("iterator"),core_isIterable=_core.isIterable=function(e){var t=Object(e);return void 0!==t[ITERATOR$4]||"@@iterator"in t||_iterators.hasOwnProperty(_classof(t))},isIterable=core_isIterable,isIterable$1=createCommonjsModule(function(e){e.exports={default:isIterable,__esModule:!0}});unwrapExports(isIterable$1);var core_getIterator=_core.getIterator=function(e){var t=core_getIteratorMethod(e);if("function"!=typeof t)throw TypeError(e+" is not iterable!");return _anObject(t.call(e))},getIterator=core_getIterator,getIterator$1=createCommonjsModule(function(e){e.exports={default:getIterator,__esModule:!0}});unwrapExports(getIterator$1);var slicedToArray=createCommonjsModule(function(e,t){t.__esModule=!0;var r=n(isIterable$1),i=n(getIterator$1);function n(e){return e&&e.__esModule?e:{default:e}}t.default=function(){return function(e,t){if(Array.isArray(e))return e;if((0,r.default)(Object(e)))return function(e,t){var r=[],n=!0,o=!1,a=void 0;try{for(var s,u=(0,i.default)(e);!(n=(s=u.next()).done)&&(r.push(s.value),!t||r.length!==t);n=!0);}catch(e){o=!0,a=e}finally{try{!n&&u.return&&u.return()}finally{if(o)throw a}}return r}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}()}),_slicedToArray=unwrapExports(slicedToArray);_objectSap("getPrototypeOf",function(){return function(e){return _objectGpo(_toObject(e))}});var getPrototypeOf=_core.Object.getPrototypeOf,getPrototypeOf$1=createCommonjsModule(function(e){e.exports={default:getPrototypeOf,__esModule:!0}}),_Object$getPrototypeOf=unwrapExports(getPrototypeOf$1),getWeak=_meta.getWeak,arrayFind=_arrayMethods(5),arrayFindIndex=_arrayMethods(6),id$1=0,uncaughtFrozenStore=function(e){return e._l||(e._l=new UncaughtFrozenStore)},UncaughtFrozenStore=function(){this.a=[]},findUncaughtFrozen=function(e,t){return arrayFind(e.a,function(e){return e[0]===t})};UncaughtFrozenStore.prototype={get:function(e){var t=findUncaughtFrozen(this,e);if(t)return t[1]},has:function(e){return!!findUncaughtFrozen(this,e)},set:function(e,t){var r=findUncaughtFrozen(this,e);r?r[1]=t:this.a.push([e,t])},delete:function(e){var t=arrayFindIndex(this.a,function(t){return t[0]===e});return~t&&this.a.splice(t,1),!!~t}};var _collectionWeak={getConstructor:function(e,t,r,i){var n=e(function(e,o){_anInstance(e,n,t,"_i"),e._t=t,e._i=id$1++,e._l=void 0,void 0!=o&&_forOf(o,r,e[i],e)});return _redefineAll(n.prototype,{delete:function(e){if(!_isObject(e))return!1;var r=getWeak(e);return!0===r?uncaughtFrozenStore(_validateCollection(this,t)).delete(e):r&&_has(r,this._i)&&delete r[this._i]},has:function(e){if(!_isObject(e))return!1;var r=getWeak(e);return!0===r?uncaughtFrozenStore(_validateCollection(this,t)).has(e):r&&_has(r,this._i)}}),n},def:function(e,t,r){var i=getWeak(_anObject(t),!0);return!0===i?uncaughtFrozenStore(e).set(t,r):i[e._i]=r,e},ufstore:uncaughtFrozenStore},es6_weakMap=createCommonjsModule(function(e){var t,r=_arrayMethods(0),i=_meta.getWeak,n=Object.isExtensible,o=_collectionWeak.ufstore,a={},s=function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},u={get:function(e){if(_isObject(e)){var t=i(e);return!0===t?o(_validateCollection(this,"WeakMap")).get(e):t?t[this._i]:void 0}},set:function(e,t){return _collectionWeak.def(_validateCollection(this,"WeakMap"),e,t)}},c=e.exports=_collection("WeakMap",s,u,_collectionWeak,!0,!0);_fails(function(){return 7!=(new c).set((Object.freeze||Object)(a),7).get(a)})&&(t=_collectionWeak.getConstructor(s,"WeakMap"),_objectAssign(t.prototype,u),_meta.NEED=!0,r(["delete","has","get","set"],function(e){var r=c.prototype,i=r[e];_redefine(r,e,function(r,o){if(_isObject(r)&&!n(r)){this._f||(this._f=new t);var a=this._f[e](r,o);return"set"==e?this:a}return i.call(this,r,o)})}))});_setCollectionOf("WeakMap"),_setCollectionFrom("WeakMap");var weakMap=_core.WeakMap,weakMap$1=createCommonjsModule(function(e){e.exports={default:weakMap,__esModule:!0}}),_WeakMap=unwrapExports(weakMap$1),defineProperty$3=createCommonjsModule(function(e,t){t.__esModule=!0;var r,i=(r=defineProperty$1)&&r.__esModule?r:{default:r};t.default=function(e,t,r){return t in e?(0,i.default)(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}}),_defineProperty=unwrapExports(defineProperty$3),meta=_meta.onFreeze;_objectSap("preventExtensions",function(e){return function(t){return e&&_isObject(t)?e(meta(t)):t}});var preventExtensions=_core.Object.preventExtensions,preventExtensions$1=createCommonjsModule(function(e){e.exports={default:preventExtensions,__esModule:!0}});unwrapExports(preventExtensions$1);var getOwnPropertyDescriptor$2=_Object$getOwnPropertyDescriptor;function isDescriptor(e){if(!e||!e.hasOwnProperty)return!1;for(var t=["value","initializer","get","set"],r=0,i=t.length;r<i;r++)if(e.hasOwnProperty(t[r]))return!0;return!1}function isAccessorDescriptor(e){return!!e&&(isFunction(e.get)||isFunction(e.set))&&isBoolean(e.configurable)&&isBoolean(e.enumerable)&&void 0===e.writable}function isDataDescriptor(e){return!!e&&e.hasOwnProperty("value")&&isBoolean(e.configurable)&&isBoolean(e.enumerable)&&isBoolean(e.writable)}function isInitializerDescriptor(e){return!!e&&isFunction(e.initializer)&&isBoolean(e.configurable)&&isBoolean(e.enumerable)&&isBoolean(e.writable)}function createDefaultSetter(e){return function(t){return _Object$defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t}),t}}function compressOneArgFnArray(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"You must pass me an array of function";if(!isArray(e)||e.length<1)throw new TypeError(t);if(1===e.length){if(!isFunction(e[0]))throw new TypeError(t);return e[0]}return e.reduce(function(e,r){if(!isFunction(r)||!isFunction(e))throw new TypeError(t);return function(t){return bind$1(r,this)(bind$1(e,this)(t))}})}function getOwnKeysFn(){var e=_Object$getOwnPropertyNames,t=_Object$getOwnPropertySymbols;return isFunction(t)?function(r){return _Array$from(e(r).concat(t(r)))}:e}var getOwnKeys=getOwnKeysFn();function getOwnPropertyDescriptorsFn(){return isFunction(_Object$getOwnPropertyDescriptors)?_Object$getOwnPropertyDescriptors:function(e){return getOwnKeys(e).reduce(function(t,r){return t[r]=getOwnPropertyDescriptor$2(e,r),t},{})}}var getOwnPropertyDescriptors$2=getOwnPropertyDescriptorsFn();function compressMultipleDecorators(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(!t.length)throw new TypeError("You must pass in decorators in compressMultipleDecorators");return t.forEach(function(e){if(!isFunction(e))throw new TypeError('Decorators must be a function, but not "'+e+'" in '+(void 0===e?"undefined":_typeof(e)))}),1===t.length?t[0]:function(e,r,i){return t.reduce(function(t,i){return i(e,r,t)},i)}}function accessor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.get,r=e.set,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=i.preGet,o=void 0!==n&&n,a=i.preSet,s=void 0===a||a;if(!(isFunction(t)||isFunction(r)||isArray(t)&&t.length>0||isArray(r)&&r.length>0))throw new TypeError("@accessor need a getter or setter. If you don't need to add setter/getter. You should remove @accessor");var u="@accessor only accept function or array of function as getter/setter";return t=isArray(t)?compressOneArgFnArray(t,u):t,r=isArray(r)?compressOneArgFnArray(r,u):r,function(e,i,n){var a=n||{},u=a.configurable,c=void 0===u||u,l=a.enumerable,d=void 0===l||l,f=isFunction(t),h=isFunction(r),p=function(e){return f?bind$1(t,this)(e):e},m=function(e){return h?bind$1(r,this)(e):e};if(isAccessorDescriptor(n)){var v=n.get,g=n.set,y=isFunction(v),_=isFunction(g);return{get:y||f?function(){var e=this,t=bind$1(p,this),r=function(){return y?bind$1(v,e)():void 0};return(o?[t,r]:[r,t]).reduce(function(e,t){return t(e)},void 0)}:void 0,set:_||h?function(e){var t=this,r=bind$1(m,this),i=function(e){return _?bind$1(g,t)(e):e};return(s?[r,i]:[i,r]).reduce(function(e,t){return t(e)},e)}:void 0,configurable:c,enumerable:d}}if(isInitializerDescriptor(n)){var b=n.initializer,w=void 0,E=!1;return{get:function(){var e=bind$1(p,this);return E?e(w):(w=bind$1(b,this)(),E=!0,e(w))},set:function(e){var t=bind$1(m,this);return w=s?t(e):e,E=!0,s||t(w),w},configurable:c,enumerable:d}}var S=(n||{}).value;return{get:function(){return bind$1(p,this)(S)},set:function(e){var t=bind$1(m,this);return S=s?t(e):e,s||t(S),S},configurable:c,enumerable:d}}}function before(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(0===t.length)throw new Error("@before accept at least one parameter. If you don't need to preprocess before your function, do not add @before decorators");if(t.length>2&&isDescriptor(t[2]))throw new Error("You may use @before straightly, @before return decorators, you should call it before you set it as decorator.");for(var i=t.length-1;i>-1;i--)if(!isFunction(t[i]))throw new TypeError("@before only accept function parameter");return function(e,r,i){var n=i||{},o=n.value,a=n.configurable,s=n.enumerable,u=n.writable;if(!isFunction(o))throw new TypeError('@before can only be used on function, please check the property "'+r+'" is a method or not.');return{value:function(){for(var e=this,r=arguments.length,i=Array(r),n=0;n<r;n++)i[n]=arguments[n];var a=t.reduce(function(t,r){var i=bind$1(r,e).apply(void 0,_toConsumableArray(t));return void 0===i?t:isArray(i)?i:[i]},i);return bind$1(o,this).apply(void 0,_toConsumableArray(a))},configurable:a,enumerable:s,writable:u}}}function after(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(0===t.length)throw new Error("@after accept at least one parameter. If you don't need to preprocess after your function, do not add @after decorators");if(t.length>2&&isDescriptor(t[2]))throw new Error("You may have used @after straightly. @after return decorators. You should call it before you use it as decorators");var i=compressOneArgFnArray(t,"@after only accept function parameter");return function(e,t,r){var n=r||{},o=n.value,a=n.configurable,s=n.enumerable,u=n.writable;if(!isFunction(o))throw new TypeError('@after can only be used on function, please checkout your property "'+t+'" is a method or not.');return{value:function(){var e=bind$1(o,this).apply(void 0,arguments);return bind$1(i,this)(e)},configurable:a,enumerable:s,writable:u}}}function initialize(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(0===t.length)throw new Error("@initialize accept at least one parameter. If you don't need to initialize your value, do not add @initialize.");if(t.length>2&&isDescriptor(t[2]))throw new Error("You may use @initialize straightly, @initialize return decorators, you need to call it");var i=compressOneArgFnArray(t,"@initialize only accept function parameter");return function(e,t,r){if(void 0===r)return{value:bind$1(i,e)(),configurable:!0,writable:!0,enumerable:!0};if(isAccessorDescriptor(r)){var n=!1;return accessor({get:function(e){return n?e:bind$1(i,this)(e)},set:r.set?function(e){return n=!0,e}:void 0})(e,t,r)}if(isInitializerDescriptor(r)){var o=r.initializer;return{initializer:function(){return bind$1(i,this)(bind$1(o,this)())},configurable:r.configurable,writable:r.writable,enumerable:r.enumerable}}return{value:bind$1(i,this)(r.value),writable:r.writable,configurable:r.configurable,enumerable:r.enumerable}}}var getOwnPropertyDescriptor$1$1=_Object$getOwnPropertyDescriptor,defineProperty$4=_Object$defineProperty;function setAlias(e,t,r,i,n,o){var a=r.configurable,s=r.enumerable,u=o.force,c=o.omit,l=getOwnPropertyDescriptor$1$1(i,n);if(void 0!==l){if(c)return;if(!u)throw new Error('"'+t+'" is an existing property, if you want to override it, please set "force" true in @alias option.');if(!l.configurable)throw new Error('property "'+t+'" is unconfigurable.')}defineProperty$4(i,n,{get:function(){return e[t]},set:function(r){return e[t]=r,t},configurable:a,enumerable:s})}function alias(e,t,r){if(2===arguments.length?isString(e)&&(r=t,t=e,e=void 0):1===arguments.length&&(t=e,e=void 0),!isString(t))throw new TypeError("@alias need a string as a key to find the porperty to set alias on");var i="If you want to use @alias to set alias on other instance, you must pass in a legal instance";if(void 0!==e&&isPrimitive(e))throw new TypeError(i);var n=isObject(r)?r:{force:!1,omit:!1},o=n.force,a=n.omit;return function(r,n,s){function u(e,t,r){var n=isPrimitive(e)?t:e,o=r.split("."),a=o.slice(-1),s=_slicedToArray(a,1)[0];if(isPrimitive(n=getDeepProperty$1(n,o.slice(0,-1),{throwError:!0})))throw new TypeError(i);return{target:n,name:s}}if(isInitializerDescriptor(s=s||{value:void 0,configurable:!0,writable:!0,enumerable:!0}))return initialize(function(r){var i=u(e,this,t),c=i.target,l=i.name;return setAlias(this,n,s,c,l,{force:o,omit:a}),r})(r,n,s);if(isAccessorDescriptor(s)){var c=void 0,l=function(r){if(c)return r;var i=u(e,this,t),l=i.target,d=i.name;return setAlias(this,n,s,l,d,{force:o,omit:a}),c=!0,r};return accessor({get:l,set:l})(r,n,s)}var d=u(e,r,t),f=d.target,h=d.name;return setAlias(r,n,s,f,h,{force:o,omit:a}),s}}var defineProperty$1$1=_Object$defineProperty;function classify(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.requirement,i=t.customArgs,n=void 0!==i&&i;return function(){for(var t=arguments.length,i=Array(t>1?t-1:0),o=1;o<t;o++)i[o-1]=arguments[o];var a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},s=a.exclude,u=void 0===s?[]:s,c=a.include,l=void 0===c?[]:c,d=a.construct,f=void 0!==d&&d,h=a.self,p=void 0!==h&&h;if(!isArray(u))throw new TypeError("options.exclude must be an array");if(!isArray(l))throw new TypeError("options.include must be an array");return function(t){var o=isFunction(t);if(!p&&!o)throw new TypeError("@"+e.name+"Class can only be used on class");if(p&&isPrimitive(t))throw new TypeError("@"+e.name+"Class must be used on non-primitive type value in 'self' mode");var a=p?t:t.prototype;if(isVoid(a))throw new Error("The prototype of the "+t.name+" is empty, please check it");var s=getOwnPropertyDescriptors$2(a);getOwnKeys(a).concat(l).forEach(function(t){var c=s[t];"constructor"===t&&!f||p&&o&&["name","length","prototype"].indexOf(t)>-1||u.indexOf(t)>-1||isFunction(r)&&!1===r(a,t,c,{self:p})||defineProperty$1$1(a,t,(n?e.apply(void 0,_toConsumableArray(i)):e)(a,t,c))})}}}var autobindClass=classify(autobind,{requirement:function(e,t,r){return isDataDescriptor(r)&&isFunction(r.value)}}),mapStore=void 0;function getBoundSuper(e,t){if(void 0===_WeakMap)throw new Error("Using @autobind on "+t.name+"() requires WeakMap support due to its use of super."+t.name+"()");mapStore||(mapStore=new _WeakMap),!1===mapStore.has(e)&&mapStore.set(e,new _WeakMap);var r=mapStore.get(e);return!1===r.has(t)&&r.set(t,bind$1(t,e)),r.get(t)}function autobind(e,t,r){if(1===arguments.length)return autobindClass()(e);var i=r||{},n=i.value,o=i.configurable;if(!isFunction(n))throw new TypeError('@autobind can only be used on functions, not "'+n+'" in '+(void 0===n?"undefined":_typeof(n))+' on property "'+t+'"');var a=e.constructor;return{configurable:o,enumerable:!1,get:function(){var r=this,i=function(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];return n.call.apply(n,[r].concat(_toConsumableArray(t)))};return this===e?n:this.constructor!==a&&_Object$getPrototypeOf(this).constructor===a?n:this.constructor!==a&&t in this.constructor.prototype?getBoundSuper(this,n):(_Object$defineProperty(this,t,{configurable:!0,writable:!0,enumerable:!1,value:i}),i)},set:createDefaultSetter(t)}}var defineProperty$2$1=_Object$defineProperty;function frozen(e,t,r){if(void 0===r)return{value:void 0,writable:!1,enumerable:!1,configurable:!1};if(r.enumerable=!1,r.configurable=!1,isAccessorDescriptor(r)){var i=r.get;if(r.set=void 0,!isFunction(i))return;return{get:function(){var e=bind$1(i,this)();return defineProperty$2$1(this,t,{value:e,writable:!1,configurable:!1,enumerable:!1}),e},set:void 0,configurable:!1,enumerable:!1}}return r.writable=!1,r}var getOwnPropertyDescriptor$2$1=_Object$getOwnPropertyDescriptor,defineProperty$3$1=_Object$defineProperty;function waituntil(e){var t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).other;if(!isFunction(e)&&!isPromise(e)&&!isString(e))throw new TypeError("@waitUntil only accept Function, Promise or String");return function(r,i,n){var o=n||{},a=o.value,s=o.configurable;if(!isFunction(a))throw new TypeError("@waituntil can only be used on function, but not "+a+' on property "'+i+'"');var u=!1,c=[],l=isPromise(e)?function(){return e}:isFunction(e)?e:function(){var r=e.split("."),i=r.slice(-1),n=isPrimitive(t)?this:t;if(!u){var o=getDeepProperty$1(n,r.slice(0,-1));if(isVoid(o))return o;var a=getOwnPropertyDescriptor$2$1(o,i),s=function(e){if(!0===e)for(;c.length>0;)c[0](),c.shift();return e},l=isDescriptor(a)?accessor({set:s})(o,i,a):accessor({set:s})(o,i,{value:void 0,configurable:!0,enumerable:!0,writable:!0});defineProperty$3$1(o,i,l),u=!0}return getDeepProperty$1(n,r)};return{value:function(){for(var e=this,t=arguments.length,r=Array(t),i=0;i<t;i++)r[i]=arguments[i];var n=bind$1(a,this),o=bind$1(l,this).apply(void 0,r);return isPromise(o)?_Promise.resolve(o).then(function(){return bind$1(a,e).apply(void 0,r)}):!0===o?bind$1(a,this).apply(void 0,r):new _Promise(function(e){c.push(function(){n.apply(void 0,r),e()})})},enumerable:!1,configurable:s,writable:!1}}}function nonenumerable(e,t,r){return void 0===r?{value:void 0,enumerable:!1,configurable:!0,writable:!0}:(r.enumerable=!1,r)}var defineProperty$6=_Object$defineProperty,getOwnPropertyDescriptor$3=_Object$getOwnPropertyDescriptor;function applyDecorators(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=r.self,n=void 0!==i&&i,o=r.omit,a=void 0!==o&&o,s=isFunction(t);if(s||isArray(t)){if(!isFunction(e))throw new TypeError("If you want to decorator class, you must pass it a legal class");if(s)t(e);else for(var u=0,c=t.length;u<c;u++){var l=t[u];if(!isFunction(l))throw new TypeError("If you want to decorate an class, you must pass it function or array of function");l(e)}return e}if(!n&&!isFunction(e))throw new TypeError("applyDecorators only accept class as first arguments. If you want to modify instance, you should set options.self true.");if(n&&isPrimitive(e))throw new TypeError("We can't apply docorators on a primitive value, even in self mode");if(!isObject(t))throw new TypeError("applyDecorators only accept object as second arguments");var d=n?e:e.prototype;if(isVoid(d))throw new Error("The class muse have a prototype, please take a check");for(var f in t){var h=t[f],p=isArray(h)?h:[h],m=void 0;try{m=compressMultipleDecorators.apply(void 0,_toConsumableArray(p))}catch(e){throw new Error("The decorators set on props must be Function or Array of Function")}var v=getOwnPropertyDescriptor$3(d,f);if(!v||v.configurable)defineProperty$6(d,f,m(d,f,v));else if(!a)throw new Error(f+" of "+d+" is unconfigurable")}return e}var arrayChangeMethod=["push","pop","unshift","shift","splice","sort","reverse"];function deepProxy(e,t,r){var i,n=r.diff,o=r.operationPrefix,a={},s=!1,u=new Proxy(e,{get:function(e,r,i){var u=e[r];if(isArray(e)&&arrayChangeMethod.indexOf(r)>-1)return function(){s=!0,bind$1(u,i).apply(void 0,arguments),s=!1,t()};if(!0===a[r])return u;if(isObject(u)||isArray(u)){var c=a[r]||deepProxy(u,t,{diff:n,operationPrefix:o});return a[r]=c,c}return a[r]=!0,u},set:function(e,r,i){var u=e[r],c=isObject(i)||isArray(i)?deepProxy(i,t,{diff:n,operationPrefix:o}):i;return e[r]=c,a[r]=!0,!!(s||n&&u===c)||(t(),!0)},deleteProperty:function(e,r){return delete e[r],delete a[r],!!s||(t(),!0)}}),c=(_defineProperty(i={},o+"set",[initialize(function(e){return function(e,t){u[e]=t}}),nonenumerable]),_defineProperty(i,o+"del",[initialize(function(e){return function(e){delete u[e]}}),nonenumerable]),i);return applyDecorators(u,c,{self:!0}),u}function deepObserve(e,t,r){var i,n=this,o=r.operationPrefix,a=r.diff,s={},u=!1;function c(e){var r=void 0;return e.reduce(function(e,i){return e[i]=[accessor({set:function(e){return r=this[i],e}}),accessor({get:function(e){return s[i]?e:((isObject(e)||isArray(e))&&deepObserve(e,t,{operationPrefix:o,diff:a}),s[i]=!0,e)},set:function(e){return(isObject(e)||isArray(e))&&deepObserve(e,t,{operationPrefix:o,diff:a}),s[i]=!0,u||a&&r===e||t(),e}},{preSet:!1})],e},{})}var l=c(getOwnKeys(e));if(applyDecorators(e,l,{self:!0,omit:!0}),isArray(e)){var d=arrayChangeMethod.reduce(function(r,i){return r[i]=[initialize(function(r){return r=isFunction(r)?r:Array.prototype[i],function(){var i=e.length;if(u=!0,bind$1(r,e).apply(void 0,arguments),u=!1,i<e.length){var n=c(new Array(e.length-i).fill(1).map(function(e,t){return(t+i).toString()}));applyDecorators(e,n,{self:!0,omit:!0})}t()}}),nonenumerable],r},{});applyDecorators(e,d,{self:!0})}var f=(_defineProperty(i={},o+"set",[initialize(function(t){return function(r,i){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=o.disable,s=o.isNewVal;if(s=s||-1===getOwnKeys(e).indexOf(r),isFunction(t)&&bind$1(t,n)(r,i,{disable:!0,isNewVal:s}),s){var u=c([r]);applyDecorators(e,u,{self:!0,omit:!0})}a||(e[r]=i)}}),nonenumerable]),_defineProperty(i,o+"del",[initialize(function(r){return function(i){isFunction(r)?bind$1(r,n)(i):delete e[i],t()}}),nonenumerable]),i);return applyDecorators(e,f,{self:!0}),e}function watch(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var i=isObject(t[t.length-1])?t[t.length-1]:{},n=i.deep,o=i.omit,a=i.other,s=i.operationPrefix,u=void 0===s?"__":s,c=i.diff,l=void 0===c||c,d=i.proxy;if("function"!=typeof Proxy&&(d=!1),!t.length)throw new TypeError("You must pass a function or a string to find the hanlder function.");if(void 0!==a&&isPrimitive(a))throw new TypeError("If you want us to trigger function on the other instance, you must pass in a legal instance");if(!isString(u))throw new TypeError("operationPrefix must be an string");return function(e,r,i){var s=t.reduce(function(r,i,n){if(!isString(i)&&!isFunction(i)){if(!n||n!==t.length-1)throw new TypeError("You can only pass function or string as handler");return r}return r.push(isString(i)?function(t,r){var n=getDeepProperty$1(a||e,i);if(isFunction(n))return bind$1(n,this)(t,r);if(!o)throw new Error("You pass in a function for us to trigger, please ensure the property to be a function or set omit flag true")}:i),r},[]),c=function(e,t){var r=this;s.forEach(function(i){return bind$1(i,r)(e,t)})},f=!1,h=void 0,p=void 0,m=void 0;return compressMultipleDecorators(accessor({set:function(e){var t=this;h=this[r],m=void 0;var i=function(){return bind$1(c,t)(p,h)};return n&&(isObject(e)||isArray(e))?d?deepProxy(e,i,{diff:l,operationPrefix:u}):deepObserve(e,i,{operationPrefix:u,diff:l}):e},get:function(e){var t=this;if(m)return m;if(!f){f=!0;var r=function(){return bind$1(c,t)(p,h)};if(n&&(isObject(e)||isArray(e))){if(d)return m=deepProxy(e,r,{diff:l,operationPrefix:u}),h=m,p=m,m;deepObserve(e,r,{operationPrefix:u,diff:l})}h=e,p=e}return e}},{preSet:!0}),accessor({set:function(e){return p=e,l&&h===e||bind$1(c,this)(p,h),h=e,e}},{preSet:!1}))(e,r,i)}}function runnable(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.other,i=t.backup;if(!isFunction(e)&&!isString(e))throw new TypeError("@runnable only accept Function or String");return function(t,n,o){var a=o||{},s=a.value,u=a.configurable;if(!isFunction(s))throw new TypeError("@runnable can only be used on method, but not "+s+' on property "'+n+'".');var c=isFunction(e)?e:function(){var t=e.split(".");return getDeepProperty$1(isPrimitive(r)?this:r,t)};return i=isFunction(i)?i:function(){},{value:function(){return!0===bind$1(c,this).apply(void 0,arguments)?bind$1(s,this).apply(void 0,arguments):bind$1(i,this).apply(void 0,arguments)},enumerable:!1,configurable:u,writable:!1}}}function nonconfigurable(e,t,r){return void 0===r?{value:void 0,enumerable:!0,configurable:!0,writable:!0}:(r.configurable=!0,r)}function string(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var i=isString(t[0])?t.shift():"";return t.unshift(function(e){return isString(e)?e:i}),initialize.apply(void 0,t)}function boolean(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var i=!!isBoolean(t[0])&&t.shift();return t.unshift(function(e){return isBoolean(e)?e:i}),initialize.apply(void 0,t)}function string$1(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var i=isString(t[0])?t.shift():"";return t.unshift(function(e){return isString(e)?e:i}),accessor({set:t,get:t})}function boolean$1(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var i=!!isBoolean(t[0])&&t.shift();return t.unshift(function(e){return isBoolean(e)?e:i}),accessor({set:t,get:t})}function number$1(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var i=isNumber(t[0])?t.shift():0;return t.unshift(function(e){return isNumber(e)?e:i}),accessor({set:t,get:t})}var before$1=classify(before,{requirement:function(e,t,r){return isDataDescriptor(r)&&isFunction(r.value)},customArgs:!0}),after$1=classify(after,{requirement:function(e,t,r){return isDataDescriptor(r)&&isFunction(r.value)},customArgs:!0}),runnable$1=classify(runnable,{requirement:function(e,t,r){return isDataDescriptor(r)&&isFunction(r.value)},customArgs:!0}),waituntil$1=classify(waituntil,{requirement:function(e,t,r){return isDataDescriptor(r)&&isFunction(r.value)},customArgs:!0});_export(_export.S,"Number",{isNaN:function(e){return e!=e}});var isNan=_core.Number.isNaN,isNan$1=createCommonjsModule(function(e){e.exports={default:isNan,__esModule:!0}}),_Number$isNaN=unwrapExports(isNan$1),$JSON$1=_core.JSON||(_core.JSON={stringify:JSON.stringify}),stringify=function(e){return $JSON$1.stringify.apply($JSON$1,arguments)},stringify$1=createCommonjsModule(function(e){e.exports={default:stringify,__esModule:!0}}),_JSON$stringify=unwrapExports(stringify$1),possibleConstructorReturn=createCommonjsModule(function(e,t){t.__esModule=!0;var r,i=(r=_typeof_1)&&r.__esModule?r:{default:r};t.default=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==(void 0===t?"undefined":(0,i.default)(t))&&"function"!=typeof t?e:t}}),_possibleConstructorReturn=unwrapExports(possibleConstructorReturn),get=createCommonjsModule(function(e,t){t.__esModule=!0;var r=n(getPrototypeOf$1),i=n(getOwnPropertyDescriptor$1);function n(e){return e&&e.__esModule?e:{default:e}}t.default=function e(t,n,o){null===t&&(t=Function.prototype);var a=(0,i.default)(t,n);if(void 0===a){var s=(0,r.default)(t);return null===s?void 0:e(s,n,o)}if("value"in a)return a.value;var u=a.get;return void 0!==u?u.call(o):void 0}}),_get=unwrapExports(get),check=function(e,t){if(_anObject(e),!_isObject(t)&&null!==t)throw TypeError(t+": can't set as prototype!")},_setProto={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,r){try{(r=_ctx(Function.call,_objectGopd.f(Object.prototype,"__proto__").set,2))(e,[]),t=!(e instanceof Array)}catch(e){t=!0}return function(e,i){return check(e,i),t?e.__proto__=i:r(e,i),e}}({},!1):void 0),check:check};_export(_export.S,"Object",{setPrototypeOf:_setProto.set});var setPrototypeOf=_core.Object.setPrototypeOf,setPrototypeOf$1=createCommonjsModule(function(e){e.exports={default:setPrototypeOf,__esModule:!0}});unwrapExports(setPrototypeOf$1);var inherits=createCommonjsModule(function(e,t){t.__esModule=!0;var r=o(setPrototypeOf$1),i=o(create$1),n=o(_typeof_1);function o(e){return e&&e.__esModule?e:{default:e}}t.default=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":(0,n.default)(t)));e.prototype=(0,i.default)(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(r.default?(0,r.default)(e,t):e.__proto__=t)}}),_inherits=unwrapExports(inherits),VENDOR_PREFIXES=["","o","ms","moz","webkit","webkitCurrent"],SYNONYMS=[["",""],["exit","cancel"],["screen","Screen"]],DESKTOP_FULLSCREEN_STYLE={position:"fixed",zIndex:"2147483647",left:0,top:0,right:0,bottom:0,overflow:"hidden",width:"100%",height:"100%"},FULLSCREEN_CHANGE=["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],FULLSCREEN_ERROR=["fullscreenerror","webkitfullscreenerror","mozfullscreenerror","MSFullscreenError"],supportDocument="undefined"!=typeof document,_dec,_dec2,_dec3,_dec4,_dec5,_class,_class2;function setStyle$1(e,t,r){if(isObject(t))for(var i in t)setStyle$1(e,i,t[i]);else e.style[t]=r}function native(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};isObject(t)&&(r=t),isString(e)&&(t=e);var i=r.keyOnly,n=void 0!==i&&i;if(!supportDocument)return n?"":void 0;if(isElement(e)||(e=document),!isString(t))throw new Error("You must pass in a string as name, but not "+(void 0===t?"undefined":_typeof(t))+".");for(var o=0;o<SYNONYMS.length;o++){t=t.replace(SYNONYMS[o][0],SYNONYMS[o][1]);for(var a=0;a<VENDOR_PREFIXES.length;a++){var s=0===a?t:VENDOR_PREFIXES[a]+t.charAt(0).toUpperCase()+t.substr(1);if(void 0!==e[s])return n?s:e[s]}}return n?"":void 0}function dispatchEvent(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=r.bubbles,n=void 0===i||i,o=r.cancelable,a=void 0===o||o,s=void 0;if(isFunction(Event)?s=new Event(t,{bubbles:n,cancelable:a}):supportDocument&&document.createEvent?(s=document.createEvent("HTMLEvents")).initEvent(t,!0,!0):supportDocument&&document.createEventObject&&((s=document.createEventObject()).eventType=t,s.eventName=t),!isObject(s)&&!isEvent(s))throw new Error("We can't create an object on this browser, please report to author");e.dispatchEvent?e.dispatchEvent(s):e.fireEvent?e.fireEvent("on"+s.eventType,s):e[t]?e[t]():e["on"+t]&&e["on"+t]()}function _applyDecoratedDescriptor(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var fullscreenEnabled=native("fullscreenEnabled"),useStyleFirst=!1,ESFullScreen=(_dec=autobindClass(),_dec2=alias("requestFullscreen"),_dec3=alias("exitFullscreen"),_dec4=alias("addEventListener"),_dec5=alias("removeEventListener"),_dec((_class2=function(){function e(){_classCallCheck(this,e),this._fullscreenElement=null,this.isNativelySupport=defined(native("fullscreenElement"))&&(!defined(fullscreenEnabled)||!0===fullscreenEnabled),this._openKey=supportDocument?native(document.body||document.documentElement,"requestFullscreen",{keyOnly:!0}):"",this._exitKey=native("exitFullscreen",{keyOnly:!0}),this._useStyleFirst=!1,this.hasUsedStyle=!1}return _createClass(e,[{key:"open",value:function(e){var t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).force,r=void 0!==t&&t,i=this.fullscreenElement;if(i&&i!==e){if(!r)return dispatchEvent(document,"fullscreenerror"),!1;this.exit()}if(!this.useStyleFirst){if(this.isNativelySupport)return isFunction(e[this._openKey])&&e[this._openKey](),!0;if(e instanceof HTMLVideoElement&&e.webkitSupportsFullscreen&&isFunction(e.webkitEnterFullscreen))return e.webkitEnterFullscreen(),this._fullscreenElement=e,!0}return this._savedStyles=_Object$keys(DESKTOP_FULLSCREEN_STYLE).reduce(function(t,r){return t[r]=e.style[r],t},{}),setStyle$1(e,DESKTOP_FULLSCREEN_STYLE),document.body&&(this._bodyOverflow=document.body.style.overflow,document.body.style.overflow="hidden"),document.documentElement&&(this._htmlOverflow=document.documentElement.style.overflow,document.documentElement.style.overflow="hidden"),this._fullscreenElement=e,this.hasUsedStyle=!0,dispatchEvent(e,"fullscreenchange"),!0}},{key:"exit",value:function(){if(!this.isFullscreen)return!1;if(this.isNativelySupport&&!this.useStyleFirst&&!this.hasUsedStyle)return document[this._exitKey](),!0;var e=this._fullscreenElement;return setStyle$1(e,this._savedStyles),document.body&&(document.body.style.overflow=this._bodyOverflow),document.documentElement&&(document.documentElement.style.overflow=this._htmlOverflow),this._fullscreenElement=null,this._savedStyles={},dispatchEvent(e,"fullscreenchange"),!0}},{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:document;this._handleEvent(r,"addEventListener",e,t)}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:document;this._handleEvent(r,"removeEventListener",e,t)}},{key:"_handleEvent",value:function(e,t,r,i){("fullscreenchange"===r?FULLSCREEN_CHANGE:"fullscreenerror"===r?FULLSCREEN_ERROR:[r]).forEach(function(r){e[t](r,i)})}},{key:"useStyleFirst",get:function(){return useStyleFirst},set:function(e){return(e=!!e)===useStyleFirst?e:(useStyleFirst=e,dispatchEvent(document,"esfullscreenmethodchange"),e)}},{key:"fullscreenElement",get:function(){return["fullscreenElement","webkitFullscreenElement","mozFullScreenElement","msFullscreenElement"].reduce(function(e,t){return e||document[t]},null)||this._fullscreenElement}},{key:"isFullscreen",get:function(){return isElement(this.fullscreenElement)}}]),e}(),_applyDecoratedDescriptor(_class2.prototype,"open",[_dec2],_Object$getOwnPropertyDescriptor(_class2.prototype,"open"),_class2.prototype),_applyDecoratedDescriptor(_class2.prototype,"exit",[_dec3],_Object$getOwnPropertyDescriptor(_class2.prototype,"exit"),_class2.prototype),_applyDecoratedDescriptor(_class2.prototype,"on",[_dec4],_Object$getOwnPropertyDescriptor(_class2.prototype,"on"),_class2.prototype),_applyDecoratedDescriptor(_class2.prototype,"off",[_dec5],_Object$getOwnPropertyDescriptor(_class2.prototype,"off"),_class2.prototype),_class=_class2))||_class),index=new ESFullScreen,isEnum$1=_objectPie.f,_objectToArray=function(e){return function(t){for(var r,i=_toIobject(t),n=_objectKeys(i),o=n.length,a=0,s=[];o>a;)isEnum$1.call(i,r=n[a++])&&s.push(e?[r,i[r]]:i[r]);return s}},$entries=_objectToArray(!0);_export(_export.S,"Object",{entries:function(e){return $entries(e)}});var entries=_core.Object.entries,entries$1=createCommonjsModule(function(e){e.exports={default:entries,__esModule:!0}}),_Object$entries=unwrapExports(entries$1),tempCurrentTime=0,NativeVideoKernel=function(e){function t(e,r,i){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||_Object$getPrototypeOf(t)).call(this));if(!isElement(e))throw new Error("You must pass in an legal video element but not "+(void 0===e?"undefined":_typeof(e)));return n.video=e,n.config=r,n.customConfig=i,n}return _inherits(t,CustEvent),_createClass(t,null,[{key:"isSupport",value:function(){return!0}}]),_createClass(t,[{key:"load",value:function(e){this.video.setAttribute("src",e),this.video.src=e}},{key:"startLoad",value:function(e){var t=this.video.currentTime||tempCurrentTime;this.load(e),this.seek(t)}},{key:"stopLoad",value:function(){tempCurrentTime=this.video.currentTime,this.video.src="",this.video.removeAttribute("src")}},{key:"destroy",value:function(){isElement(this.video)&&this.stopLoad()}},{key:"play",value:function(){return this.video.play()}},{key:"pause",value:function(){return this.video.pause()}},{key:"refresh",value:function(){this.video.src=this.config.src}},{key:"attachMedia",value:function(){}},{key:"seek",value:function(e){this.video.currentTime=e}}]),t}(),defaultConfig={isLive:!1,box:"",preset:{},presetConfig:{}},LOG_TAG="chimee-kernel",kernelEvents=["mediaInfo","heartbeat","error"],boxSuffixMap={flv:".flv",hls:".m3u8",mp4:".mp4"},ChimeeKernel=function(e){function t(e,r){_classCallCheck(this,t);var i=_possibleConstructorReturn(this,(t.__proto__||_Object$getPrototypeOf(t)).call(this));if(i.VERSION="1.4.0",!isElement(e))throw new Error("You must pass in an video element to the chimee-kernel");return i.config=deepAssign({},defaultConfig,r),i.videoElement=e,i.initVideoKernel(),i.bindEvents(i.videoKernel),i}return _inherits(t,CustEvent),_createClass(t,[{key:"destroy",value:function(){this.bindEvents(this.videoKernel,!0),this.videoKernel.destroy()}},{key:"initVideoKernel",value:function(){var e=this.config,t=this.chooseBox(e);this.box=t;var r=this.chooseVideoKernel(this.box,e.preset);if(!isFunction(r))throw new Error("We can't find video kernel for "+t+". Please check your config and make sure it's installed or provided");var i=e.presetConfig[this.box]||{};deepAssign(e,i),this.videoKernel=new r(this.videoElement,e,i)}},{key:"chooseBox",value:function(e){var t=e.src,r=e.box;if(isString(r)&&r)return r;for(var i in t=t.toLowerCase(),boxSuffixMap){var n=boxSuffixMap[i];if(t.indexOf(n)>-1)return i}return"native"}},{key:"chooseVideoKernel",value:function(e,t){switch(e){case"native":return NativeVideoKernel;case"mp4":return this.getMp4Kernel(t.mp4);case"flv":case"hls":return t[e];default:throw new Error("We currently do not support box "+e+", please contact us through https://github.com/Chimeejs/chimee/issues.")}}},{key:"getMp4Kernel",value:function(e){var t=e&&isFunction(e.isSupport);return t&&e.isSupport()?e:(t&&this.warnLog("mp4 decode is not support in this browser, we will switch to the native video kernel"),this.box="native",NativeVideoKernel)}},{key:"errorLog",value:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.emit("error",new Error(t[0])),Log$1.error.apply(Log$1,[LOG_TAG].concat(t))}},{key:"warnLog",value:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return Log$1.warn.apply(Log$1,[LOG_TAG].concat(t))}},{key:"bindEvents",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];kernelEvents.forEach(function(i){e[r?"off":"on"](i,function(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).data;t.emit(i,e)})})}},{key:"attachMedia",value:function(){this.videoKernel.attachMedia()}},{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.config.src;this.config.src=e,this.videoKernel.load(e)}},{key:"startLoad",value:function(){if(!isFunction(this.videoKernel.startLoad))throw new Error("This video kernel do not support startLoad, please contact us on https://github.com/Chimeejs/chimee/issues");this.videoKernel.startLoad(this.config.src)}},{key:"stopLoad",value:function(){isFunction(this.videoKernel.stopLoad)&&this.videoKernel.stopLoad()}},{key:"play",value:function(){this.videoKernel.play()}},{key:"pause",value:function(){this.videoKernel.pause()}},{key:"seek",value:function(e){isNumber(e)?this.videoKernel.seek(e):this.errorLog("When you try to seek, you must offer us a number, but not "+(void 0===e?"undefined":_typeof(e)))}},{key:"refresh",value:function(){this.videoKernel.refresh()}},{key:"currentTime",get:function(){return this.videoElement.currentTime||0}}]),t}(),_global$1=createCommonjsModule(function(e){var t=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=t)}),_core$1=createCommonjsModule(function(e){var t=e.exports={version:"2.5.3"};"number"==typeof __e&&(__e=t)}),_core_1$1=_core$1.version,_isObject$1=function(e){return"object"==typeof e?null!==e:"function"==typeof e},_anObject$1=function(e){if(!_isObject$1(e))throw TypeError(e+" is not an object!");return e},_fails$1=function(e){try{return!!e()}catch(e){return!0}},_descriptors$1=!_fails$1(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),document$3=_global$1.document,is$1=_isObject$1(document$3)&&_isObject$1(document$3.createElement),_domCreate$1=function(e){return is$1?document$3.createElement(e):{}},_ie8DomDefine$1=!_descriptors$1&&!_fails$1(function(){return 7!=Object.defineProperty(_domCreate$1("div"),"a",{get:function(){return 7}}).a}),_toPrimitive$1=function(e,t){if(!_isObject$1(e))return e;var r,i;if(t&&"function"==typeof(r=e.toString)&&!_isObject$1(i=r.call(e)))return i;if("function"==typeof(r=e.valueOf)&&!_isObject$1(i=r.call(e)))return i;if(!t&&"function"==typeof(r=e.toString)&&!_isObject$1(i=r.call(e)))return i;throw TypeError("Can't convert object to primitive value")},dP$4=Object.defineProperty,f$8=_descriptors$1?Object.defineProperty:function(e,t,r){if(_anObject$1(e),t=_toPrimitive$1(t,!0),_anObject$1(r),_ie8DomDefine$1)try{return dP$4(e,t,r)}catch(e){}if("get"in r||"set"in r)throw TypeError("Accessors not supported!");return"value"in r&&(e[t]=r.value),e},_objectDp$1={f:f$8},_propertyDesc$1=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},_hide$1=_descriptors$1?function(e,t,r){return _objectDp$1.f(e,t,_propertyDesc$1(1,r))}:function(e,t,r){return e[t]=r,e},hasOwnProperty$1={}.hasOwnProperty,_has$1=function(e,t){return hasOwnProperty$1.call(e,t)},id$2=0,px$1=Math.random(),_uid$1=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++id$2+px$1).toString(36))},_redefine$1=createCommonjsModule(function(e){var t=_uid$1("src"),r=Function.toString,i=(""+r).split("toString");_core$1.inspectSource=function(e){return r.call(e)},(e.exports=function(e,r,n,o){var a="function"==typeof n;a&&(_has$1(n,"name")||_hide$1(n,"name",r)),e[r]!==n&&(a&&(_has$1(n,t)||_hide$1(n,t,e[r]?""+e[r]:i.join(String(r)))),e===_global$1?e[r]=n:o?e[r]?e[r]=n:_hide$1(e,r,n):(delete e[r],_hide$1(e,r,n)))})(Function.prototype,"toString",function(){return"function"==typeof this&&this[t]||r.call(this)})}),_aFunction$1=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e},_ctx$1=function(e,t,r){if(_aFunction$1(e),void 0===t)return e;switch(r){case 1:return function(r){return e.call(t,r)};case 2:return function(r,i){return e.call(t,r,i)};case 3:return function(r,i,n){return e.call(t,r,i,n)}}return function(){return e.apply(t,arguments)}},PROTOTYPE$3="prototype",$export$1=function(e,t,r){var i,n,o,a,s=e&$export$1.F,u=e&$export$1.G,c=e&$export$1.S,l=e&$export$1.P,d=e&$export$1.B,f=u?_global$1:c?_global$1[t]||(_global$1[t]={}):(_global$1[t]||{})[PROTOTYPE$3],h=u?_core$1:_core$1[t]||(_core$1[t]={}),p=h[PROTOTYPE$3]||(h[PROTOTYPE$3]={});for(i in u&&(r=t),r)o=((n=!s&&f&&void 0!==f[i])?f:r)[i],a=d&&n?_ctx$1(o,_global$1):l&&"function"==typeof o?_ctx$1(Function.call,o):o,f&&_redefine$1(f,i,o,e&$export$1.U),h[i]!=o&&_hide$1(h,i,a),l&&p[i]!=o&&(p[i]=o)};_global$1.core=_core$1,$export$1.F=1,$export$1.G=2,$export$1.S=4,$export$1.P=8,$export$1.B=16,$export$1.W=32,$export$1.U=64,$export$1.R=128;var _export$1=$export$1;_export$1(_export$1.G,{global:_global$1});var global$1=_core$1.global,videoEvents=["abort","canplay","canplaythrough","durationchange","emptied","encrypted","ended","error","interruptbegin","interruptend","loadeddata","loadedmetadata","loadstart","mozaudioavailable","pause","play","playing","progress","ratechange","seeked","seeking","stalled","suspend","timeupdate","volumechange","waiting"],videoReadOnlyProperties=["buffered","currentSrc","duration","error","ended","networkState","paused","readyState","seekable","sinkId","controlsList","tabIndex","dataset","offsetHeight","offsetLeft","offsetParent","offsetTop","offsetWidth"],domEvents=["beforeinput","blur","click","compositionend","compositionstart","compositionupdate","dblclick","focus","focusin","focusout","input","keydown","keypress","keyup","mousedown","mouseenter","mouseleave","mousemove","mouseout","mouseover","mouseup","resize","scroll","select","wheel","mousewheel","fullscreenchange","contextmenu","touchstart","touchmove","touchend"],passiveEvents=["wheel","mousewheel","touchstart","touchmove"],selfProcessorEvents=["silentLoad","fullscreen"],kernelMethods=["play","pause","seek","startLoad","stopLoad"],dispatcherMethods=["load"],kernelEvents$1=["mediaInfo","heartbeat","error"],domMethods=["focus","fullscreen","requestFullscreen","exitFullscreen"],videoMethods=["canPlayType","captureStream","setSinkId"],_dec$1,_dec2$1,_dec3$1,_dec4$1,_class$1;function _applyDecoratedDescriptor$1(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var secondaryReg=/^(before|after|_)/;function secondaryChecker(e){return!e.match(secondaryReg)}var Bus=(_dec$1=runnable(secondaryChecker),_dec2$1=runnable(secondaryChecker,{backup:function(){return!1}}),_dec3$1=runnable(secondaryChecker),_dec4$1=runnable(secondaryChecker,{backup:function(){return!1}}),_class$1=function(){function e(t){_classCallCheck(this,e),this.events={},this.onceMap={},this.__dispatcher=t}return _createClass(e,[{key:"on",value:function(e,t,r){var i=this._getEventStage(t),n=i.stage,o=i.key;this._addEvent([o,n,e],r)}},{key:"off",value:function(e,t,r){var i=this._getEventStage(t),n=i.stage,o=[i.key,n,e];if(!this._removeEvent(o,r)){var a=this._getHandlerFromOnceMap(o,r);isFunction(a)&&this._removeEvent(o,a)&&this._removeFromOnceMap(o,r,a)}}},{key:"once",value:function(e,t,r){var i=this._getEventStage(t),n=i.stage,o=this,a=[i.key,n,e],s=function e(){bind(r,this).apply(void 0,arguments),o._removeEvent(a,e),o._removeFromOnceMap(a,r,e)};this._addEvent(a,s),this._addToOnceMap(a,r,s)}},{key:"emit",value:function(e){for(var t=this,r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];var o=this.events[e];if(isEmpty(o))return selfProcessorEvents.indexOf(e)>-1?_Promise.resolve():this._eventProcessor.apply(this,[e,{sync:!1}].concat(_toConsumableArray(i)));var a=this._getEventQueue(o.before,this.__dispatcher.order);return runRejectableQueue.apply(void 0,[a].concat(_toConsumableArray(i))).then(function(){if(!(selfProcessorEvents.indexOf(e)>-1))return t._eventProcessor.apply(t,[e,{sync:!1}].concat(_toConsumableArray(i)))}).catch(function(e){return isError(e)&&t.__dispatcher.throwError(e),_Promise.reject(e)})}},{key:"emitSync",value:function(e){for(var t=this.events[e],r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];if(isEmpty(t))return selfProcessorEvents.indexOf(e)>-1||this._eventProcessor.apply(this,[e,{sync:!0}].concat(_toConsumableArray(i)));var o=this._getEventQueue(t.before,this.__dispatcher.order);return runStoppableQueue.apply(void 0,[o].concat(_toConsumableArray(i)))&&(selfProcessorEvents.indexOf(e)>-1||this._eventProcessor.apply(this,[e,{sync:!0}].concat(_toConsumableArray(i))))}},{key:"trigger",value:function(e){for(var t=this,r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];var o=this.events[e];if(isEmpty(o))return _Promise.resolve(!0);var a=this._getEventQueue(o.main,this.__dispatcher.order);return runRejectableQueue.apply(void 0,[a].concat(_toConsumableArray(i))).then(function(){var e=t._getEventQueue(o.after,t.__dispatcher.order);return runRejectableQueue.apply(void 0,[e].concat(_toConsumableArray(i)))}).then(function(){return t._runSideEffectEvent.apply(t,[e,t.__dispatcher.order].concat(_toConsumableArray(i)))}).catch(function(r){return isError(r)&&t.__dispatcher.throwError(r),t._runSideEffectEvent.apply(t,[e,t.__dispatcher.order].concat(_toConsumableArray(i)))})}},{key:"triggerSync",value:function(e){var t=this.events[e];if(isEmpty(t))return!0;for(var r=this._getEventQueue(t.main,this.__dispatcher.order),i=this._getEventQueue(t.after,this.__dispatcher.order),n=arguments.length,o=Array(n>1?n-1:0),a=1;a<n;a++)o[a-1]=arguments[a];var s=runStoppableQueue.apply(void 0,[r].concat(_toConsumableArray(o)))&&runStoppableQueue.apply(void 0,[i].concat(_toConsumableArray(o)));return this._runSideEffectEvent.apply(this,[e,this.__dispatcher.order].concat(_toConsumableArray(o))),s}},{key:"destroy",value:function(){delete this.events,delete this.__dispatcher}},{key:"_addEvent",value:function(e,t){var r=(e=deepClone(e)).pop(),i=e.reduce(function(e,t){return e[t]=e[t]||{},e[t]},this.events);i[r]=i[r]||[],i[r].push(t)}},{key:"_removeEvent",value:function(e,t){for(var r=(e=deepClone(e)).pop(),i=this.events,n=0,o=e.length;n<o;n++){var a=i[e[n]];if(isEmpty(a))return;i=a}var s=i[r]||[],u=s.indexOf(t),c=u>-1;return c&&s.splice(u,1),s.length<1&&delete i[r],c}},{key:"_addToOnceMap",value:function(e,t,r){var i=e.join("-"),n=this.onceMap[i]=this.onceMap[i]||new _Map;n.has(t)||n.set(t,[]),n.get(t).push(r)}},{key:"_removeFromOnceMap",value:function(e,t,r){var i=e.join("-"),n=this.onceMap[i],o=n.get(t),a=o.indexOf(r);o.splice(a,1),isEmpty(o)&&n.delete(t)}},{key:"_getHandlerFromOnceMap",value:function(e,t){var r=e.join("-"),i=this.onceMap[r];if(!isVoid(i)&&i.has(t))return i.get(t)[0]}},{key:"_getEventStage",value:function(e){var t=e.match(secondaryReg),r=t&&t[0]||"main";return t&&(e=camelize(e.replace(secondaryReg,""))),{stage:r,key:e}}},{key:"_getEventQueue",value:function(e,t){var r=this;return t=isArray(t)?t.concat(["_vm"]):["_vm"],isEmpty(e)?[]:t.reduce(function(t,i){return isEmpty(e[i])||!isArray(e[i])||!r.__dispatcher.plugins[i]&&"_vm"!==i?t:t.concat(e[i].map(function(e){return bind(e,r.__dispatcher.plugins[i]||r.__dispatcher.vm)}))},[])}},{key:"_eventProcessor",value:function(e,t){for(var r=t.sync,i=kernelMethods.indexOf(e)>-1,n=domMethods.indexOf(e)>-1,o=dispatcherMethods.indexOf(e)>-1,a=arguments.length,s=Array(a>2?a-2:0),u=2;u<a;u++)s[u-2]=arguments[u];if(i||n||o){var c,l;if(o)(c=this.__dispatcher)[e].apply(c,_toConsumableArray(s));else(l=this.__dispatcher[i?"kernel":"dom"])[e].apply(l,_toConsumableArray(s));if(videoEvents.indexOf(e)>-1||domEvents.indexOf(e)>-1)return!0}return this[r?"triggerSync":"trigger"].apply(this,[e].concat(_toConsumableArray(s)))}},{key:"_runSideEffectEvent",value:function(e,t){for(var r=arguments.length,i=Array(r>2?r-2:0),n=2;n<r;n++)i[n-2]=arguments[n];var o=this.events[e];return!isEmpty(o)&&(this._getEventQueue(o._,t).forEach(function(e){return e.apply(void 0,_toConsumableArray(i))}),!0)}}]),e}(),_applyDecoratedDescriptor$1(_class$1.prototype,"emit",[_dec$1],_Object$getOwnPropertyDescriptor(_class$1.prototype,"emit"),_class$1.prototype),_applyDecoratedDescriptor$1(_class$1.prototype,"emitSync",[_dec2$1],_Object$getOwnPropertyDescriptor(_class$1.prototype,"emitSync"),_class$1.prototype),_applyDecoratedDescriptor$1(_class$1.prototype,"trigger",[_dec3$1],_Object$getOwnPropertyDescriptor(_class$1.prototype,"trigger"),_class$1.prototype),_applyDecoratedDescriptor$1(_class$1.prototype,"triggerSync",[_dec4$1],_Object$getOwnPropertyDescriptor(_class$1.prototype,"triggerSync"),_class$1.prototype),_class$1),_dec$1$1,_dec2$1$1,_class$1$1,_descriptor,_descriptor2,_descriptor3,_descriptor4,_descriptor5,_descriptor6,_descriptor7;function eventBinderCheck(e,t){if(!isString(e))throw new TypeError("key parameter must be String");if(!isFunction(t))throw new TypeError("fn parameter must be Function")}function attrAndStyleCheck(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return t.length>2?["set"].concat(t):2===t.length?["video","container","wrapper","videoElement"].indexOf(t[0])>-1?["get"].concat(t):["set","container"].concat(t):["get","container"].concat(t)}function _initDefineProp(e,t,r,i){r&&_Object$defineProperty(e,t,{enumerable:r.enumerable,configurable:r.configurable,writable:r.writable,value:r.initializer?r.initializer.call(i):void 0})}function _applyDecoratedDescriptor$1$1(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}function stringOrVoid(e){return isString(e)?e:void 0}function accessorVideoProperty(e){return accessor({get:function(t){return this.dispatcher.videoConfigReady&&this.inited?this.dom.videoElement[e]:t},set:function(t){return this.dispatcher.videoConfigReady?(this.dom.videoElement[e]=t,t):t}})}function accessorVideoAttribute(e){var t=isObject(e)?e:{set:e,get:e,isBoolean:!1},r=t.set,i=t.get,n=t.isBoolean;return accessor({get:function(e){return this.dispatcher.videoConfigReady&&this.inited?this.dom.videoElement[i]:e},set:function(e){if(!this.dispatcher.videoConfigReady)return e;var t=n?e?"":void 0:null===e?void 0:e;return this.dom.setAttr("video",r,t),e}},{preSet:!1})}function accessorCustomAttribute(e,t){return accessor({get:function(r){var i=this.dom.getAttr("video",e);return this.dispatcher.videoConfigReady&&this.inited?t?!!i:i:r},set:function(r){if(!this.dispatcher.videoConfigReady)return r;var i=t?r||void 0:null===r?void 0:r;return this.dom.setAttr("video",e,i),r}})}function accessorWidthAndHeight(e){return accessor({get:function(t){if(!this.dispatcher.videoConfigReady||!this.inited)return t;var r=this.dom.getAttr("video",e),i=this.dom.videoElement[e];return isNumeric(r)&&isNumber(i)?i:r||void 0},set:function(t){if(!this.dispatcher.videoConfigReady)return t;var r=void 0;return void 0===t||isNumber(t)?r=t:isString(t)&&!_Number$isNaN(parseFloat(t))&&(r=t),this.dom.setAttr("video",e,r),r}})}var accessorMap={src:[string$1(),accessor({set:function(e){return this.dispatcher.readySync&&this.autoload&&e!==this.src&&(this.needToLoadSrc=!0),e}}),accessor({set:function(e){return this.needToLoadSrc&&(this.needToLoadSrc=!1,this.dispatcher.bus.emit("load",e)),e}},{preSet:!1})],autoload:boolean$1(),autoplay:[boolean$1(),accessorVideoProperty("autoplay")],controls:[boolean$1(),accessorVideoProperty("controls")],width:[accessorWidthAndHeight("width")],height:[accessorWidthAndHeight("height")],crossOrigin:[accessor({set:stringOrVoid}),accessorVideoAttribute({set:"crossorigin",get:"crossOrigin"})],loop:[boolean$1(),accessorVideoProperty("loop")],defaultMuted:[boolean$1(),accessorVideoAttribute({get:"defaultMuted",set:"muted",isBoolean:!0})],muted:[boolean$1(),accessorVideoProperty("muted")],preload:[accessor({set:function(e){return["none","auto","metadata",""].indexOf(e)>-1?e:"none"}},{preSet:!0}),accessorVideoAttribute("preload")],poster:[string$1(),accessor({get:function(e){return this.dispatcher.videoConfigReady&&this.inited?this.dom.videoElement.poster:e},set:function(e){return this.dispatcher.videoConfigReady?(e.length&&this.dom.setAttr("video","poster",e),e):e}})],playsInline:[accessor({get:function(e){var t=this.dom.videoElement.playsInline;return this.dispatcher.videoConfigReady&&this.inited?void 0===t?e:t:e},set:function(e){if(!this.dispatcher.videoConfigReady)return e;this.dom.videoElement.playsInline=e;var t=e?"":void 0;return this.dom.setAttr("video","playsinline",t),this.dom.setAttr("video","webkit-playsinline",t),this.dom.setAttr("video","x5-playsinline",t),e}}),boolean$1()],x5VideoPlayerFullscreen:[accessor({set:function(e){return!!e},get:function(e){return!!e}}),accessorCustomAttribute("x5-video-player-fullscreen",!0)],x5VideoOrientation:[accessor({set:stringOrVoid}),accessorCustomAttribute("x5-video-orientation")],x5VideoPlayerType:[accessor({set:function(e){if(!this.dispatcher.videoConfigReady)return e;var t="h5"===e?"h5":void 0;return this.dom.setAttr("video","x5-video-player-type",t),e},get:function(){return this.dom.getAttr("video","x5-video-player-type")?"h5":void 0}})],xWebkitAirplay:[accessor({set:function(e){return!!e},get:function(e){return!!e}}),accessorCustomAttribute("x-webkit-airplay",!0)],playbackRate:[number$1(1),accessorVideoProperty("playbackRate")],defaultPlaybackRate:[accessorVideoProperty("defaultPlaybackRate"),number$1(1)],disableRemotePlayback:[boolean$1(),accessorVideoProperty("disableRemotePlayback")],volume:[number$1(1),accessorVideoProperty("volume")]},VideoConfig=(_dec$1$1=boolean(),_dec2$1$1=string(function(e){return e.toLocaleLowerCase()}),_class$1$1=function(){function e(t,r){_classCallCheck(this,e),_initDefineProp(this,"needToLoadSrc",_descriptor,this),_initDefineProp(this,"changeWatchable",_descriptor2,this),_initDefineProp(this,"inited",_descriptor3,this),this.src="",_initDefineProp(this,"isLive",_descriptor4,this),_initDefineProp(this,"box",_descriptor5,this),this.preset={},this.presetConfig={},this.autoload=!0,this.autoplay=!1,this.controls=!1,this.width="100%",this.height="100%",this.crossOrigin=void 0,this.loop=!1,this.defaultMuted=!1,this.muted=!1,this.preload="auto",this.poster=void 0,this.playsInline=!1,this.x5VideoPlayerFullscreen=!1,this.x5VideoOrientation=void 0,this.x5VideoPlayerType=void 0,this.xWebkitAirplay=!1,this.playbackRate=1,this.defaultPlaybackRate=1,this.disableRemotePlayback=!1,this.volume=1,_initDefineProp(this,"_kernelProperty",_descriptor6,this),_initDefineProp(this,"_realDomAttr",_descriptor7,this),applyDecorators(this,accessorMap,{self:!0}),Object.defineProperty(this,"dispatcher",{value:t,enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(this,"dom",{value:t.dom,enumerable:!1,writable:!1,configurable:!1}),deepAssign(this,r)}return _createClass(e,[{key:"init",value:function(){var e=this;this._realDomAttr.forEach(function(t){e[t]=e[t]}),this.inited=!0}}]),e}(),_descriptor=_applyDecoratedDescriptor$1$1(_class$1$1.prototype,"needToLoadSrc",[nonenumerable],{enumerable:!0,initializer:function(){return!1}}),_descriptor2=_applyDecoratedDescriptor$1$1(_class$1$1.prototype,"changeWatchable",[nonenumerable],{enumerable:!0,initializer:function(){return!0}}),_descriptor3=_applyDecoratedDescriptor$1$1(_class$1$1.prototype,"inited",[nonenumerable],{enumerable:!0,initializer:function(){return!1}}),_descriptor4=_applyDecoratedDescriptor$1$1(_class$1$1.prototype,"isLive",[_dec$1$1,nonconfigurable],{enumerable:!0,initializer:function(){return!1}}),_descriptor5=_applyDecoratedDescriptor$1$1(_class$1$1.prototype,"box",[_dec2$1$1,nonconfigurable],{enumerable:!0,initializer:function(){return""}}),_descriptor6=_applyDecoratedDescriptor$1$1(_class$1$1.prototype,"_kernelProperty",[frozen],{enumerable:!0,initializer:function(){return["isLive","box","preset","kernels","presetConfig"]}}),_descriptor7=_applyDecoratedDescriptor$1$1(_class$1$1.prototype,"_realDomAttr",[frozen],{enumerable:!0,initializer:function(){return["src","controls","width","height","crossOrigin","loop","muted","preload","poster","autoplay","playsInline","x5VideoPlayerFullscreen","x5VideoOrientation","xWebkitAirplay","playbackRate","defaultPlaybackRate","autoload","disableRemotePlayback","defaultMuted","volume","x5VideoPlayerType"]}}),_class$1$1),_dec$2,_dec2$2,_dec3$1$1,_dec4$1$1,_dec5$1,_dec6,_dec7,_dec8,_dec9,_dec10,_dec11,_dec12,_dec13,_dec14,_dec15,_dec16,_dec17,_dec18,_dec19,_class$2,_class2$1;function _applyDecoratedDescriptor$2(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var VideoWrapper=(_dec$2=autobindClass(),_dec2$2=alias("silentLoad"),_dec3$1$1=alias("fullScreen"),_dec4$1$1=alias("$fullScreen"),_dec5$1=alias("fullscreen"),_dec6=alias("emit"),_dec7=alias("emitSync"),_dec8=alias("on"),_dec9=alias("addEventListener"),_dec10=before(eventBinderCheck),_dec11=alias("off"),_dec12=alias("removeEventListener"),_dec13=before(eventBinderCheck),_dec14=alias("once"),_dec15=before(eventBinderCheck),_dec16=alias("css"),_dec17=before(attrAndStyleCheck),_dec18=alias("attr"),_dec19=before(attrAndStyleCheck),_dec$2((_class2$1=function(){function e(){_classCallCheck(this,e),this.__events={},this.__unwatchHandlers=[]}return _createClass(e,[{key:"__wrapAsVideo",value:function(e){var t=this;videoReadOnlyProperties.forEach(function(e){_Object$defineProperty(t,e,{get:function(){return this.__dispatcher.dom.videoElement[e]},set:void 0,configurable:!1,enumerable:!1})}),videoMethods.forEach(function(e){_Object$defineProperty(t,e,{get:function(){var t=this.__dispatcher.dom.videoElement;return bind(t[e],t)},set:void 0,configurable:!1,enumerable:!1})}),applyDecorators(this,e._realDomAttr.concat(e._kernelProperty).reduce(function(t,r){return t[r]=[accessor({get:function(){return e[r]},set:function(t){return e[r]=t,t}}),nonenumerable],t},{}),{self:!0}),kernelMethods.forEach(function(e){_Object$defineProperty(t,e,{value:function(){for(var t=this,r=arguments.length,i=Array(r),n=0;n<r;n++)i[n]=arguments[n];return new _Promise(function(r){var n;t.__dispatcher.bus.once(t.__id,"_"+e,r),(n=t.__dispatcher.bus)[/^(seek)$/.test(e)?"emitSync":"emit"].apply(n,[e].concat(_toConsumableArray(i)))})},configurable:!0,enumerable:!1,writable:!0})}),domMethods.forEach(function(e){"fullscreen"!==e&&_Object$defineProperty(t,e,{value:function(){var t;return(t=this.__dispatcher.dom)[e].apply(t,arguments)},configurable:!0,enumerable:!1,writable:!0})})}},{key:"$watch",value:function(e,t){var r=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=i.deep,o=i.diff,a=void 0===o||o,s=i.other,u=i.proxy,c=void 0!==u&&u;if(!isString(e)&&!isArray(e))throw new TypeError("$watch only accept string and Array<string> as key to find the target to spy on, but not "+e+", whose type is "+(void 0===e?"undefined":_typeof(e)));var l=!0,d=function e(){l=!1;var t=r.__unwatchHandlers.indexOf(e);t>-1&&r.__unwatchHandlers.splice(t,1)},f=isString(e)?e.split("."):e,h=f.pop(),p=this.__dispatcher.videoConfig;return applyDecorators(0===f.length&&!s&&p._realDomAttr.indexOf(h)>-1?p:["isFullscreen","fullscreenElement"].indexOf(h)>-1?this.__dispatcher.dom:getDeepProperty(s||this,f,{throwError:!0}),_defineProperty({},h,watch(function(){!l||this instanceof VideoConfig&&!this.dispatcher.changeWatchable||bind(t,this).apply(void 0,arguments)},{deep:n,diff:a,proxy:c})),{self:!0}),this.__unwatchHandlers.push(d),d}},{key:"$set",value:function(e,t,r){if(!isObject(e)&&!isArray(e))throw new TypeError("$set only support Array or Object, but not "+e+", whose type is "+(void 0===e?"undefined":_typeof(e)));isFunction(e.__set)?e.__set(t,r):e[t]=r}},{key:"$del",value:function(e,t){if(!isObject(e)&&!isArray(e))throw new TypeError("$del only support Array or Object, but not "+e+", whose type is "+(void 0===e?"undefined":_typeof(e)));isFunction(e.__del)?e.__del(t):delete e[t]}},{key:"load",value:function(){for(var e=this,t=arguments.length,r=Array(t),i=0;i<t;i++)r[i]=arguments[i];return new _Promise(function(t){var i;e.__dispatcher.bus.once(e.__id,"_load",t),(i=e.__dispatcher.bus).emit.apply(i,["load"].concat(r))})}},{key:"$silentLoad",value:function(){for(var e=this,t=arguments.length,r=Array(t),i=0;i<t;i++)r[i]=arguments[i];return this.__dispatcher.bus.emit("silentLoad").then(function(){var t;return(t=e.__dispatcher).silentLoad.apply(t,r)}).then(function(t){e.__dispatcher.bus.trigger("silentLoad",t)})}},{key:"$fullscreen",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"container";if(!this.__dispatcher.bus.emitSync("fullscreen",e,t))return!1;var r=this.__dispatcher.dom.fullscreen(e,t);return this.__dispatcher.bus.triggerSync("fullscreen",e,t),r}},{key:"$emit",value:function(e){var t;if(!isString(e))throw new TypeError("emit key parameter must be String");for(var r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];(t=this.__dispatcher.bus).emit.apply(t,[e].concat(_toConsumableArray(i)))}},{key:"$emitSync",value:function(e){var t;if(!isString(e))throw new TypeError("emitSync key parameter must be String");for(var r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];return(t=this.__dispatcher.bus).emitSync.apply(t,[e].concat(_toConsumableArray(i)))}},{key:"$on",value:function(e,t){this.__dispatcher.bus.on(this.__id,e,t),this.__addEvents(e,t)}},{key:"$off",value:function(e,t){this.__dispatcher.bus.off(this.__id,e,t),this.__removeEvents(e,t)}},{key:"$once",value:function(e,t){var r=this,i=function i(){bind(t,this).apply(void 0,arguments),r.__removeEvents(e,i)};r.__addEvents(e,i),this.__dispatcher.bus.once(this.__id,e,i)}},{key:"$css",value:function(e){for(var t,r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];return(t=this.__dispatcher.dom)[e+"Style"].apply(t,i)}},{key:"$attr",value:function(e){for(var t,r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];if("set"===e&&/video/.test(i[0])){if(!this.__dispatcher.videoConfigReady)return i[2];if(this.__dispatcher.videoConfig._realDomAttr.indexOf(i[1])>-1){var o=i[1],a=i[2];return this.__dispatcher.videoConfig[o]=a,a}}return(t=this.__dispatcher.dom)[e+"Attr"].apply(t,i)}},{key:"__addEvents",value:function(e,t){this.__events[e]=this.__events[e]||[],this.__events[e].push(t)}},{key:"__removeEvents",value:function(e,t){if(!isEmpty(this.__events[e])){var r=this.__events[e].indexOf(t);r<0||(this.__events[e].splice(r,1),isEmpty(this.__events[e])&&delete this.__events[e])}}},{key:"__destroy",value:function(){var e=this;this.__unwatchHandlers.forEach(function(e){return e()}),_Object$keys(this.__events).forEach(function(t){isArray(e.__events[t])&&e.__events[t].forEach(function(r){return e.$off(t,r)})}),delete this.__events}},{key:"currentTime",get:function(){return this.__dispatcher.kernel.currentTime},set:function(e){this.__dispatcher.bus.emitSync("seek",e)}},{key:"$plugins",get:function(){return this.__dispatcher.plugins}},{key:"$pluginOrder",get:function(){return this.__dispatcher.order}},{key:"$wrapper",get:function(){return this.__dispatcher.dom.wrapper}},{key:"$container",get:function(){return this.__dispatcher.dom.container}},{key:"$video",get:function(){return this.__dispatcher.dom.videoElement}},{key:"isFullscreen",get:function(){return this.__dispatcher.dom.isFullscreen}},{key:"fullscreenElement",get:function(){return this.__dispatcher.dom.fullscreenElement}},{key:"container",get:function(){return this.__dispatcher.containerConfig},set:function(e){if(!isObject(e))throw new Error("The config of container must be Object, but not "+(void 0===e?"undefined":_typeof(e))+".");return deepAssign(this.__dispatcher.containerConfig,e),this.__dispatcher.container}}]),e}(),_applyDecoratedDescriptor$2(_class2$1.prototype,"$silentLoad",[_dec2$2],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$silentLoad"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$fullscreen",[_dec3$1$1,_dec4$1$1,_dec5$1],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$fullscreen"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$emit",[_dec6],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$emit"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$emitSync",[_dec7],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$emitSync"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$on",[_dec8,_dec9,_dec10],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$on"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$off",[_dec11,_dec12,_dec13],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$off"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$once",[_dec14,_dec15],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$once"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$css",[_dec16,_dec17],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$css"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$attr",[_dec18,_dec19],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$attr"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$plugins",[nonenumerable],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$plugins"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$pluginOrder",[nonenumerable],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$pluginOrder"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$wrapper",[nonenumerable],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$wrapper"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$container",[nonenumerable],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$container"),_class2$1.prototype),_applyDecoratedDescriptor$2(_class2$1.prototype,"$video",[nonenumerable],_Object$getOwnPropertyDescriptor(_class2$1.prototype,"$video"),_class2$1.prototype),_class$2=_class2$1))||_class$2),_dec$3,_class$3,Plugin=(_dec$3=autobindClass(),_dec$3(_class$3=function(e){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.id,i=e.name,n=e.level,o=void 0===n?0:n,a=e.operable,s=void 0===a||a,u=e.beforeCreate,c=e.create,l=e.init,d=e.inited,f=e.destroy,h=e.events,p=void 0===h?{}:h,m=e.data,v=void 0===m?{}:m,g=e.computed,y=void 0===g?{}:g,_=e.methods,b=void 0===_?{}:_,w=e.el,E=e.penetrate,S=void 0!==E&&E,T=e.inner,O=void 0===T||T,A=e.autoFocus,$=e.className,k=arguments[1],D=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{name:i};_classCallCheck(this,t);var I=_possibleConstructorReturn(this,(t.__proto__||_Object$getPrototypeOf(t)).call(this));if(I.destroyed=!1,I.VERSION="0.9.5",I.__operable=!0,I.__level=0,isEmpty(k))throw new TypeError("lack of dispatcher");if(!isString(r))throw new TypeError("id of PluginConfig must be string");I.__id=r,I.__dispatcher=k,I.$videoConfig=I.__dispatcher.videoConfig,I.__wrapAsVideo(I.$videoConfig),I.beforeCreate=I.beforeCreate||u;try{isFunction(I.beforeCreate)&&I.beforeCreate({events:p,data:v,computed:y,methods:b},D)}catch(e){I.$throwError(e)}if(!isEmpty(b)&&isObject(b)&&_Object$keys(b).forEach(function(e){var t=b[e];if(!isFunction(t))throw new TypeError("plugins methods must be Function");_Object$defineProperty(I,e,{value:bind(t,I),writable:!0,enumerable:!1,configurable:!0})}),!isEmpty(p)&&isObject(p)&&_Object$keys(p).forEach(function(e){if(!isFunction(p[e]))throw new TypeError("plugins events hook must bind with Function");I.$on(e,p[e])}),!isEmpty(v)&&isObject(v)&&deepAssign(I,v),!isEmpty(y)&&isObject(y)){var x=_Object$keys(y).reduce(function(e,t){var r=y[t];return isFunction(r)?(e[t]=accessor({get:r}),e):isObject(r)&&(isFunction(r.get)||isFunction(r.set))?(e[t]=accessor(r),e):e},{});applyDecorators(I,x,{self:!0})}I.create=I.create||c,I.init=I.init||l,I.inited=I.inited||d,I.destroy=I.destroy||f,I.$dom=I.__dispatcher.dom.insertPlugin(I.__id,w,{penetrate:S,inner:O,autoFocus:A,className:$}),I.$inner=O,I.$autoFocus=A,I.$penetrate=S,applyDecorators(I,{$inner:frozen,$autoFocus:frozen,$penetrate:frozen},{self:!0}),I.$operable=isBoolean(D.operable)?D.operable:s,I.__level=isInteger$2(D.level)?D.level:o,I.$config=D;try{isFunction(I.create)&&I.create()}catch(e){I.$throwError(e)}return I}return _inherits(t,VideoWrapper),_createClass(t,[{key:"__init",value:function(e){try{isFunction(this.init)&&this.init(e)}catch(e){this.$throwError(e)}}},{key:"__inited",value:function(){var e=this,t=void 0;try{t=isFunction(this.inited)&&this.inited()}catch(e){this.$throwError(e)}return this.readySync=!isPromise(t),this.ready=this.readySync?_Promise.resolve():t.then(function(t){return e.readySync=!0,t}).catch(function(t){return isError(t)?e.$throwError(t):_Promise.reject(t)}),this.readySync||this.ready}},{key:"$bumpToTop",value:function(){var e=this.__dispatcher._getTopLevel(this.$inner);this.$level=e+1}},{key:"$throwError",value:function(e){this.__dispatcher.throwError(e)}},{key:"$destroy",value:function(){isFunction(this.destroy)&&this.destroy(),_get(t.prototype.__proto__||_Object$getPrototypeOf(t.prototype),"__destroy",this).call(this),this.__dispatcher.dom.removePlugin(this.__id),delete this.__dispatcher,delete this.$dom,this.destroyed=!0}},{key:"$operable",set:function(e){isBoolean(e)&&(this.$dom.style.pointerEvents=e?"auto":"none",this.__operable=e)},get:function(){return this.__operable}},{key:"$level",set:function(e){isInteger$2(e)&&(this.__level=e,this.__dispatcher._sortZIndex())},get:function(){return this.__level}}]),t}())||_class$3),_dec$4,_dec2$3,_dec3$2,_dec4$2,_dec5$1$1,_dec6$1,_class$4;function _applyDecoratedDescriptor$3(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}function targetCheck(e){if("video"===e&&(e="videoElement"),!isElement(this[e]))throw new TypeError('Your target "'+e+'" is not a legal HTMLElement');for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return[e].concat(r)}function attrOperationCheck(e,t,r){if(!isString(t))throw new TypeError("to handle dom's attribute or style, your attr parameter must be string, but not "+t+" in "+(void 0===t?"undefined":_typeof(t)));if(!isString(e))throw new TypeError("to handle dom's attribute or style, your target parameter must be string, , but not "+e+" in "+(void 0===e?"undefined":_typeof(e)));return[e,t,r]}var Dom=(_dec$4=waituntil("__dispatcher.videoConfigReady"),_dec2$3=before(attrOperationCheck,targetCheck),_dec3$2=before(attrOperationCheck,targetCheck),_dec4$2=before(attrOperationCheck,targetCheck),_dec5$1$1=before(attrOperationCheck,targetCheck),_dec6$1=before(targetCheck),_class$4=function(){function e(t,r){var i=this;if(_classCallCheck(this,e),this.plugins={},this.originHTML="",this.videoEventHandlerList=[],this.videoDomEventHandlerList=[],this.containerDomEventHandlerList=[],this.wrapperDomEventHandlerList=[],this.__domEventHandlerList={},this.__mouseInVideo=!1,this.__videoExtendedNodes=[],this.isFullscreen=!1,this.fullscreenElement=void 0,this.__dispatcher=r,!isElement(t)&&!isString(t))throw new TypeError("Wrapper can only be string or HTMLElement, but not "+(void 0===t?"undefined":_typeof(t)));var n=$(t);if(0===n.length)throw new TypeError("Can not get dom node accroding wrapper. Please check your wrapper");this.wrapper=n[0],this.originHTML=this.wrapper.innerHTML;var o=n.find("video")[0];o||(o=document.createElement("video")),this.installVideo(o),this._addDomEvents(this.container,this.containerDomEventHandlerList,function(e){return function(){for(var t,r=arguments.length,n=Array(r),o=0;o<r;o++)n[o]=arguments[o];return(t=i.__dispatcher.bus).triggerSync.apply(t,["c_"+e].concat(_toConsumableArray(n)))}}),this._addDomEvents(this.wrapper,this.wrapperDomEventHandlerList,function(e){return function(){for(var t,r=arguments.length,n=Array(r),o=0;o<r;o++)n[o]=arguments[o];return(t=i.__dispatcher.bus).triggerSync.apply(t,["w_"+e].concat(_toConsumableArray(n)))}}),this._fullscreenMonitor(),index.on("fullscreenchange",this._fullscreenMonitor)}return _createClass(e,[{key:"installVideo",value:function(e){var t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).bindEvent,r=void 0===t||t;if(this.__videoExtendedNodes.push(e),setAttr(e,"tabindex",-1),this._autoFocusToVideo(e),isElement(this.container)){var i=this.container;0===i.childNodes.length?i.appendChild(e):i.insertBefore(e,i.childNodes[0])}else e.parentElement&&isElement(e.parentElement)&&e.parentElement!==this.wrapper?this.container=e.parentElement:(this.container=document.createElement("container"),$(this.container).append(e));return this.container.parentElement!==this.wrapper&&$(this.wrapper).append(this.container),r&&this.bindVideoEvents(e),this.videoElement=e,e}},{key:"bindVideoEvents",value:function(e){var t=this;videoEvents.forEach(function(r){var i=function(){for(var e,i=arguments.length,n=Array(i),o=0;o<i;o++)n[o]=arguments[o];return(e=t.__dispatcher.bus).trigger.apply(e,[r].concat(_toConsumableArray(n)))};t.videoEventHandlerList.push(i),addEvent(e,r,i)}),this._addDomEvents(e,this.videoDomEventHandlerList,function(e){return t._getEventHandler(e,{penetrate:!0})})}},{key:"removeVideo",value:function(){var e=this,t=this.videoElement;return this._autoFocusToVideo(this.videoElement,!1),videoEvents.forEach(function(t,r){removeEvent(e.videoElement,t,e.videoEventHandlerList[r])}),this.videoEventHandlerList=[],domEvents.forEach(function(t,r){removeEvent(e.videoElement,t,e.videoDomEventHandlerList[r])}),this.videoDomEventHandlerList=[],$(t).remove(),delete this.videoElement,t}},{key:"insertPlugin",value:function(e,t){var r=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!isString(e))throw new TypeError("insertPlugin id parameter must be string");if(isElement(this.plugins[e])&&this.removePlugin(e),isString(t))if(isHTMLString(t)){var n=document.createElement("div");n.innerHTML=t,t=n.children[0]}else t=document.createElement(hypenate(t));else isObject(t)&&(i=t);var o=i,a=o.inner,s=o.penetrate,u=o.autoFocus,c=i.className,l=t&&isElement(t)?t:document.createElement("div");isArray(c)&&(c=c.join(" ")),isString(c)&&addClassName(l,c),this.plugins[e]=l;var d=a?this.container:this.wrapper,f=a?this.videoElement:this.container;return(isBoolean(u)?u:a)&&this._autoFocusToVideo(l),s&&(this.__domEventHandlerList[e]=this.__domEventHandlerList[e]||[],this._addDomEvents(l,this.__domEventHandlerList[e],function(e){return r._getEventHandler(e,{penetrate:s})}),this.__videoExtendedNodes.push(l)),d.lastChild===f?(d.appendChild(l),l):(d.insertBefore(l,f.nextSibling),l)}},{key:"removePlugin",value:function(e){var t=this;if(isString(e)){var r=this.plugins[e];isElement(r)&&(r.parentNode&&r.parentNode.removeChild(r),this._autoFocusToVideo(r,!0)),isEmpty(this.__domEventHandlerList[e])||(domEvents.forEach(function(r,i){removeEvent(t.plugins[e],r,t.__domEventHandlerList[e][i])}),delete this.__domEventHandlerList[e]),delete this.plugins[e]}}},{key:"setPluginsZIndex",value:function(e){var t=this;e.forEach(function(e,r){return setStyle(e.match(/^(videoElement|container)$/)?t[e]:t.plugins[e],"z-index",++r)})}},{key:"setAttr",value:function(e,t,r){setAttr(this[e],t,r)}},{key:"getAttr",value:function(e,t){return getAttr(this[e],t)}},{key:"setStyle",value:function(e,t,r){setStyle(this[e],t,r)}},{key:"getStyle",value:function(e,t){return getStyle(this[e],t)}},{key:"requestFullscreen",value:function(e){return index.open(this[e])}},{key:"exitFullscreen",value:function(){return index.exit()}},{key:"fullscreen",value:function(){for(var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"container",r=arguments.length,i=Array(r>2?r-2:0),n=2;n<r;n++)i[n-2]=arguments[n];return e?this.requestFullscreen.apply(this,[t].concat(_toConsumableArray(i))):this.exitFullscreen.apply(this,_toConsumableArray(i))}},{key:"focus",value:function(){this.videoElement.focus()}},{key:"destroy",value:function(){var e=this;this.removeVideo(),domEvents.forEach(function(t,r){removeEvent(e.container,t,e.containerDomEventHandlerList[r]),removeEvent(e.wrapper,t,e.wrapperDomEventHandlerList[r])}),index.off("fullscreenchange",this._fullscreenMonitor),this.wrapper.innerHTML=this.originHTML,delete this.wrapper,delete this.plugins}},{key:"_addDomEvents",value:function(e,t,r){domEvents.forEach(function(i){var n=r(i);t.push(n),passiveEvents.indexOf(i)>-1?addEvent(e,i,n,!1,{passive:!0}):addEvent(e,i,n)})}},{key:"_autoFocusToVideo",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];isElement(e)&&((t?removeEvent:addEvent)(e,"mouseup",this._focusToVideo,!1,!0),(t?removeEvent:addEvent)(e,"touchend",this._focusToVideo,!1,!0))}},{key:"_focusToVideo",value:function(){var e=window.scrollX,t=window.scrollY;isFunction(this.videoElement.focus)&&this.videoElement.focus(),window.scrollTo(e,t)}},{key:"_fullscreenMonitor",value:function(e){var t=index.fullscreenElement,r=this.isFullscreen;!t||!isPosterityNode(this.wrapper,t)&&t!==this.wrapper?(this.isFullscreen=!1,this.fullscreenElement=void 0):(this.isFullscreen=!0,this.fullscreenElement=this.wrapper===t?"wrapper":this.container===t?"container":this.videoElement===t?"video":t),isEvent(e)&&r!==this.isFullscreen&&this.__dispatcher.bus.triggerSync("fullscreenchange",e)}},{key:"_getEventHandler",value:function(e,t){var r=this;if(!t.penetrate||["mouseenter","mouseleave"].indexOf(e)<0)return function(){for(var t,i=arguments.length,n=Array(i),o=0;o<i;o++)n[o]=arguments[o];(t=r.__dispatcher.bus).triggerSync.apply(t,[e].concat(n))};var i=function(e){return r.__videoExtendedNodes.indexOf(e)>-1||r.__videoExtendedNodes.reduce(function(t,r){return t||isPosterityNode(r,e)},!1)};return function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var o,a,s=t[0],u=s.toElement,c=s.currentTarget,l=s.relatedTarget,d=s.type,f=u||l;return r.__mouseInVideo&&"mouseleave"===d&&!i(f)?(r.__mouseInVideo=!1,(o=r.__dispatcher.bus).triggerSync.apply(o,["mouseleave"].concat(t))):!r.__mouseInVideo&&"mouseenter"===d&&i(c)?(r.__mouseInVideo=!0,(a=r.__dispatcher.bus).triggerSync.apply(a,["mouseenter"].concat(t))):void 0}}}]),e}(),_applyDecoratedDescriptor$3(_class$4.prototype,"setAttr",[_dec$4,_dec2$3],_Object$getOwnPropertyDescriptor(_class$4.prototype,"setAttr"),_class$4.prototype),_applyDecoratedDescriptor$3(_class$4.prototype,"getAttr",[_dec3$2],_Object$getOwnPropertyDescriptor(_class$4.prototype,"getAttr"),_class$4.prototype),_applyDecoratedDescriptor$3(_class$4.prototype,"setStyle",[_dec4$2],_Object$getOwnPropertyDescriptor(_class$4.prototype,"setStyle"),_class$4.prototype),_applyDecoratedDescriptor$3(_class$4.prototype,"getStyle",[_dec5$1$1],_Object$getOwnPropertyDescriptor(_class$4.prototype,"getStyle"),_class$4.prototype),_applyDecoratedDescriptor$3(_class$4.prototype,"requestFullscreen",[_dec6$1],_Object$getOwnPropertyDescriptor(_class$4.prototype,"requestFullscreen"),_class$4.prototype),_applyDecoratedDescriptor$3(_class$4.prototype,"_focusToVideo",[autobind],_Object$getOwnPropertyDescriptor(_class$4.prototype,"_focusToVideo"),_class$4.prototype),_applyDecoratedDescriptor$3(_class$4.prototype,"_fullscreenMonitor",[autobind],_Object$getOwnPropertyDescriptor(_class$4.prototype,"_fullscreenMonitor"),_class$4.prototype),_class$4),defaultContainerConfig={width:"100%",height:"100%",position:"relative",display:"block"},Vessel=function e(t,r,i){var n=this;_classCallCheck(this,e),this.__dispatcher=t,this.__target=r,["width","height","position","display"].forEach(function(e){_Object$defineProperty(n,e,{get:function(){return this.__dispatcher.dom.getStyle(this.__target,e)},set:function(t){if(isNumber(t)&&(t+="px"),!isString(t))throw new Error("The value of "+e+" in "+this.__target+"Config must be string, but not "+(void 0===t?"undefined":_typeof(t))+".");this.__dispatcher.dom.setStyle(this.__target,e,t)},configurable:!0,enumerable:!0})}),deepAssign(this,i)},_dec$5,_dec2$4,_dec3$3,_dec4$3,_dec5$2,_class$5;function _applyDecoratedDescriptor$4(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var pluginConfigSet={},kernelsSet={};function convertNameIntoId(e){if(!isString(e))throw new Error("Plugin's name must be a string, but not \""+e+'" in '+(void 0===e?"undefined":_typeof(e)));return camelize(e)}function checkPluginConfig(e){if(isFunction(e)){if(!(e.prototype instanceof Plugin))throw new TypeError("Your are trying to install plugin "+e.name+", but it's not extends from Chimee.plugin.")}else{if(!isObject(e)||isEmpty(e))throw new TypeError("plugin's config must be an Object, but not \""+e+'" in '+(void 0===e?"undefined":_typeof(e)));var t=e.name;if(!isString(t)||t.length<1)throw new TypeError('plugin must have a legal namea, but not "'+t+'" in '+(void 0===t?"undefined":_typeof(t)))}}var Dispatcher=(_dec$5=before(convertNameIntoId),_dec2$4=before(checkPluginConfig),_dec3$3=before(convertNameIntoId),_dec4$3=before(convertNameIntoId),_dec5$2=before(convertNameIntoId),_class$5=function(){function e(t,r){var i=this;if(_classCallCheck(this,e),this.plugins={},this.order=[],this.readySync=!1,this.zIndexMap={inner:[],outer:[]},this.changeWatchable=!0,this.kernelEventHandlerList=[],!isObject(t))throw new TypeError('UserConfig must be an Object, but not "'+t+'" in '+(void 0===t?"undefined":_typeof(t)));this.dom=new Dom(t.wrapper,this),this.bus=new Bus(this),this.vm=r,this.videoConfigReady=!1,this.videoConfig=new VideoConfig(this,t),isArray(t.plugins)&&!isArray(t.plugin)&&(t.plugin=t.plugins,delete t.plugins),this._initUserPlugin(t.plugin);var n=deepAssign({},defaultContainerConfig,t.container||{});this.order.forEach(function(e){return i.plugins[e].__init(i.videoConfig,n)}),this.videoConfigReady=!0,this.videoConfig.init(),this.containerConfig=new Vessel(this,"container",n),this.kernel=this._createKernel(this.dom.videoElement,this.videoConfig),this._bindKernelEvents(this.kernel);var o=[];this.order.forEach(function(e){var t=i.plugins[e].__inited();isPromise(t)&&o.push(t)}),this.readySync=0===o.length,this.ready=this.readySync?_Promise.resolve():_Promise.all(o).then(function(){i.readySync=!0,i.bus.trigger("ready"),i._autoloadVideoSrcAtFirst()}),this.readySync&&this._autoloadVideoSrcAtFirst()}return _createClass(e,[{key:"use",value:function(t){if(isString(t)&&(t={name:t,alias:void 0}),!isObject(t)||isObject(t)&&!isString(t.name))throw new TypeError("pluginConfig do not match requirement");isString(t.alias)||(t.alias=void 0);var r=t,i=r.name,n=r.alias;t.name=n||i,delete t.alias;var o=camelize(i),a=camelize(n||i),s=t,u=e.getPluginConfig(o);if(isEmpty(u))throw new TypeError("You have not installed plugin "+o);isObject(u)&&(u.id=a);var c=isFunction(u)?new u({id:a},this,s):new Plugin(u,this,s);return this.plugins[a]=c,_Object$defineProperty(this.vm,a,{value:c,configurable:!0,enumerable:!1,writable:!1}),this.order.push(a),this._sortZIndex(),this.videoConfigReady&&c.__inited(),c.ready}},{key:"unuse",value:function(e){var t=this.plugins[e];if(isObject(t)&&isFunction(t.$destroy)){t.$destroy();var r=this.order.indexOf(e);r>-1&&this.order.splice(r,1),delete this.plugins[e],delete this.vm[e]}else delete this.plugins[e]}},{key:"throwError",value:function(e){this.vm.__throwError(e)}},{key:"silentLoad",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=r.duration,n=void 0===i?3:i,o=r.bias,a=void 0===o?0:o,s=r.repeatTimes,u=void 0===s?0:s,c=r.increment,l=void 0===c?0:c,d=r.isLive,f=void 0===d?this.videoConfig.isLive:d,h=r.box,p=void 0===h?this.videoConfig.box:h,m=r.kernels,v=void 0===m?this.videoConfig.kernels:m,g=r.preset,y=void 0===g?this.videoConfig.preset:g,_=r.immediate||f,b={isLive:f,box:p,src:e,kernels:v,preset:y};return runRejectableQueue(new Array(u+1).fill(1).map(function(e,i){return function(){return new _Promise(function(e,o){r.abort&&o({error:!0,message:"user abort the mission"});var s=document.createElement("video"),c=t.kernel.currentTime+n+l*i;s.muted=!0;var d=!1,h=void 0,p=void 0,m=void 0,v=void 0,g=function r(){var i=t.kernel.currentTime;if(a<=0&&i>=c||a>0&&(Math.abs(c-i)<=a&&d||i-c>a))return removeEvent(t.dom.videoElement,"timeupdate",r),removeEvent(s,"error",p,!0),d?o({error:!1,video:s,kernel:h}):(removeEvent(s,"canplay",m,!0),removeEvent(s,"loadedmetadata",v,!0),h.destroy(),e())};m=function(){if(d=!0,_)return removeEvent(t.dom.videoElement,"timeupdate",g),removeEvent(s,"error",p,!0),o({error:!1,video:s,kernel:h})},v=function(){f||h.seek(c)},p=function(r){removeEvent(s,"canplay",m,!0),removeEvent(s,"loadedmetadata",v,!0),removeEvent(t.dom.videoElement,"timeupdate",g),h.off("error",p);var n=void 0;if(r.target===h){var a=r.data.errmsg;Log$1.error("chimee's silentload bump into a kernel error",a),n=new Error(a)}else n=isEmpty(s.error)?new Error("unknow video error"):new Error(s.error.message),Log$1.error("chimee's silentload",n.message);return h.destroy(),t._silentLoadTempKernel=void 0,i===u?o(n):e(n)},addEvent(s,"canplay",m,!0),addEvent(s,"loadedmetadata",v,!0),addEvent(s,"error",p,!0),h=t._createKernel(s,b),t._silentLoadTempKernel=h,h.on("error",p),addEvent(t.dom.videoElement,"timeupdate",g),h.load()})}})).then(function(){var t="The silentLoad for "+e+" timed out. Please set a longer duration or check your network";return _Promise.reject(new Error(t))}).catch(function(e){if(isError(e))return _Promise.reject(e);if(e.error)return _Promise.reject(new Error(e.message));var i=e.video,n=e.kernel;return r.abort?(n.destroy(),_Promise.reject(new Error("user abort the mission"))):t.dom.videoElement.paused?(t.switchKernel({video:i,kernel:n,config:b}),_Promise.resolve()):new _Promise(function(e){addEvent(i,"play",function(){t.switchKernel({video:i,kernel:n,config:b}),e()},!0),i.play()})})}},{key:"load",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=isString(e)?e:isObject(e)&&isString(e.src)?e.src:"";isObject(e)&&(delete e.src,t=e);var i=this.kernel.box,n=this.videoConfig,o=t,a=o.isLive,s=void 0===a?n.isLive:a,u=o.box,c=void 0===u?n.box:u,l=o.preset,d=void 0===l?n.preset:l,f=o.kernels,h=void 0===f?n.kernels:f;if("native"!==c||c!==i||!isEmpty(t)){var p=document.createElement("video"),m={isLive:s,box:c,preset:d,src:r,kernels:h},v=this._createKernel(p,m);this.switchKernel({video:p,kernel:v,config:m})}var g=this.videoConfig.autoload;this._changeUnwatchable(this.videoConfig,"autoload",!1),this.videoConfig.src=r||this.videoConfig.src,this.kernel.load(this.videoConfig.src),this._changeUnwatchable(this.videoConfig,"autoload",g)}},{key:"switchKernel",value:function(e){var t=this,r=e.video,i=e.kernel,n=e.config,o=this.kernel,a=deepClone(this.videoConfig);this.dom.removeVideo(),this.dom.installVideo(r,{bindEvent:!1}),this.videoConfig.changeWatchable=!1,this.videoConfig.autoload=!1,this.videoConfig.src=n.src,this.videoConfig._realDomAttr.forEach(function(e){"src"!==e&&(t.videoConfig[e]=a[e])}),this.videoConfig.changeWatchable=!0,this._bindKernelEvents(o,!0),this._bindKernelEvents(i),this.kernel=i,this._silentLoadTempKernel=void 0;var s=n.isLive,u=n.box,c=n.preset,l=n.kernels;_Object$assign(this.videoConfig,{isLive:s,box:u,preset:c,kernels:l}),o.destroy(),setTimeout(function(){return t.dom.bindVideoEvents(r)})}},{key:"destroy",value:function(){for(var e in this.plugins)this.unuse(e);this.bus.destroy(),delete this.bus,this.dom.destroy(),delete this.dom,this._bindKernelEvents(this.kernel,!0),this.kernel.destroy(),delete this.kernel,delete this.vm,delete this.plugins,delete this.order}},{key:"_initUserPlugin",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return isArray(t)||(t=[]),t.map(function(t){return e.use(t)})}},{key:"_sortZIndex",value:function(){var e=this,t=this.order.reduce(function(t,r){var i=e.plugins[r];if(isEmpty(i))return t;var n=t[i.$inner?"inner":"outer"],o=i.$level;return n[o]=n[o]||[],n[o].push(r),t},{inner:{},outer:{}}),r=t.inner,i=t.outer;r[0]=r[0]||[],r[0].unshift("videoElement"),i[0]=i[0]||[],i[0].unshift("container");var n=transObjectAttrIntoArray(r),o=transObjectAttrIntoArray(i);this.dom.setPluginsZIndex(n),this.dom.setPluginsZIndex(o),this.zIndexMap.inner=n,this.zIndexMap.outer=o}},{key:"_getTopLevel",value:function(e){var t=this.zIndexMap[e?"inner":"outer"],r=this.plugins[t[t.length-1]];return isEmpty(r)?0:r.$level}},{key:"_autoloadVideoSrcAtFirst",value:function(){if(this.videoConfig.autoload){if(!this.videoConfig.src)return void Log$1.warn("You have not set the src, so you better set autoload to be false. Accroding to https://github.com/Chimeejs/chimee/blob/master/doc/zh-cn/chimee-api.md#src.");this.bus.emit("load",this.videoConfig.src)}}},{key:"_changeUnwatchable",value:function(e,t,r){this.changeWatchable=!1,e[t]=r,this.changeWatchable=!0}},{key:"_createKernel",value:function(e,t){var r=t.kernels,i=t.preset,n={},o={};return isArray(r)&&(o=r.reduce(function(e,t){if(isString(t)){var r=kernelsSet[t];return isFunction(r)?(e[t]=r,e):(Log$1.warn("You have not installed kernel for "+t+"."),e)}if(isObject(t)){var i=t.name,o=t.handler;if(isString(o)){var a=kernelsSet[o];return isFunction(a)?(e[o]=a,n[o]=t,e):(Log$1.warn("You have not installed kernel for "+o+"."),e)}if(isFunction(o)){var s=i||o.name;return e[s]=o,n[s]=t,e}return Log$1.warn("When you pass in an SingleKernelConfig in Array, you must clarify it's handler, we only support handler in string or function but not "+(void 0===o?"undefined":_typeof(o))),e}return Log$1.warn("If you pass in kernels as array, you must pass in kernels in string or function, but not "+(void 0===t?"undefined":_typeof(t))),e},{})),isObject(r)&&_Object$keys(r).forEach(function(e){var t=r[e];if(!isFunction(t)){if(isObject(t)){var i=t.handler;if(isString(i)){var a=kernelsSet[i];return isFunction(a)?(o[e]=a,void(n[e]=t)):void Log$1.warn("You have not installed kernel for "+i+".")}return isFunction(i)?(o[e]=i,void(n[e]=t)):void Log$1.warn("When you pass in an SingleKernelConfig in Object, you must clarify it's handler, we only support handler in string or function but not "+(void 0===i?"undefined":_typeof(i)))}return Log$1.warn("If you pass in kernels as object, you must pass in kernels in string or function, but not "+(void 0===t?"undefined":_typeof(t))),r}o[e]=t}),t.preset=_Object$assign(o,i),t.presetConfig=n,new ChimeeKernel(e,t)}},{key:"_bindKernelEvents",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];kernelEvents$1.forEach(function(i,n){if(!r){var o=function(){for(var e,r=arguments.length,n=Array(r),o=0;o<r;o++)n[o]=arguments[o];return(e=t.bus).triggerSync.apply(e,[i].concat(_toConsumableArray(n)))};return e.on(i,o),void t.kernelEventHandlerList.push(o)}var a=t.kernelEventHandlerList[n];e.off(i,a)}),r?(this.kernelEventHandlerList=[],e.off("error",this.throwError)):e.on("error",this.throwError)}}],[{key:"install",value:function(e){var t=camelize(e.name);isEmpty(pluginConfigSet[t]);var r=isFunction(e)?e:deepAssign({id:t},e);return pluginConfigSet[t]=r,t}},{key:"hasInstalled",value:function(e){return!isEmpty(pluginConfigSet[e])}},{key:"uninstall",value:function(e){delete pluginConfigSet[e]}},{key:"getPluginConfig",value:function(e){return pluginConfigSet[e]}},{key:"installKernel",value:function(e,t){(isObject(e)?_Object$entries(e):[[e,t]]).forEach(function(e){var t=_slicedToArray(e,2),r=t[0],i=t[1];if(!isFunction(i))throw new Error("The kernel you install on "+r+" must be a Function, but not "+(void 0===i?"undefined":_typeof(i)));isFunction(kernelsSet[r])&&Log$1.warn("You have alrady install a kernel on "+r+", and now we will replace it"),kernelsSet[r]=i})}},{key:"uninstallKernel",value:function(e){delete kernelsSet[e]}},{key:"hasInstalledKernel",value:function(e){return isFunction(kernelsSet[e])}}]),e}(),_applyDecoratedDescriptor$4(_class$5.prototype,"unuse",[_dec$5],_Object$getOwnPropertyDescriptor(_class$5.prototype,"unuse"),_class$5.prototype),_applyDecoratedDescriptor$4(_class$5.prototype,"throwError",[autobind],_Object$getOwnPropertyDescriptor(_class$5.prototype,"throwError"),_class$5.prototype),_applyDecoratedDescriptor$4(_class$5,"install",[_dec2$4],_Object$getOwnPropertyDescriptor(_class$5,"install"),_class$5),_applyDecoratedDescriptor$4(_class$5,"hasInstalled",[_dec3$3],_Object$getOwnPropertyDescriptor(_class$5,"hasInstalled"),_class$5),_applyDecoratedDescriptor$4(_class$5,"uninstall",[_dec4$3],_Object$getOwnPropertyDescriptor(_class$5,"uninstall"),_class$5),_applyDecoratedDescriptor$4(_class$5,"getPluginConfig",[_dec5$2],_Object$getOwnPropertyDescriptor(_class$5,"getPluginConfig"),_class$5),_class$5),_class$6,_descriptor$1;function _initDefineProp$1(e,t,r,i){r&&_Object$defineProperty(e,t,{enumerable:r.enumerable,configurable:r.configurable,writable:r.writable,value:r.initializer?r.initializer.call(i):void 0})}function _applyDecoratedDescriptor$5(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var GlobalConfig=(_class$6=function(){function e(){_classCallCheck(this,e),this.log={error:!0,info:!0,warn:!0,debug:!0,verbose:!0},_initDefineProp$1(this,"_silent",_descriptor$1,this),this.errorHandler=void 0;var t=_Object$keys(this.log).reduce(function(e,t){return e[t]=accessor({get:function(){return Log$1["ENABLE_"+t.toUpperCase()]},set:function(e){return Log$1["ENABLE_"+t.toUpperCase()]=e,!0===e&&(this.silent=!1),e}}),e},{});applyDecorators(this.log,t,{self:!0})}return _createClass(e,[{key:"silent",get:function(){return this._silent},set:function(e){var t=this;e=!!e,this._silent=e,_Object$keys(this.log).forEach(function(r){t.log[r]=!e})}}]),e}(),_descriptor$1=_applyDecoratedDescriptor$5(_class$6.prototype,"_silent",[nonenumerable],{enumerable:!0,initializer:function(){return!1}}),_class$6),_dec$6,_class$7,_class2$1$1,_descriptor$2,_descriptor2$1,_descriptor3$1,_init,_init2,_init3,_init4,_init5,_init6,_init7,_init8,_init9,_class3,_temp;function _initDefineProp$2(e,t,r,i){r&&_Object$defineProperty(e,t,{enumerable:r.enumerable,configurable:r.configurable,writable:r.writable,value:r.initializer?r.initializer.call(i):void 0})}function _applyDecoratedDescriptor$6(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var Chimee=(_dec$6=autobindClass(),_dec$6((_temp=_class3=function(e){function t(e){_classCallCheck(this,t);var r=_possibleConstructorReturn(this,(t.__proto__||_Object$getPrototypeOf(t)).call(this));if(r.destroyed=!1,_initDefineProp$2(r,"__id",_descriptor$2,r),_initDefineProp$2(r,"version",_descriptor2$1,r),_initDefineProp$2(r,"config",_descriptor3$1,r),isString(e)||isElement(e))e={wrapper:e,controls:!0};else{if(!isObject(e))throw new Error("You must pass in an Object containing wrapper or string or element to new a Chimee");if(!e.wrapper)throw new Error("You must pass in an legal object")}return r.__dispatcher=new Dispatcher(e,r),r.ready=r.__dispatcher.ready,r.readySync=r.__dispatcher.readySync,r.__wrapAsVideo(r.__dispatcher.videoConfig),r}return _inherits(t,VideoWrapper),_createClass(t,[{key:"destroy",value:function(){_get(t.prototype.__proto__||_Object$getPrototypeOf(t.prototype),"__destroy",this).call(this),this.__dispatcher.destroy(),Object.defineProperty(this,"__dispatcher",{get:function(){throw new Error("This instance has been destroyed.")},enumerable:!0,configurable:!0}),this.destroyed=!0}},{key:"use",value:function(e){this.__dispatcher.use(e)}},{key:"unuse",value:function(e){this.__dispatcher.unuse(e)}},{key:"__throwError",value:function(e){isString(e)&&(e=new Error(e));var r=this.config.errorHandler||t.config.errorHandler;if(isFunction(r))return r(e);if(!t.config.silent){if(isError(e))throw e;console.error(e)}}}]),t}(),_class3.plugin=Plugin,_class3.config=new GlobalConfig,_class3.install=Dispatcher.install,_class3.uninstall=Dispatcher.uninstall,_class3.hasInstalled=Dispatcher.hasInstalled,_class3.installKernel=Dispatcher.installKernel,_class3.uninstallKernel=Dispatcher.uninstallKernel,_class3.hasInstalledKernel=Dispatcher.hasInstalledKernel,_class3.getPluginConfig=Dispatcher.getPluginConfig,_class2$1$1=_temp,_descriptor$2=_applyDecoratedDescriptor$6(_class2$1$1.prototype,"__id",[frozen],{enumerable:!0,initializer:function(){return"_vm"}}),_descriptor2$1=_applyDecoratedDescriptor$6(_class2$1$1.prototype,"version",[frozen],{enumerable:!0,initializer:function(){return"0.9.5"}}),_descriptor3$1=_applyDecoratedDescriptor$6(_class2$1$1.prototype,"config",[frozen],{enumerable:!0,initializer:function(){return{errorHandler:void 0}}}),_applyDecoratedDescriptor$6(_class2$1$1,"plugin",[frozen],(_init=_Object$getOwnPropertyDescriptor(_class2$1$1,"plugin"),_init=_init?_init.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return _init}}),_class2$1$1),_applyDecoratedDescriptor$6(_class2$1$1,"config",[frozen],(_init2=_Object$getOwnPropertyDescriptor(_class2$1$1,"config"),_init2=_init2?_init2.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return _init2}}),_class2$1$1),_applyDecoratedDescriptor$6(_class2$1$1,"install",[frozen],(_init3=_Object$getOwnPropertyDescriptor(_class2$1$1,"install"),_init3=_init3?_init3.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return _init3}}),_class2$1$1),_applyDecoratedDescriptor$6(_class2$1$1,"uninstall",[frozen],(_init4=_Object$getOwnPropertyDescriptor(_class2$1$1,"uninstall"),_init4=_init4?_init4.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return _init4}}),_class2$1$1),_applyDecoratedDescriptor$6(_class2$1$1,"hasInstalled",[frozen],(_init5=_Object$getOwnPropertyDescriptor(_class2$1$1,"hasInstalled"),_init5=_init5?_init5.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return _init5}}),_class2$1$1),_applyDecoratedDescriptor$6(_class2$1$1,"installKernel",[frozen],(_init6=_Object$getOwnPropertyDescriptor(_class2$1$1,"installKernel"),_init6=_init6?_init6.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return _init6}}),_class2$1$1),_applyDecoratedDescriptor$6(_class2$1$1,"uninstallKernel",[frozen],(_init7=_Object$getOwnPropertyDescriptor(_class2$1$1,"uninstallKernel"),_init7=_init7?_init7.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return _init7}}),_class2$1$1),_applyDecoratedDescriptor$6(_class2$1$1,"hasInstalledKernel",[frozen],(_init8=_Object$getOwnPropertyDescriptor(_class2$1$1,"hasInstalledKernel"),_init8=_init8?_init8.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return _init8}}),_class2$1$1),_applyDecoratedDescriptor$6(_class2$1$1,"getPluginConfig",[frozen],(_init9=_Object$getOwnPropertyDescriptor(_class2$1$1,"getPluginConfig"),_init9=_init9?_init9.value:void 0,{enumerable:!0,configurable:!0,writable:!0,initializer:function(){return _init9}}),_class2$1$1),_class$7=_class2$1$1))||_class$7);function __$styleInject(e,t){if("undefined"==typeof document)return t;e=e||"";var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");return i.type="text/css",r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e)),t}function unwrapExports$1(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function createCommonjsModule$1(e,t){return e(t={exports:{}},t.exports),t.exports}__$styleInject('container{position:relative}container,video{display:block;width:100%;height:100%;background:#000;outline:none}video:focus{outline:none}.chimee-flex-component svg:hover g,.chimee-flex-component svg g{fill:#fff;stroke:#fff}chimee-clarity-list,chimee-control-state-pause,chimee-control-state-play,chimee-progressbar-tip,chimee-screen-full,chimee-screen-small,chimee-volume-state-high,chimee-volume-state-low,chimee-volume-state-mute{display:none}chimee-control.full chimee-screen-full,chimee-control.pause chimee-control-state-pause,chimee-control.play chimee-control-state-play,chimee-control.small chimee-screen-small,chimee-volume.high chimee-volume-state-high,chimee-volume.low chimee-volume-state-low,chimee-volume.mute chimee-volume-state-mute{display:inline-block;width:1.4em;height:100%}chimee-control{display:block;height:100%;line-height:2em;font-size:14px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;overflow:hidden;font-family:Roboto,Arial,Helvetica,sans-serif;-webkit-transition:visibility .5s ease;transition:visibility .5s ease}chimee-control,chimee-control-wrap{position:absolute;bottom:0;left:0;width:100%}chimee-control-wrap{height:2.2em;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-flow:row nowrap;flex-flow:row nowrap;-webkit-box-pack:start;-ms-flex-pack:start;justify-content:flex-start;-webkit-box-align:start;-ms-flex-align:start;align-items:flex-start;background:rgba(0,0,0,.5);-webkit-transition:bottom .5s ease;transition:bottom .5s ease;pointer-events:auto}.chimee-flex-component{-webkit-box-ordinal-group:2;-ms-flex-order:1;order:1;-webkit-box-flex:0;-ms-flex-positive:0;flex-grow:0;height:2em;cursor:pointer}.chimee-flex-component svg{vertical-align:middle;width:2em;height:1.5em}chimee-control-state.chimee-flex-component{-ms-flex-preferred-size:3em;flex-basis:3em;text-align:right;margin-right:1em}chimee-control-state .left,chimee-control-state .right{-webkit-transition:d .2s ease-in-out;transition:d .2s ease-in-out}chimee-progresstime.chimee-flex-component{color:#fff;font-weight:400;text-align:center;white-space:nowrap}chimee-progresstime-pass,chimee-progresstime-total{display:inline}chimee-progressbar.chimee-flex-component{position:relative;-webkit-box-flex:1;-ms-flex-positive:1;flex-grow:1}chimee-progressbar-wrap{display:inline-block;height:100%;position:absolute;left:1em;right:1em;top:0}chimee-progressbar.progressbar-layout-top{position:static}chimee-progressbar.progressbar-layout-top chimee-progressbar-wrap{top:-1.6em;height:1.6em;left:0;right:0}chimee-progressbar.progressbar-layout-top .chimee-progressbar-line{left:0;top:.8em}.chimee-progressbar-line{position:absolute;top:.9em;left:0;display:inline-block;height:3px}chimee-progressbar-bg{width:100%;background:#4c4c4c}chimee-progressbar-buffer{width:0;background:#6f6f6f}chimee-progressbar-all{background:#de698c}chimee-progressbar-ball{content:"";position:absolute;right:-.8em;top:-.3em;display:inline-block;width:.8em;height:.8em;border-radius:.8em;background:#fff;pointer-events:none}chimee-progressbar-tip{position:absolute;bottom:.5em;top:-1.5em;left:0;z-index:1;padding:0 .5em;height:1.5em;background:#fff;line-height:1.5em;border-radius:4px;color:#000;text-align:center}chimee-volume.chimee-flex-component{cursor:pointer;padding:0;-ms-flex-preferred-size:7em;flex-basis:7em;white-space:nowrap;margin-right:1em;position:relative}chimee-volume.chimee-flex-component.vertical{padding-right:1em;-ms-flex-preferred-size:2em;flex-basis:2em}chimee-volume-state{display:inline-block;width:2em;vertical-align:top}chimee-volume .line,chimee-volume .ring1,chimee-volume .ring2{stroke-dasharray:150;stroke-dashoffset:150;-webkit-transition:stroke-dashoffset .7s ease-in-out;transition:stroke-dashoffset .7s ease-in-out}chimee-volume.high .ring1,chimee-volume.high .ring2,chimee-volume.low .ring2,chimee-volume.mute .line,chimee-volume.mute .ring1,chimee-volume.mute .ring2{stroke-dashoffset:0}chimee-volume.vertical:hover chimee-volume-bar{display:inline-block}chimee-volume.vertical chimee-volume-bar{position:absolute;top:-7em;left:-.2em;width:2em;height:4em;padding-bottom:3em;display:none;vertical-align:middle}chimee-volume.vertical chimee-volume-bar:before{content:"";position:absolute;left:0;right:0;top:0;bottom:1em;background:#212121;border-radius:4px}chimee-volume.vertical chimee-volume-bar-wrap{display:inline-block;position:absolute;bottom:1em;left:0;top:1em;right:0;height:4em}chimee-volume.vertical chimee-volume-bar-all,chimee-volume.vertical chimee-volume-bar-bg{position:absolute;bottom:0;left:1em;display:inline-block;width:2px;border-radius:4px}chimee-volume.vertical chimee-volume-bar-bg{height:4em;background:#4c4c4c;opacity:.5}chimee-volume.vertical chimee-volume-bar-all{background:#de698c}chimee-volume.vertical chimee-volume-bar-all:after{content:"";position:absolute;right:-.34em;top:-.4em;display:inline-block;width:.8em;height:.8em;border-radius:.8em;background:#fff;pointer-events:none}chimee-volume.horizonal chimee-volume-bar{position:relative;height:1.2em;width:4em;display:inline-block;vertical-align:middle}chimee-volume.horizonal chimee-volume-bar-all,chimee-volume.horizonal chimee-volume-bar-bg{position:absolute;top:.4em;left:0;display:inline-block;height:2px}chimee-volume.horizonal chimee-volume-bar-bg{width:4em;background:#4c4c4c;opacity:.5}chimee-volume.horizonal chimee-volume-bar-all{background:#de698c}chimee-volume.horizonal chimee-volume-bar-all:after{content:"";position:absolute;right:-.4em;top:-.3em;display:inline-block;width:.8em;height:.8em;border-radius:.8em;background:#fff;pointer-events:none}chimee-screen.chimee-flex-component{-ms-flex-preferred-size:3em;flex-basis:3em;text-align:left}chimee-clarity.chimee-flex-component{position:relative;color:#fff;width:6em;height:1.75em;padding:0;padding-right:1em;padding-left:1em;text-align:center;vertical-align:middle;font-size:16px}chimee-clarity.chimee-flex-component:hover chimee-clarity-list{display:inline-block}chimee-clarity.chimee-flex-component svg{width:auto;height:auto}chimee-clarity-list{position:absolute;left:0;bottom:1em;width:100%;padding-bottom:1.5em;opacity:.8;-webkit-box-sizing:content-box;box-sizing:content-box;line-height:0}chimee-clarity-list ul{margin:0;padding:.5em 0;background:#292929;line-height:2em}chimee-clarity-list li{list-style-type:none}chimee-clarity-list li.active,chimee-clarity-list li:hover{color:#de698c}chimee-clarity-list-arrow{position:absolute;bottom:1.5em;width:100%}',void 0);var _defined$1=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e},_toObject$1=function(e){return Object(_defined$1(e))},hasOwnProperty$2={}.hasOwnProperty,_has$2=function(e,t){return hasOwnProperty$2.call(e,t)},toString$2={}.toString,_cof$1=function(e){return toString$2.call(e).slice(8,-1)},_iobject$1=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==_cof$1(e)?e.split(""):Object(e)},_toIobject$1=function(e){return _iobject$1(_defined$1(e))},ceil$1=Math.ceil,floor$2=Math.floor,_toInteger$1=function(e){return isNaN(e=+e)?0:(e>0?floor$2:ceil$1)(e)},min$2=Math.min,_toLength$1=function(e){return e>0?min$2(_toInteger$1(e),9007199254740991):0},max$1=Math.max,min$1$1=Math.min,_toAbsoluteIndex$1=function(e,t){return(e=_toInteger$1(e))<0?max$1(e+t,0):min$1$1(e,t)},_arrayIncludes$1=function(e){return function(t,r,i){var n,o=_toIobject$1(t),a=_toLength$1(o.length),s=_toAbsoluteIndex$1(i,a);if(e&&r!=r){for(;a>s;)if((n=o[s++])!=n)return!0}else for(;a>s;s++)if((e||s in o)&&o[s]===r)return e||s||0;return!e&&-1}},_global$2=createCommonjsModule$1(function(e){var t=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=t)}),SHARED$1="__core-js_shared__",store$1=_global$2[SHARED$1]||(_global$2[SHARED$1]={}),_shared$1=function(e){return store$1[e]||(store$1[e]={})},id$3=0,px$2=Math.random(),_uid$2=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++id$3+px$2).toString(36))},shared$1=_shared$1("keys"),_sharedKey$1=function(e){return shared$1[e]||(shared$1[e]=_uid$2(e))},arrayIndexOf$1=_arrayIncludes$1(!1),IE_PROTO$3=_sharedKey$1("IE_PROTO"),_objectKeysInternal$1=function(e,t){var r,i=_toIobject$1(e),n=0,o=[];for(r in i)r!=IE_PROTO$3&&_has$2(i,r)&&o.push(r);for(;t.length>n;)_has$2(i,r=t[n++])&&(~arrayIndexOf$1(o,r)||o.push(r));return o},_enumBugKeys$1="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),_objectKeys$1=Object.keys||function(e){return _objectKeysInternal$1(e,_enumBugKeys$1)},_core$2=createCommonjsModule$1(function(e){var t=e.exports={version:"2.5.1"};"number"==typeof __e&&(__e=t)}),_aFunction$2=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e},_ctx$2=function(e,t,r){if(_aFunction$2(e),void 0===t)return e;switch(r){case 1:return function(r){return e.call(t,r)};case 2:return function(r,i){return e.call(t,r,i)};case 3:return function(r,i,n){return e.call(t,r,i,n)}}return function(){return e.apply(t,arguments)}},_isObject$2=function(e){return"object"==typeof e?null!==e:"function"==typeof e},_anObject$2=function(e){if(!_isObject$2(e))throw TypeError(e+" is not an object!");return e},_fails$2=function(e){try{return!!e()}catch(e){return!0}},_descriptors$2=!_fails$2(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),document$1$1=_global$2.document,is$2=_isObject$2(document$1$1)&&_isObject$2(document$1$1.createElement),_domCreate$2=function(e){return is$2?document$1$1.createElement(e):{}},_ie8DomDefine$2=!_descriptors$2&&!_fails$2(function(){return 7!=Object.defineProperty(_domCreate$2("div"),"a",{get:function(){return 7}}).a}),_toPrimitive$2=function(e,t){if(!_isObject$2(e))return e;var r,i;if(t&&"function"==typeof(r=e.toString)&&!_isObject$2(i=r.call(e)))return i;if("function"==typeof(r=e.valueOf)&&!_isObject$2(i=r.call(e)))return i;if(!t&&"function"==typeof(r=e.toString)&&!_isObject$2(i=r.call(e)))return i;throw TypeError("Can't convert object to primitive value")},dP$5=Object.defineProperty,f$9=_descriptors$2?Object.defineProperty:function(e,t,r){if(_anObject$2(e),t=_toPrimitive$2(t,!0),_anObject$2(r),_ie8DomDefine$2)try{return dP$5(e,t,r)}catch(e){}if("get"in r||"set"in r)throw TypeError("Accessors not supported!");return"value"in r&&(e[t]=r.value),e},_objectDp$2={f:f$9},_propertyDesc$2=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},_hide$2=_descriptors$2?function(e,t,r){return _objectDp$2.f(e,t,_propertyDesc$2(1,r))}:function(e,t,r){return e[t]=r,e},PROTOTYPE$4="prototype",$export$2=function(e,t,r){var i,n,o,a=e&$export$2.F,s=e&$export$2.G,u=e&$export$2.S,c=e&$export$2.P,l=e&$export$2.B,d=e&$export$2.W,f=s?_core$2:_core$2[t]||(_core$2[t]={}),h=f[PROTOTYPE$4],p=s?_global$2:u?_global$2[t]:(_global$2[t]||{})[PROTOTYPE$4];for(i in s&&(r=t),r)(n=!a&&p&&void 0!==p[i])&&i in f||(o=n?p[i]:r[i],f[i]=s&&"function"!=typeof p[i]?r[i]:l&&n?_ctx$2(o,_global$2):d&&p[i]==o?function(e){var t=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,r)}return new e(t,r,i)}return e.apply(this,arguments)};return t[PROTOTYPE$4]=e[PROTOTYPE$4],t}(o):c&&"function"==typeof o?_ctx$2(Function.call,o):o,c&&((f.virtual||(f.virtual={}))[i]=o,e&$export$2.R&&h&&!h[i]&&_hide$2(h,i,o)))};$export$2.F=1,$export$2.G=2,$export$2.S=4,$export$2.P=8,$export$2.B=16,$export$2.W=32,$export$2.U=64,$export$2.R=128;var _export$2=$export$2,_objectSap$1=function(e,t){var r=(_core$2.Object||{})[e]||Object[e],i={};i[e]=t(r),_export$2(_export$2.S+_export$2.F*_fails$2(function(){r(1)}),"Object",i)};_objectSap$1("keys",function(){return function(e){return _objectKeys$1(_toObject$1(e))}});var keys$1$1=_core$2.Object.keys,keys$2=createCommonjsModule$1(function(e){e.exports={default:keys$1$1,__esModule:!0}}),_Object$keys$1=unwrapExports$1(keys$2),IE_PROTO$1$1=_sharedKey$1("IE_PROTO"),ObjectProto$2=Object.prototype,_objectGpo$1=Object.getPrototypeOf||function(e){return e=_toObject$1(e),_has$2(e,IE_PROTO$1$1)?e[IE_PROTO$1$1]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?ObjectProto$2:null};_objectSap$1("getPrototypeOf",function(){return function(e){return _objectGpo$1(_toObject$1(e))}});var getPrototypeOf$1$1=_core$2.Object.getPrototypeOf,getPrototypeOf$2=createCommonjsModule$1(function(e){e.exports={default:getPrototypeOf$1$1,__esModule:!0}}),_Object$getPrototypeOf$1=unwrapExports$1(getPrototypeOf$2),classCallCheck$1=createCommonjsModule$1(function(e,t){t.__esModule=!0,t.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}}),_classCallCheck$1=unwrapExports$1(classCallCheck$1);_export$2(_export$2.S+_export$2.F*!_descriptors$2,"Object",{defineProperty:_objectDp$2.f});var $Object$4=_core$2.Object,defineProperty$2$2=function(e,t,r){return $Object$4.defineProperty(e,t,r)},defineProperty$7=createCommonjsModule$1(function(e){e.exports={default:defineProperty$2$2,__esModule:!0}});unwrapExports$1(defineProperty$7);var createClass$1=createCommonjsModule$1(function(e,t){t.__esModule=!0;var r,i=(r=defineProperty$7)&&r.__esModule?r:{default:r};t.default=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),(0,i.default)(e,n.key,n)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}()}),_createClass$1=unwrapExports$1(createClass$1),_stringAt$1=function(e){return function(t,r){var i,n,o=String(_defined$1(t)),a=_toInteger$1(r),s=o.length;return a<0||a>=s?e?"":void 0:(i=o.charCodeAt(a))<55296||i>56319||a+1===s||(n=o.charCodeAt(a+1))<56320||n>57343?e?o.charAt(a):i:e?o.slice(a,a+2):n-56320+(i-55296<<10)+65536}},_library$1=!0,_redefine$2=_hide$2,_iterators$1={},_objectDps$1=_descriptors$2?Object.defineProperties:function(e,t){_anObject$2(e);for(var r,i=_objectKeys$1(t),n=i.length,o=0;n>o;)_objectDp$2.f(e,r=i[o++],t[r]);return e},document$2$1=_global$2.document,_html$1=document$2$1&&document$2$1.documentElement,IE_PROTO$2$1=_sharedKey$1("IE_PROTO"),Empty$1=function(){},PROTOTYPE$1$1="prototype",createDict$1=function(){var e,t=_domCreate$2("iframe"),r=_enumBugKeys$1.length;for(t.style.display="none",_html$1.appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),createDict$1=e.F;r--;)delete createDict$1[PROTOTYPE$1$1][_enumBugKeys$1[r]];return createDict$1()},_objectCreate$1=Object.create||function(e,t){var r;return null!==e?(Empty$1[PROTOTYPE$1$1]=_anObject$2(e),r=new Empty$1,Empty$1[PROTOTYPE$1$1]=null,r[IE_PROTO$2$1]=e):r=createDict$1(),void 0===t?r:_objectDps$1(r,t)},_wks$1=createCommonjsModule$1(function(e){var t=_shared$1("wks"),r=_global$2.Symbol,i="function"==typeof r;(e.exports=function(e){return t[e]||(t[e]=i&&r[e]||(i?r:_uid$2)("Symbol."+e))}).store=t}),def$1=_objectDp$2.f,TAG$2=_wks$1("toStringTag"),_setToStringTag$1=function(e,t,r){e&&!_has$2(e=r?e:e.prototype,TAG$2)&&def$1(e,TAG$2,{configurable:!0,value:t})},IteratorPrototype$1={};_hide$2(IteratorPrototype$1,_wks$1("iterator"),function(){return this});var _iterCreate$1=function(e,t,r){e.prototype=_objectCreate$1(IteratorPrototype$1,{next:_propertyDesc$2(1,r)}),_setToStringTag$1(e,t+" Iterator")},ITERATOR$5=_wks$1("iterator"),BUGGY$1=!([].keys&&"next"in[].keys()),FF_ITERATOR$1="@@iterator",KEYS$1="keys",VALUES$1="values",returnThis$1=function(){return this},_iterDefine$1=function(e,t,r,i,n,o,a){_iterCreate$1(r,t,i);var s,u,c,l=function(e){if(!BUGGY$1&&e in p)return p[e];switch(e){case KEYS$1:case VALUES$1:return function(){return new r(this,e)}}return function(){return new r(this,e)}},d=t+" Iterator",f=n==VALUES$1,h=!1,p=e.prototype,m=p[ITERATOR$5]||p[FF_ITERATOR$1]||n&&p[n],v=m||l(n),g=n?f?l("entries"):v:void 0,y="Array"==t&&p.entries||m;if(y&&(c=_objectGpo$1(y.call(new e)))!==Object.prototype&&c.next&&(_setToStringTag$1(c,d,!0),_library$1||_has$2(c,ITERATOR$5)||_hide$2(c,ITERATOR$5,returnThis$1)),f&&m&&m.name!==VALUES$1&&(h=!0,v=function(){return m.call(this)}),_library$1&&!a||!BUGGY$1&&!h&&p[ITERATOR$5]||_hide$2(p,ITERATOR$5,v),_iterators$1[t]=v,_iterators$1[d]=returnThis$1,n)if(s={values:f?v:l(VALUES$1),keys:o?v:l(KEYS$1),entries:g},a)for(u in s)u in p||_redefine$2(p,u,s[u]);else _export$2(_export$2.P+_export$2.F*(BUGGY$1||h),t,s);return s},$at$1=_stringAt$1(!0);_iterDefine$1(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,r=this._i;return r>=t.length?{value:void 0,done:!0}:(e=$at$1(t,r),this._i+=e.length,{value:e,done:!1})});var _iterStep$1=function(e,t){return{value:t,done:!!e}},es6_array_iterator$1=_iterDefine$1(Array,"Array",function(e,t){this._t=_toIobject$1(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,r=this._i++;return!e||r>=e.length?(this._t=void 0,_iterStep$1(1)):_iterStep$1(0,"keys"==t?r:"values"==t?e[r]:[r,e[r]])},"values");_iterators$1.Arguments=_iterators$1.Array;for(var TO_STRING_TAG$1=_wks$1("toStringTag"),DOMIterables$1="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),i$1=0;i$1<DOMIterables$1.length;i$1++){var NAME$1=DOMIterables$1[i$1],Collection$1=_global$2[NAME$1],proto$1=Collection$1&&Collection$1.prototype;proto$1&&!proto$1[TO_STRING_TAG$1]&&_hide$2(proto$1,TO_STRING_TAG$1,NAME$1),_iterators$1[NAME$1]=_iterators$1.Array}var f$1$1=_wks$1,_wksExt$1={f:f$1$1},iterator$2$1=_wksExt$1.f("iterator"),iterator$3=createCommonjsModule$1(function(e){e.exports={default:iterator$2$1,__esModule:!0}});unwrapExports$1(iterator$3);var _meta$1=createCommonjsModule$1(function(e){var t=_uid$2("meta"),r=_objectDp$2.f,i=0,n=Object.isExtensible||function(){return!0},o=!_fails$2(function(){return n(Object.preventExtensions({}))}),a=function(e){r(e,t,{value:{i:"O"+ ++i,w:{}}})},s=e.exports={KEY:t,NEED:!1,fastKey:function(e,r){if(!_isObject$2(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!_has$2(e,t)){if(!n(e))return"F";if(!r)return"E";a(e)}return e[t].i},getWeak:function(e,r){if(!_has$2(e,t)){if(!n(e))return!0;if(!r)return!1;a(e)}return e[t].w},onFreeze:function(e){return o&&s.NEED&&n(e)&&!_has$2(e,t)&&a(e),e}}}),defineProperty$4$2=_objectDp$2.f,_wksDefine$1=function(e){var t=_core$2.Symbol||(_core$2.Symbol=_library$1?{}:_global$2.Symbol||{});"_"==e.charAt(0)||e in t||defineProperty$4$2(t,e,{value:_wksExt$1.f(e)})},f$2$1=Object.getOwnPropertySymbols,_objectGops$1={f:f$2$1},f$3$1={}.propertyIsEnumerable,_objectPie$1={f:f$3$1},_enumKeys$1=function(e){var t=_objectKeys$1(e),r=_objectGops$1.f;if(r)for(var i,n=r(e),o=_objectPie$1.f,a=0;n.length>a;)o.call(e,i=n[a++])&&t.push(i);return t},_isArray$1=Array.isArray||function(e){return"Array"==_cof$1(e)},hiddenKeys$1=_enumBugKeys$1.concat("length","prototype"),f$5$1=Object.getOwnPropertyNames||function(e){return _objectKeysInternal$1(e,hiddenKeys$1)},_objectGopn$1={f:f$5$1},gOPN$1$1=_objectGopn$1.f,toString$1$1={}.toString,windowNames$1="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],getWindowNames$1=function(e){try{return gOPN$1$1(e)}catch(e){return windowNames$1.slice()}},f$4$1=function(e){return windowNames$1&&"[object Window]"==toString$1$1.call(e)?getWindowNames$1(e):gOPN$1$1(_toIobject$1(e))},_objectGopnExt$1={f:f$4$1},gOPD$1$1=Object.getOwnPropertyDescriptor,f$6$1=_descriptors$2?gOPD$1$1:function(e,t){if(e=_toIobject$1(e),t=_toPrimitive$2(t,!0),_ie8DomDefine$2)try{return gOPD$1$1(e,t)}catch(e){}if(_has$2(e,t))return _propertyDesc$2(!_objectPie$1.f.call(e,t),e[t])},_objectGopd$1={f:f$6$1},META$1=_meta$1.KEY,gOPD$2=_objectGopd$1.f,dP$1$1=_objectDp$2.f,gOPN$2=_objectGopnExt$1.f,$Symbol$1=_global$2.Symbol,$JSON$2=_global$2.JSON,_stringify$1=$JSON$2&&$JSON$2.stringify,PROTOTYPE$2$1="prototype",HIDDEN$1=_wks$1("_hidden"),TO_PRIMITIVE$1=_wks$1("toPrimitive"),isEnum$2={}.propertyIsEnumerable,SymbolRegistry$1=_shared$1("symbol-registry"),AllSymbols$1=_shared$1("symbols"),OPSymbols$1=_shared$1("op-symbols"),ObjectProto$1$1=Object[PROTOTYPE$2$1],USE_NATIVE$2="function"==typeof $Symbol$1,QObject$1=_global$2.QObject,setter$1=!QObject$1||!QObject$1[PROTOTYPE$2$1]||!QObject$1[PROTOTYPE$2$1].findChild,setSymbolDesc$1=_descriptors$2&&_fails$2(function(){return 7!=_objectCreate$1(dP$1$1({},"a",{get:function(){return dP$1$1(this,"a",{value:7}).a}})).a})?function(e,t,r){var i=gOPD$2(ObjectProto$1$1,t);i&&delete ObjectProto$1$1[t],dP$1$1(e,t,r),i&&e!==ObjectProto$1$1&&dP$1$1(ObjectProto$1$1,t,i)}:dP$1$1,wrap$1=function(e){var t=AllSymbols$1[e]=_objectCreate$1($Symbol$1[PROTOTYPE$2$1]);return t._k=e,t},isSymbol$1=USE_NATIVE$2&&"symbol"==typeof $Symbol$1.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof $Symbol$1},$defineProperty$1=function(e,t,r){return e===ObjectProto$1$1&&$defineProperty$1(OPSymbols$1,t,r),_anObject$2(e),t=_toPrimitive$2(t,!0),_anObject$2(r),_has$2(AllSymbols$1,t)?(r.enumerable?(_has$2(e,HIDDEN$1)&&e[HIDDEN$1][t]&&(e[HIDDEN$1][t]=!1),r=_objectCreate$1(r,{enumerable:_propertyDesc$2(0,!1)})):(_has$2(e,HIDDEN$1)||dP$1$1(e,HIDDEN$1,_propertyDesc$2(1,{})),e[HIDDEN$1][t]=!0),setSymbolDesc$1(e,t,r)):dP$1$1(e,t,r)},$defineProperties$1=function(e,t){_anObject$2(e);for(var r,i=_enumKeys$1(t=_toIobject$1(t)),n=0,o=i.length;o>n;)$defineProperty$1(e,r=i[n++],t[r]);return e},$create$1=function(e,t){return void 0===t?_objectCreate$1(e):$defineProperties$1(_objectCreate$1(e),t)},$propertyIsEnumerable$1=function(e){var t=isEnum$2.call(this,e=_toPrimitive$2(e,!0));return!(this===ObjectProto$1$1&&_has$2(AllSymbols$1,e)&&!_has$2(OPSymbols$1,e))&&(!(t||!_has$2(this,e)||!_has$2(AllSymbols$1,e)||_has$2(this,HIDDEN$1)&&this[HIDDEN$1][e])||t)},$getOwnPropertyDescriptor$2=function(e,t){if(e=_toIobject$1(e),t=_toPrimitive$2(t,!0),e!==ObjectProto$1$1||!_has$2(AllSymbols$1,t)||_has$2(OPSymbols$1,t)){var r=gOPD$2(e,t);return!r||!_has$2(AllSymbols$1,t)||_has$2(e,HIDDEN$1)&&e[HIDDEN$1][t]||(r.enumerable=!0),r}},$getOwnPropertyNames$1=function(e){for(var t,r=gOPN$2(_toIobject$1(e)),i=[],n=0;r.length>n;)_has$2(AllSymbols$1,t=r[n++])||t==HIDDEN$1||t==META$1||i.push(t);return i},$getOwnPropertySymbols$1=function(e){for(var t,r=e===ObjectProto$1$1,i=gOPN$2(r?OPSymbols$1:_toIobject$1(e)),n=[],o=0;i.length>o;)!_has$2(AllSymbols$1,t=i[o++])||r&&!_has$2(ObjectProto$1$1,t)||n.push(AllSymbols$1[t]);return n};USE_NATIVE$2||($Symbol$1=function(){if(this instanceof $Symbol$1)throw TypeError("Symbol is not a constructor!");var e=_uid$2(arguments.length>0?arguments[0]:void 0),t=function(r){this===ObjectProto$1$1&&t.call(OPSymbols$1,r),_has$2(this,HIDDEN$1)&&_has$2(this[HIDDEN$1],e)&&(this[HIDDEN$1][e]=!1),setSymbolDesc$1(this,e,_propertyDesc$2(1,r))};return _descriptors$2&&setter$1&&setSymbolDesc$1(ObjectProto$1$1,e,{configurable:!0,set:t}),wrap$1(e)},_redefine$2($Symbol$1[PROTOTYPE$2$1],"toString",function(){return this._k}),_objectGopd$1.f=$getOwnPropertyDescriptor$2,_objectDp$2.f=$defineProperty$1,_objectGopn$1.f=_objectGopnExt$1.f=$getOwnPropertyNames$1,_objectPie$1.f=$propertyIsEnumerable$1,_objectGops$1.f=$getOwnPropertySymbols$1,_descriptors$2&&!_library$1&&_redefine$2(ObjectProto$1$1,"propertyIsEnumerable",$propertyIsEnumerable$1,!0),_wksExt$1.f=function(e){return wrap$1(_wks$1(e))}),_export$2(_export$2.G+_export$2.W+_export$2.F*!USE_NATIVE$2,{Symbol:$Symbol$1});for(var es6Symbols$1="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),j$1=0;es6Symbols$1.length>j$1;)_wks$1(es6Symbols$1[j$1++]);for(var wellKnownSymbols$1=_objectKeys$1(_wks$1.store),k$1=0;wellKnownSymbols$1.length>k$1;)_wksDefine$1(wellKnownSymbols$1[k$1++]);_export$2(_export$2.S+_export$2.F*!USE_NATIVE$2,"Symbol",{for:function(e){return _has$2(SymbolRegistry$1,e+="")?SymbolRegistry$1[e]:SymbolRegistry$1[e]=$Symbol$1(e)},keyFor:function(e){if(!isSymbol$1(e))throw TypeError(e+" is not a symbol!");for(var t in SymbolRegistry$1)if(SymbolRegistry$1[t]===e)return t},useSetter:function(){setter$1=!0},useSimple:function(){setter$1=!1}}),_export$2(_export$2.S+_export$2.F*!USE_NATIVE$2,"Object",{create:$create$1,defineProperty:$defineProperty$1,defineProperties:$defineProperties$1,getOwnPropertyDescriptor:$getOwnPropertyDescriptor$2,getOwnPropertyNames:$getOwnPropertyNames$1,getOwnPropertySymbols:$getOwnPropertySymbols$1}),$JSON$2&&_export$2(_export$2.S+_export$2.F*(!USE_NATIVE$2||_fails$2(function(){var e=$Symbol$1();return"[null]"!=_stringify$1([e])||"{}"!=_stringify$1({a:e})||"{}"!=_stringify$1(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!isSymbol$1(e)){for(var t,r,i=[e],n=1;arguments.length>n;)i.push(arguments[n++]);return"function"==typeof(t=i[1])&&(r=t),!r&&_isArray$1(t)||(t=function(e,t){if(r&&(t=r.call(this,e,t)),!isSymbol$1(t))return t}),i[1]=t,_stringify$1.apply($JSON$2,i)}}}),$Symbol$1[PROTOTYPE$2$1][TO_PRIMITIVE$1]||_hide$2($Symbol$1[PROTOTYPE$2$1],TO_PRIMITIVE$1,$Symbol$1[PROTOTYPE$2$1].valueOf),_setToStringTag$1($Symbol$1,"Symbol"),_setToStringTag$1(Math,"Math",!0),_setToStringTag$1(_global$2.JSON,"JSON",!0),_wksDefine$1("asyncIterator"),_wksDefine$1("observable");var symbol$2$1=_core$2.Symbol,symbol$3=createCommonjsModule$1(function(e){e.exports={default:symbol$2$1,__esModule:!0}});unwrapExports$1(symbol$3);var _typeof_1$1=createCommonjsModule$1(function(e,t){t.__esModule=!0;var r=o(iterator$3),i=o(symbol$3),n="function"==typeof i.default&&"symbol"==typeof r.default?function(e){return typeof e}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":typeof e};function o(e){return e&&e.__esModule?e:{default:e}}t.default="function"==typeof i.default&&"symbol"===n(r.default)?function(e){return void 0===e?"undefined":n(e)}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":void 0===e?"undefined":n(e)}});unwrapExports$1(_typeof_1$1);var possibleConstructorReturn$1=createCommonjsModule$1(function(e,t){t.__esModule=!0;var r,i=(r=_typeof_1$1)&&r.__esModule?r:{default:r};t.default=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==(void 0===t?"undefined":(0,i.default)(t))&&"function"!=typeof t?e:t}}),_possibleConstructorReturn$1=unwrapExports$1(possibleConstructorReturn$1),$getOwnPropertyDescriptor$1$1=_objectGopd$1.f;_objectSap$1("getOwnPropertyDescriptor",function(){return function(e,t){return $getOwnPropertyDescriptor$1$1(_toIobject$1(e),t)}});var $Object$1$1=_core$2.Object,getOwnPropertyDescriptor$1$2=function(e,t){return $Object$1$1.getOwnPropertyDescriptor(e,t)},getOwnPropertyDescriptor$4=createCommonjsModule$1(function(e){e.exports={default:getOwnPropertyDescriptor$1$2,__esModule:!0}}),_Object$getOwnPropertyDescriptor$1=unwrapExports$1(getOwnPropertyDescriptor$4),get$1=createCommonjsModule$1(function(e,t){t.__esModule=!0;var r=n(getPrototypeOf$2),i=n(getOwnPropertyDescriptor$4);function n(e){return e&&e.__esModule?e:{default:e}}t.default=function e(t,n,o){null===t&&(t=Function.prototype);var a=(0,i.default)(t,n);if(void 0===a){var s=(0,r.default)(t);return null===s?void 0:e(s,n,o)}if("value"in a)return a.value;var u=a.get;return void 0!==u?u.call(o):void 0}}),_get$1=unwrapExports$1(get$1),check$1=function(e,t){if(_anObject$2(e),!_isObject$2(t)&&null!==t)throw TypeError(t+": can't set as prototype!")},_setProto$1={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,r){try{(r=_ctx$2(Function.call,_objectGopd$1.f(Object.prototype,"__proto__").set,2))(e,[]),t=!(e instanceof Array)}catch(e){t=!0}return function(e,i){return check$1(e,i),t?e.__proto__=i:r(e,i),e}}({},!1):void 0),check:check$1};_export$2(_export$2.S,"Object",{setPrototypeOf:_setProto$1.set});var setPrototypeOf$2$1=_core$2.Object.setPrototypeOf,setPrototypeOf$3=createCommonjsModule$1(function(e){e.exports={default:setPrototypeOf$2$1,__esModule:!0}});unwrapExports$1(setPrototypeOf$3),_export$2(_export$2.S,"Object",{create:_objectCreate$1});var $Object$2$1=_core$2.Object,create$2=function(e,t){return $Object$2$1.create(e,t)},create$3=createCommonjsModule$1(function(e){e.exports={default:create$2,__esModule:!0}});unwrapExports$1(create$3);var inherits$1=createCommonjsModule$1(function(e,t){t.__esModule=!0;var r=o(setPrototypeOf$3),i=o(create$3),n=o(_typeof_1$1);function o(e){return e&&e.__esModule?e:{default:e}}t.default=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":(0,n.default)(t)));e.prototype=(0,i.default)(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(r.default?(0,r.default)(e,t):e.__proto__=t)}}),_inherits$1=unwrapExports$1(inherits$1),_iterCall$1=function(e,t,r,i){try{return i?t(_anObject$2(r)[0],r[1]):t(r)}catch(t){var n=e.return;throw void 0!==n&&_anObject$2(n.call(e)),t}},ITERATOR$1$1=_wks$1("iterator"),ArrayProto$1=Array.prototype,_isArrayIter$1=function(e){return void 0!==e&&(_iterators$1.Array===e||ArrayProto$1[ITERATOR$1$1]===e)},_createProperty$1=function(e,t,r){t in e?_objectDp$2.f(e,t,_propertyDesc$2(0,r)):e[t]=r},TAG$1$1=_wks$1("toStringTag"),ARG$1="Arguments"==_cof$1(function(){return arguments}()),tryGet$1=function(e,t){try{return e[t]}catch(e){}},_classof$1=function(e){var t,r,i;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=tryGet$1(t=Object(e),TAG$1$1))?r:ARG$1?_cof$1(t):"Object"==(i=_cof$1(t))&&"function"==typeof t.callee?"Arguments":i},ITERATOR$2$1=_wks$1("iterator"),core_getIteratorMethod$1=_core$2.getIteratorMethod=function(e){if(void 0!=e)return e[ITERATOR$2$1]||e["@@iterator"]||_iterators$1[_classof$1(e)]},ITERATOR$3$1=_wks$1("iterator"),SAFE_CLOSING$1=!1;try{var riter$1=[7][ITERATOR$3$1]();riter$1.return=function(){SAFE_CLOSING$1=!0}}catch(e){}var _iterDetect$1=function(e,t){if(!t&&!SAFE_CLOSING$1)return!1;var r=!1;try{var i=[7],n=i[ITERATOR$3$1]();n.next=function(){return{done:r=!0}},i[ITERATOR$3$1]=function(){return n},e(i)}catch(e){}return r};_export$2(_export$2.S+_export$2.F*!_iterDetect$1(function(e){}),"Array",{from:function(e){var t,r,i,n,o=_toObject$1(e),a="function"==typeof this?this:Array,s=arguments.length,u=s>1?arguments[1]:void 0,c=void 0!==u,l=0,d=core_getIteratorMethod$1(o);if(c&&(u=_ctx$2(u,s>2?arguments[2]:void 0,2)),void 0==d||a==Array&&_isArrayIter$1(d))for(r=new a(t=_toLength$1(o.length));t>l;l++)_createProperty$1(r,l,c?u(o[l],l):o[l]);else for(n=d.call(o),r=new a;!(i=n.next()).done;l++)_createProperty$1(r,l,c?_iterCall$1(n,u,[i.value,l],!0):i.value);return r.length=l,r}});var from$1$1=_core$2.Array.from,from$2=createCommonjsModule$1(function(e){e.exports={default:from$1$1,__esModule:!0}}),_Array$from$1=unwrapExports$1(from$2),toConsumableArray$1=createCommonjsModule$1(function(e,t){t.__esModule=!0;var r,i=(r=from$2)&&r.__esModule?r:{default:r};t.default=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return(0,i.default)(e)}}),_toConsumableArray$1=unwrapExports$1(toConsumableArray$1),floor$1$1=Math.floor,_isInteger$1=function(e){return!_isObject$2(e)&&isFinite(e)&&floor$1$1(e)===e};_export$2(_export$2.S,"Number",{isInteger:_isInteger$1});var isInteger$2$1=_core$2.Number.isInteger,isInteger$1$1=createCommonjsModule$1(function(e){e.exports={default:isInteger$2$1,__esModule:!0}});unwrapExports$1(isInteger$1$1);var _stringWs$1="\t\n\v\f\r \u2028\u2029\ufeff",space$1="["+_stringWs$1+"]",non$1="
",ltrim$1=RegExp("^"+space$1+space$1+"*"),rtrim$1=RegExp(space$1+space$1+"*$"),exporter$1=function(e,t,r){var i={},n=_fails$2(function(){return!!_stringWs$1[e]()||non$1[e]()!=non$1}),o=i[e]=n?t(trim$1):_stringWs$1[e];r&&(i[r]=o),_export$2(_export$2.P+_export$2.F*n,"String",i)},trim$1=exporter$1.trim=function(e,t){return e=String(_defined$1(e)),1&t&&(e=e.replace(ltrim$1,"")),2&t&&(e=e.replace(rtrim$1,"")),e},_stringTrim$1=exporter$1,$parseFloat$1=_global$2.parseFloat,$trim$1=_stringTrim$1.trim,_parseFloat$3=1/$parseFloat$1(_stringWs$1+"-0")!=-1/0?function(e){var t=$trim$1(String(e),3),r=$parseFloat$1(t);return 0===r&&"-"==t.charAt(0)?-0:r}:$parseFloat$1;_export$2(_export$2.S+_export$2.F*(Number.parseFloat!=_parseFloat$3),"Number",{parseFloat:_parseFloat$3});var _parseFloat$1$1=parseFloat,_parseFloat$4=createCommonjsModule$1(function(e){e.exports={default:_parseFloat$1$1,__esModule:!0}});function bind$2(e,t){return e.bind?e.bind(t):e.apply?function(){for(var r=arguments.length,i=Array(r),n=0;n<r;n++)i[n]=arguments[n];return e.apply(t,i)}:function(){for(var r=arguments.length,i=Array(r),n=0;n<r;n++)i[n]=arguments[n];return e.call.apply(e,[t].concat(_toConsumableArray$1(i)))}}unwrapExports$1(_parseFloat$4);var Base=function(){function e(t){_classCallCheck$1(this,e),this.parent=t}return _createClass$1(e,[{key:"create",value:function(){this.createEl(),this.addAllEvent()}},{key:"destroy",value:function(){this.removeAllEvent()}},{key:"createEl",value:function(){this.$dom=document.createElement(this.option.tag),this.$dom.innerHTML=this.option.html,this.parent.$wrap.appendChild(this.$dom)}},{key:"addAllEvent",value:function(){var e=this;this.option.defaultEvent&&_Object$keys$1(this.option.defaultEvent).forEach(function(t){var r=e.option.defaultEvent[t];e[r]=bind$2(e[r],e),addEvent(e.$dom,t,e[r],!1,!1)}),this.option.event&&_Object$keys$1(this.option.event).forEach(function(t){var r="__"+t;e[r]=bind$2(e.option.event[t],e),addEvent(e.$dom,t,e[r],!1,!1)})}},{key:"removeAllEvent",value:function(){var e=this;this.option.defaultEvent&&_Object$keys$1(this.option.defaultEvent).forEach(function(t){var r=e.option.defaultEvent[t];e[r]=bind$2(e[r],e),removeEvent(e.$dom,t,e[r],!1,!1)}),this.option.event&&_Object$keys$1(this.option.event).forEach(function(t){var r="__"+t;e[r]=bind$2(e.option.event[t],e),removeEvent(e.$dom,t,e[r],!1,!1)})}}]),e}(),Component=function(e){function t(e,r){_classCallCheck$1(this,t);var i=_possibleConstructorReturn$1(this,(t.__proto__||_Object$getPrototypeOf$1(t)).call(this,e));return i.option=r,i.init(),i}return _inherits$1(t,Base),_createClass$1(t,[{key:"init",value:function(){_get$1(t.prototype.__proto__||_Object$getPrototypeOf$1(t.prototype),"create",this).call(this),addClassName(this.$dom,"chimee-flex-component")}}]),t}(),defaultOption={tag:"chimee-control-state",html:"\n <chimee-control-state-play></chimee-control-state-play>\n <chimee-control-state-pause></chimee-control-state-pause>\n ",animate:{icon:'\n <svg viewBox="0 0 200 200" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n <g fill="#ffffff" stroke="#ffffff">\n <path class="left"></path>\n <path class="right"></path>\n </g>\n </svg>\n ',path:{play:{left:"M0.921875,0.265625L0.921875,197.074852L95.7890625,149L96.2929688,49Z",right:"M90.3142151,45.9315226L90.3142151,151.774115L201.600944,99.9938782L201.600944,98.0237571Z"},pause:{left:"M0.921875,1.265625L0.921875,198.074852L79.3611677,198.074852L79.3611677,0.258923126Z",right:"M126.921875,1.265625L126.921875,198.074852L205.361168,198.074852L205.361168,0.258923126Z"}}},defaultEvent:{click:"click"}},Play=function(e){function t(e,r){_classCallCheck$1(this,t);var i=_possibleConstructorReturn$1(this,(t.__proto__||_Object$getPrototypeOf$1(t)).call(this,e));return i.option=deepAssign(defaultOption,isObject(r)?r:{}),i.animate=!1,i.init(),i}return _inherits$1(t,Base),_createClass$1(t,[{key:"init",value:function(){_get$1(t.prototype.__proto__||_Object$getPrototypeOf$1(t.prototype),"create",this).call(this),this.$dom=$(this.$dom),this.$dom.addClass("chimee-flex-component"),this.option.icon&&this.option.icon.play&&this.option.icon.pause?(this.$play=this.$dom.find("chimee-control-state-play"),this.$pause=this.$dom.find("chimee-control-state-pause"),this.$play.html(this.option.icon.play),this.$pause.html(this.option.icon.pause)):this.option.bitmap||(this.animate=!0,this.option.animate.path=this.option.path?this.option.path:this.option.animate.path,this.$dom.html(this.option.animate.icon),this.$left=this.$dom.find(".left"),this.$right=this.$dom.find(".right")),this.changeState("pause")}},{key:"changeState",value:function(e){var t="play"===e?"pause":"play";this.state=e,addClassName(this.parent.$dom,t),removeClassName(this.parent.$dom,e),this.animate&&this.setPath(t)}},{key:"setPath",value:function(e){var t=this.option.animate.path;"play"===e?(this.$left.attr("d",t.play.left),this.$right.attr("d",t.play.right)):(this.$left.attr("d",t.pause.left),this.$right.attr("d",t.pause.right))}},{key:"click",value:function(e){var t="play"===this.state?"pause":"play";this.changeState(t),this.parent.$emit(t)}}]),t}(),_class$8;function _applyDecoratedDescriptor$7(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var defaultOption$1={tag:"chimee-volume",html:"\n <chimee-volume-state>\n <chimee-volume-state-mute></chimee-volume-state-mute>\n <chimee-volume-state-low></chimee-volume-state-low>\n <chimee-volume-state-high></chimee-volume-state-high>\n </chimee-volume-state>\n <chimee-volume-bar>\n <chimee-volume-bar-wrap>\n <chimee-volume-bar-bg></chimee-volume-bar-bg>\n <chimee-volume-bar-all>\n <chimee-volume-bar-ball></chimee-volume-bar-ball>\n </chimee-volume-bar-all>\n <chimee-volume-bar-track></chimee-volume-bar-track>\n </chimee-volume-bar-wrap>\n </chimee-volume-bar>\n ",animate:{icon:'\n <svg viewBox="0 0 107 101" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n <g class="volume">\n <polygon class="horn" points="0.403399942 30 27.3842118 30 56.8220589 2.84217094e-14 57.9139815 100 27.3842118 70 0.403399942 70"></polygon>\n <path class="ring1" d="M63,5.00975239 C69.037659,4.78612057 75.9178585,8.40856146 83.6405984,15.877075 C95.2247083,27.0798454 100,34.7975125 100,50.9608558 C100,67.1241991 95.3628694,73.7907482 83.6405984,83.8306724 C75.8257511,90.5239552 68.9455516,94.0320644 63,94.355" fill-opacity="0" stroke-width="10"></path>\n <path class="ring2" d="M65.2173913,29.4929195 C67.8779343,29.3931169 70.9097496,31.0097416 74.3128371,34.3427934 C79.4174684,39.3423712 81.5217391,42.7866154 81.5217391,50 C81.5217391,57.2133846 79.4783502,60.1885354 74.3128371,64.6691576 C70.8691617,67.656239 67.8373465,69.2218397 65.2173913,69.3659595" fill-opacity="0" stroke-width="10"></path>\n <path class="line" d="M4.19119202,3.65220497 L102,96" stroke-width="10"></path>\n </g>\n </svg>\n '},defaultEvent:{mousedown:"mousedown"}},getElementPath=function(e){var t=[];if(null===e)return t;for(t.push(e);null!==e.parentNode;)e=e.parentNode,t.push(e);return t},Volume=(_class$8=function(e){function t(e,r){_classCallCheck$1(this,t);var i=_possibleConstructorReturn$1(this,(t.__proto__||_Object$getPrototypeOf$1(t)).call(this,e));return i.parent.preVolume=0,i.option=deepAssign(defaultOption$1,isObject(r)?r:{}),i.init(),i}return _inherits$1(t,Base),_createClass$1(t,[{key:"init",value:function(){var e=this;_get$1(t.prototype.__proto__||_Object$getPrototypeOf$1(t.prototype),"create",this).call(this),this.$dom=$(this.$dom),this.$state=this.$dom.find("chimee-volume-state"),this.$bar=this.$dom.find("chimee-volume-bar"),this.$all=this.$dom.find("chimee-volume-bar-all"),this.$bg=this.$dom.find("chimee-volume-bar-bg"),this.layout="vertical"===this.option.layout?"vertical":"horizonal",this.option.icon&&this.option.icon.mute&&this.option.icon.low?(this.option.icon.high=this.option.icon.high||this.option.icon.low,this.$mute=this.$dom.find("chimee-volume-state-mute"),this.$low=this.$dom.find("chimee-volume-state-low"),this.$high=this.$dom.find("chimee-volume-state-high"),this.$mute.html(this.option.icon.mute),this.$low.html(this.option.icon.low),this.$high.html(this.option.icon.high)):this.option.bitmap||(this.animate=!0,this.$state.html(this.option.animate.icon)),this.$dom.addClass("chimee-flex-component "+this.layout),this.changeState(),this.watch_muted=this.parent.$watch("muted",function(t){e.update()})}},{key:"inited",value:function(){this.update()}},{key:"destroy",value:function(){this.watch_muted(),_get$1(t.prototype.__proto__||_Object$getPrototypeOf$1(t.prototype),"destroy",this).call(this)}},{key:"changeState",value:function(){this.parent.muted||0===this.parent.volume?this.state="mute":this.parent.volume>0&&this.parent.volume<=.5?this.state="low":this.parent.volume>.5&&this.parent.volume<=1&&(this.state="high"),this.$dom.removeClass("mute low high"),this.$dom.addClass(this.state)}},{key:"click",value:function(e){var t=e.path||getElementPath(e.target);return-1!==t.indexOf(this.$state[0])?(this.stateClick(e),"state"):-1!==t.indexOf(this.$bar[0])?(this.barClick(e),"bar"):"padding"}},{key:"stateClick",value:function(){if(this.parent.muted)this.parent.muted=!1;else{var e=this.parent.volume;this.parent.volume=0===e?this.parent.preVolume:0,this.parent.preVolume=e,this.changeState()}}},{key:"barClick",value:function(e){var t="vertical"===this.layout?1-e.offsetY/this.$bg[0].offsetHeight:e.offsetX/this.$bg[0].offsetWidth;this.parent.volume=t<0?0:t>1?1:t,this.update()}},{key:"mousedown",value:function(e){"bar"===this.click(e)&&(this.startX="vertical"===this.layout?e.clientY:e.clientX,this.startVolume=this.parent.volume,addEvent(window,"mousemove",this.draging),addEvent(window,"mouseup",this.dragEnd),addEvent(window,"contextmenu",this.dragEnd))}},{key:"update",value:function(){this.changeState();var e=this.parent.muted?0:this.parent.volume;"vertical"===this.layout?this.$all.css("height",100*e+"%"):this.$all.css("width",100*e+"%")}},{key:"draging",value:function(e){this.endX="vertical"===this.layout?e.clientY:e.clientX;var t="vertical"===this.layout?(this.startX-this.endX)/this.$bg[0].offsetHeight:(this.endX-this.startX)/this.$bg[0].offsetWidth,r=+(this.startVolume+t).toFixed(2);this.parent.volume=r<0?0:r>1?1:r,this.parent.muted=!1}},{key:"dragEnd",value:function(){this.startX=0,this.startVolume=0,removeEvent(window,"mousemove",this.draging),removeEvent(window,"mouseup",this.dragEnd),removeEvent(window,"contextmenu",this.dragEnd)}}]),t}(),_applyDecoratedDescriptor$7(_class$8.prototype,"draging",[autobind],_Object$getOwnPropertyDescriptor$1(_class$8.prototype,"draging"),_class$8.prototype),_applyDecoratedDescriptor$7(_class$8.prototype,"dragEnd",[autobind],_Object$getOwnPropertyDescriptor$1(_class$8.prototype,"dragEnd"),_class$8.prototype),_class$8),_class$1$2;function _applyDecoratedDescriptor$1$2(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var defaultOption$2={tag:"chimee-progressbar",html:'\n <chimee-progressbar-wrap>\n <chimee-progressbar-bg class="chimee-progressbar-line"></chimee-progressbar-bg>\n <chimee-progressbar-buffer class="chimee-progressbar-line"></chimee-progressbar-buffer>\n <chimee-progressbar-all class="chimee-progressbar-line">\n <chimee-progressbar-ball></chimee-progressbar-ball>\n </chimee-progressbar-all>\n <chimee-progressbar-tip></chimee-progressbar-tip>\n </chimee-progressbar-wrap>\n '},ProgressBar=(_class$1$2=function(e){function t(e,r){_classCallCheck$1(this,t);var i=_possibleConstructorReturn$1(this,(t.__proto__||_Object$getPrototypeOf$1(t)).call(this,e));return i.option=deepAssign(defaultOption$2,isObject(r)?r:{}),i.visiable=!1!==r,i.init(),i}return _inherits$1(t,Base),_createClass$1(t,[{key:"init",value:function(){_get$1(t.prototype.__proto__||_Object$getPrototypeOf$1(t.prototype),"create",this).call(this),this.$dom=$(this.$dom),this.$wrap=this.$dom.find("chimee-progressbar-wrap"),this.$buffer=this.$dom.find("chimee-progressbar-buffer"),this.$all=this.$dom.find("chimee-progressbar-all"),this.$tip=this.$dom.find("chimee-progressbar-tip"),this.$track=this.$dom.find("chimee-progressbar-track"),this.$line=this.$dom.find(".chimee-progressbar-line"),this.$ball=this.$dom.find("chimee-progressbar-ball"),this.$dom.addClass("chimee-flex-component"),!this.visiable&&this.$dom.css("visibility","hidden"),"top"===this.option.layout&&(this.$dom.addClass("progressbar-layout-top"),this.$wrap.css({top:-this.$ball[0].offsetHeight+"px"}),setStyle(this.parent.$wrap,"paddingTop",this.$ball[0].offsetHeight+"px")),this.addWrapEvent()}},{key:"destroy",value:function(){this.removeWrapEvent(),this.watch_screen&&this.watch_screen(),_get$1(t.prototype.__proto__||_Object$getPrototypeOf$1(t.prototype),"destroy",this).call(this)}},{key:"addWrapEvent",value:function(){this.$wrap.on("mousedown",this.mousedown),this.$wrap.on("mousemove",this.tipShow),this.$wrap.on("mouseleave",this.tipEnd)}},{key:"removeWrapEvent",value:function(){this.$wrap.off("mousedown",this.mousedown),this.$wrap.off("mousemove",this.tipShow),this.$wrap.off("mouseleave",this.tipEnd)}},{key:"progress",value:function(){var e=0;try{e=this.parent.buffered.end(0)}catch(e){}var t=e/this.parent.duration*100+"%";this.$buffer.css("width",t)}},{key:"update",value:function(){var e=void 0!==this._currentTime?this._currentTime:this.parent.currentTime,t=e?e/this.parent.duration:0;this.$all.css("width","calc("+100*t+"% - "+this.$ball[0].offsetWidth/2+"px")}},{key:"mousedown",value:function(e){e.target!==this.$tip[0]&&(this._currentTime=e.offsetX/this.$wrap[0].offsetWidth*this.parent.duration,this.startX=e.clientX,this.startTime=this._currentTime,addEvent(window,"mousemove",this.draging),addEvent(window,"mouseup",this.dragEnd),addEvent(window,"contextmenu",this.dragEnd))}},{key:"draging",value:function(e){this.endX=e.clientX;var t=(this.endX-this.startX)/this.$wrap[0].offsetWidth*this.parent.duration,r=+(this.startTime+t).toFixed(2);this._currentTime=r<0?0:r>this.parent.duration?this.parent.duration:r,this.update()}},{key:"dragEnd",value:function(){this.update(),this.startX=0,this.startTime=0,this.parent.currentTime=this._currentTime,this._currentTime=void 0,removeEvent(window,"mousemove",this.draging),removeEvent(window,"mouseup",this.dragEnd),removeEvent(window,"contextmenu",this.dragEnd)}},{key:"tipShow",value:function(e){if(e.target!==this.$tip[0]&&e.target!==this.$ball[0]){var t=e.offsetX/this.$wrap[0].offsetWidth*this.parent.duration,r=formatTime(t=t<0?0:t>this.parent.duration?this.parent.duration:t),i=e.offsetX-this.$tip[0].offsetWidth/2,n=this.$wrap[0].offsetWidth-this.$tip[0].offsetWidth;i=i<0?0:i>n?n:i,this.$tip.text(r),this.$tip.css("display","inline-block"),this.$tip.css("left",i+"px")}else this.$tip.css("display","none")}},{key:"tipEnd",value:function(){this.$tip.css("display","none")}}]),t}(),_applyDecoratedDescriptor$1$2(_class$1$2.prototype,"mousedown",[autobind],_Object$getOwnPropertyDescriptor$1(_class$1$2.prototype,"mousedown"),_class$1$2.prototype),_applyDecoratedDescriptor$1$2(_class$1$2.prototype,"draging",[autobind],_Object$getOwnPropertyDescriptor$1(_class$1$2.prototype,"draging"),_class$1$2.prototype),_applyDecoratedDescriptor$1$2(_class$1$2.prototype,"dragEnd",[autobind],_Object$getOwnPropertyDescriptor$1(_class$1$2.prototype,"dragEnd"),_class$1$2.prototype),_applyDecoratedDescriptor$1$2(_class$1$2.prototype,"tipShow",[autobind],_Object$getOwnPropertyDescriptor$1(_class$1$2.prototype,"tipShow"),_class$1$2.prototype),_applyDecoratedDescriptor$1$2(_class$1$2.prototype,"tipEnd",[autobind],_Object$getOwnPropertyDescriptor$1(_class$1$2.prototype,"tipEnd"),_class$1$2.prototype),_class$1$2),defaultOption$3={tag:"chimee-progresstime",html:"\n <chimee-progresstime-pass>00:00</chimee-progresstime-pass\n ><chimee-progresstime-total\n ><span>/</span\n ><chimee-progresstime-total-value>00:00</chimee-progresstime-total-value>\n </chimee-progresstime-total>\n "},ProgressTime=function(e){function t(e,r){_classCallCheck$1(this,t);var i=_possibleConstructorReturn$1(this,(t.__proto__||_Object$getPrototypeOf$1(t)).call(this,e));return i.option=deepAssign(defaultOption$3,isObject(r)?r:{}),i.init(),i}return _inherits$1(t,Base),_createClass$1(t,[{key:"init",value:function(){_get$1(t.prototype.__proto__||_Object$getPrototypeOf$1(t.prototype),"create",this).call(this),this.$dom=$(this.$dom),this.$total=this.$dom.find("chimee-progresstime-total-value"),this.$pass=this.$dom.find("chimee-progresstime-pass"),this.$dom.addClass("chimee-flex-component")}},{key:"updatePass",value:function(){this.$pass.text(formatTime(this.parent.currentTime))}},{key:"updateTotal",value:function(){this.$total.text(formatTime(this.parent.duration))}}]),t}(),_class$2$1;function _applyDecoratedDescriptor$2$1(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var defaultOption$4={tag:"chimee-screen",html:'\n <chimee-screen-full>\n <svg viewBox="0 0 67 66" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n \x3c!-- Generator: Sketch 43.1 (39012) - http://www.bohemiancoding.com/sketch --\x3e\n <desc>Created with Sketch.</desc>\n <defs></defs>\n <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">\n <g id="screen-small" transform="translate(33.756308, 32.621867) rotate(45.000000) translate(-33.756308, -32.621867) translate(18.756308, -10.378133)" fill="#FFFFFF">\n <polygon id="Path" transform="translate(14.967695, 66.389245) rotate(180.000000) translate(-14.967695, -66.389245) " points="11.5190786 46.9431778 11.7210093 70.7913773 0.565180527 70.7913773 15.4674455 85.8353125 29.3702096 70.7913773 18.5573247 70.7702156 18.5573247 46.9431778"></polygon>\n <polygon id="Path" points="11.5190786 0.274130278 11.7210093 24.1223298 0.565180527 24.1223298 15.4674455 39.1662649 29.3702096 24.1223298 18.5573247 24.1011681 18.5573247 0.274130278"></polygon>\n </g>\n </g>\n </svg>\n </chimee-screen-full>\n <chimee-screen-small>\n <svg viewBox="0 0 61 62" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n \x3c!-- Generator: Sketch 43.1 (39012) - http://www.bohemiancoding.com/sketch --\x3e\n <desc>Created with Sketch.</desc>\n <defs></defs>\n <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">\n <g id="Group" transform="translate(30.756308, 30.621867) rotate(45.000000) translate(-30.756308, -30.621867) translate(15.756308, -12.378133)" fill="#FFFFFF">\n <polygon id="Path" points="11.5190786 46.9431778 11.7210093 70.7913773 0.565180527 70.7913773 15.4674455 85.8353125 29.3702096 70.7913773 18.5573247 70.7702156 18.5573247 46.9431778"></polygon>\n <polygon id="Path" transform="translate(14.967695, 19.720198) rotate(180.000000) translate(-14.967695, -19.720198) " points="11.5190786 0.274130278 11.7210093 24.1223298 0.565180527 24.1223298 15.4674455 39.1662649 29.3702096 24.1223298 18.5573247 24.1011681 18.5573247 0.274130278"></polygon>\n </g>\n </g>\n </svg>\n </chimee-screen-small>\n ',defaultEvent:{click:"click"}},Screen=(_class$2$1=function(e){function t(e,r){_classCallCheck$1(this,t);var i=_possibleConstructorReturn$1(this,(t.__proto__||_Object$getPrototypeOf$1(t)).call(this,e));return i.state="small",i.option=deepAssign(defaultOption$4,isObject(r)?r:{}),i.init(),i}return _inherits$1(t,Base),_createClass$1(t,[{key:"init",value:function(){_get$1(t.prototype.__proto__||_Object$getPrototypeOf$1(t.prototype),"create",this).call(this),this.$dom=$(this.$dom),this.changeState(this.state),this.$dom.addClass("chimee-flex-component"),this.$full=this.$dom.find("chimee-screen-full"),this.$small=this.$dom.find("chimee-screen-small"),this.option.icon&&this.option.icon.full&&this.option.icon.small?(this.$full.html(this.option.icon.full),this.$small.html(this.option.icon.small)):this.option.bitmap&&(this.$full.html(""),this.$small.html(""))}},{key:"changeState",value:function(e){var t="small"===e?"full":"small";addClassName(this.parent.$dom,e),removeClassName(this.parent.$dom,t)}},{key:"click",value:function(){var e=!1;"small"===this.state?(this.state="full",e=!0):(this.state="small",e=!1),this.changeState(this.state),this.parent.$fullscreen(e,"container"),e?this.watch_screen=this.parent.$watch("isFullscreen",this.screenChange):this.watch_screen()}},{key:"screenChange",value:function(){this.parent.fullscreenElement&&(this.state="small",this.changeState("small"),this.parent.$fullscreen(!1,"container"))}}]),t}(),_applyDecoratedDescriptor$2$1(_class$2$1.prototype,"screenChange",[autobind],_Object$getOwnPropertyDescriptor$1(_class$2$1.prototype,"screenChange"),_class$2$1.prototype),_class$2$1),defaultOption$5={tag:"chimee-clarity",width:"2em",html:'\n <chimee-clarity-text></chimee-clarity-text>\n <chimee-clarity-list>\n <ul></ul>\n <div class="chimee-clarity-list-arrow">\n <svg viewBox="0 0 115 6" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n <g id="Group-3-Copy" fill="#57B0F6">\n <polygon id="Path-2" points="0.0205224145 0.0374249581 0.0205224145 2.12677903 53.9230712 2.12677903 57.1127727 5.3468462 60.2283558 2.12677903 113.820935 2.12677903 113.820935 0.0374249581"></polygon>\n </g>\n </svg>\n </div>\n </chimee-clarity-list>\n ',defaultEvent:{click:"click"},duration:10,increment:1},Clarity=function(e){function t(e,r){_classCallCheck$1(this,t);var i=_possibleConstructorReturn$1(this,(t.__proto__||_Object$getPrototypeOf$1(t)).call(this,e));return i.option=deepAssign(defaultOption$5,isObject(r)?r:{}),i.init(),i}return _inherits$1(t,Base),_createClass$1(t,[{key:"init",value:function(){_get$1(t.prototype.__proto__||_Object$getPrototypeOf$1(t.prototype),"create",this).call(this),addClassName(this.$dom,"chimee-flex-component"),this.$text=$(this.$dom).find("chimee-clarity-text"),this.$list=$(this.$dom).find("chimee-clarity-list"),this.$listUl=this.$list.find("ul"),this.option.width&&setStyle(this.$dom,"width",this.option.width),this.initTextList()}},{key:"initTextList",value:function(){var e=this;this.option.list.forEach(function(t){var r=$(document.createElement("li"));r.attr("data-url",t.src),r.text(t.name),t.src===e.parent.$videoConfig.src&&(e.$text.text(t.name),r.addClass("active")),e.$listUl.append(r)})}},{key:"click",value:function(e){var t=this,r=e.target;if("LI"===r.tagName){var i=r.getAttribute("data-url")||"";this.switchClarity(i).then(function(){t.loadOption=void 0,_Array$from$1(r.parentElement.children).map(function(e){removeClassName(e,"active")}),addClassName(e.target,"active"),t.$text.text(e.target.textContent)}).catch(function(e){console.warn(e)})}}},{key:"switchClarity",value:function(e){return this.loadOption&&(this.loadOption.abort=!0),this.loadOption={duration:this.option.duration,repeatTimes:3,immediate:!0,increment:this.option.increment},this.parent.$silentLoad(e,this.loadOption)}}]),t}();function hundleChildren(e){return e.$config.children?e.$config.children:e.isLive?{play:!0,progressTime:!1,progressBar:!1,volume:!0,screen:!0}:{play:!0,progressTime:!0,progressBar:!0,volume:!0,screen:!0}}function createChild(e){var t=e.config.children=hundleChildren(e),r={};return t?_Object$keys$1(t).forEach(function(i){switch(i){case"play":t.play&&(r.play=new Play(e,t.play));break;case"progressTime":t.progressTime&&(r.progressTime=new ProgressTime(e,t.progressTime));break;case"progressBar":r.progressBar=new ProgressBar(e,t.progressBar);break;case"volume":t.volume&&(r.volume=new Volume(e,t.volume));break;case"screen":t.screen&&(r.screen=new Screen(e,t.screen));break;case"clarity":t.clarity&&Array.isArray(t.clarity.list)&&(r.clarity=new Clarity(e,t.clarity));break;default:r[i]=new Component(e,t[i])}}):(r.play=new Play(e),r.progressTime=new ProgressTime(e),r.progressBar=new ProgressBar(e),r.volume=new Volume(e),r.screen=new Screen(e)),r}var majorColorStyle="\n .chimee-flex-component svg *{\n fill: majorColor;\n stroke: majorColor;\n }\n chimee-progressbar-all{\n background: majorColor;\n }\n chimee-volume.chimee-flex-component chimee-volume-bar-all{\n background: majorColor; \n }\n chimee-clarity-list li:hover,\n chimee-clarity-list li.active {\n color: majorColor;\n }\n",hoverColorStyle="\n .chimee-flex-component svg:hover *{\n fill: hoverColor;\n stroke: hoverColor;\n }\n",defaultConfig$1={hideBarTime:2e3,barShowByMouse:"move"},chimeeControl={name:"chimeeControl",el:"chimee-control",data:{children:{},show:!1,disabled:!0},level:99,operable:!1,penetrate:!1,create:function(){},init:function(e){e.controls&&(this.show=!0,e.controls=!1);var t=this;applyDecorators(e,{controls:accessor({get:function(){return t.show},set:function(e){return t.show=Boolean(e),t._display(),!1}},{preSet:!0})},{self:!0}),this.config=isObject(this.$config)?deepAssign(defaultConfig$1,this.$config):defaultConfig$1,this.config.hideBarTime="move"===this.config.barShowByMouse?this.config.hideBarTime:0,this.$dom.innerHTML="<chimee-control-wrap></chimee-control-wrap>",this.$wrap=this.$dom.querySelector("chimee-control-wrap"),this.children=createChild(this),this._setStyle()},destroy:function(){window.clearTimeout(this.timeId)},inited:function(){for(var e in this.children)this.children[e].inited&&this.children[e].inited()},events:{loadstart:function(){this._disable(!0)},canplay:function(){this._disable(!1)},play:function(){this.children.play&&this.children.play.changeState("play"),"move"===this.config.barShowByMouse&&this._hideItself()},pause:function(){this.children.play&&this.children.play.changeState("pause"),this._showItself()},c_mouseenter:function(){"move"!==this.config.barShowByMouse&&this._showItself()},c_mousemove:function(){this._mousemove()},c_mouseleave:function(){"move"!==this.config.barShowByMouse&&this._hideItself()},durationchange:function(){this.children.progressTime&&this.children.progressTime.updateTotal()},timeupdate:function(){this._progressUpdate()},progress:function(){this.children.progressBar&&this.children.progressBar.progress()},volumechange:function(){this.children.volume&&this.children.volume.update()},keydown:function(e){if(!this.disabled)switch(e.stopPropagation(),e.keyCode){case 32:e.preventDefault(),this.children.play&&this.children.play.click(e);break;case 37:e.preventDefault();var t=this.currentTime-10;this.currentTime=t<0?0:t,this._mousemove();break;case 39:e.preventDefault();var r=this.currentTime+10;this.currentTime=r>this.duration?this.duration:r,this._mousemove();break;case 38:e.preventDefault();var i=this.volume+.1;this.volume=i>1?1:i,this._mousemove();break;case 40:e.preventDefault();var n=this.volume-.1;this.volume=n<0?0:n,this._mousemove()}},click:function(e){var t=this,r=new Date,i=this.clickTime;this.clickTime=r,r-i<300?clearTimeout(this.clickTimeId):this.clickTimeId=setTimeout(function(){!t.disabled&&t.children.play&&t.children.play.click(e)},300)},dblclick:function(e){!this.disabled&&this.children.screen&&this.children.screen.click()}},methods:{_progressUpdate:function(){this.children.progressBar&&this.children.progressBar.update(),this.children.progressTime&&this.children.progressTime.updatePass()},_hideItself:function(){var e=this;window.clearTimeout(this.timeId),this.timeId=setTimeout(function(){var t=e.$wrap.offsetHeight;t=e.children.progressBar?e.children.progressBar.$wrap[0].offsetTop-t:-t,setStyle(e.$wrap,{bottom:t+"px"}),setStyle(e.$dom,{visibility:"hidden"})},this.config.hideBarTime)},_showItself:function(){window.clearTimeout(this.timeId),setStyle(this.$wrap,{bottom:"0"}),setStyle(this.$dom,{visibility:"visible"})},_display:function(){var e=this.show?"block":"none";setStyle(this.$dom,{display:e})},_mousemove:function(e){this.paused||"enter"===this.config.barShowByMouse||(this._showItself(),this._hideItself())},_disable:function(e){this.show&&(this.disabled=e,setStyle(this.$wrap,"pointerEvents",e?"none":"auto"))},_setStyle:function(){var e="";e+=this.config.majorColor?majorColorStyle.replace(/majorColor/g,this.config.majorColor):"",e+=this.config.hoverColor?hoverColorStyle.replace(/hoverColor/g,this.config.hoverColor):"";var t=document.createElement("style");t.setAttribute("type","text/css"),t.innerHTML=e,document.head.appendChild(t)}}};function __$styleInject$1(e,t){if("undefined"==typeof document)return t;e=e||"";var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");return i.type="text/css",r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e)),t}function popupFactory(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.tagName,r=void 0===t?"chimee-popup":t,i=e.className,n=e.name,o=void 0===n?"popup":n,a=e.html,s=e.title,u=void 0===s?"这是一个信息框":s,c=e.body,l=void 0===c?"这里是信息内容":c,d=e.offsetAttr,f=void 0===d?"left top":d,h=e.offset,p=void 0===h?"50% 50%":h,m=e.translate,v=void 0===m?"":m,g=e.width,y=e.height,_=e.level,b=e.init,w=e.inited,E=e.data,S=e.create,T=e.beforeCreate,O=e.destroy,A=e.events,k=e.computed,D=e.methods,I=void 0===D?{}:D,x=e.penetrate,C=void 0!==x&&x,M=e.operable,P=void 0===M||M,L=e.hide,R=void 0!==L&&L,N=e.opened,j=e.closed,F=e.autoFocus,B={html:a||"\n <cm-pp-close>×</cm-pp-close>\n "+(!1!==u?"<cm-pp-head>"+u+"</cm-pp-head>":"")+"\n "+(!1!==l?"<cm-pp-body>"+l+"</cm-pp-body>":"")+"\n ",closeSelector:"._close"};return{name:o,el:r,className:i,beforeCreate:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.events,r=e.methods,i=arguments[1];isObject(i)&&(isObject(i.events)&&deepAssign(t,i.events),isObject(i.methods)&&deepAssign(r,i.methods)),T&&T.apply(this,arguments)},create:function(){var e=isObject(this.$config)?deepAssign(B,this.$config):B;(this.$domWrap=$(this.$dom).css("display","none")).html(e.html).delegate("cm-pp-close, "+e.closeSelector,"click",this.close),this.width(g).height(y).offset(p).translate(v),this._hide=R;for(var t=arguments.length,r=Array(t),i=0;i<t;i++)r[i]=arguments[i];S&&S.apply(this,r),!this._hide&&this.open()},destroy:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];O&&O.apply(this,t),this.$domWrap.undelegate(this.$config.closeSelector,"click",this.close).remove()},level:_,init:b,inited:w,data:E,events:A,computed:k,penetrate:C,operable:P,autoFocus:F,methods:deepAssign({open:function(){if(this.destroyed)return this;this.$domWrap.css("display","block"),this._hide=!1;for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.$emit("popupOpen",t,this),isFunction(N)&&N.apply(this,t),this},close:function(){if(this.destroyed)return this;this.$domWrap.css("display","none"),this._hide=!0;for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.$emit("popupClose",t,this),isFunction(j)&&j.apply(this,t),this},width:function(e){return e&&this.$domWrap.css("width",e),this},height:function(e){return e&&this.$domWrap.css("height",e),this},offset:function(e){var t=(""+(e||"")).split(" "),r={};if(t.length>2)return["top","right","bottom","left"].forEach(function(e,i){t[i]&&(r[e]=t[i])}),this.$domWrap.css(r),this;var i=_slicedToArray(t,2),n=i[0],o=i[1];if(""===n)return this;var a=o||n,s=f.split(" ");r[s[0]]=n,r[s[1]]=a,this.$domWrap.css(r);var u=[];return"50%"===n&&u.push("-50%"),"50%"===a&&u.push("-50%"),u.length>0&&this.translate(u.join(" ")),this},translate:function(e){var t=(""+(e||"")).split(" "),r=_slicedToArray(t,2),i=r[0],n=r[1];return""!==i&&(this.$domWrap.css("transform","translate("+i+", "+(n||i)+")"),"transform"in document.createElement("a").style||!window.console||!window.console.warn||console.warn("[chimee-plugin-popup] 当前环境不支持CSS3的transform特性,Dom元素无法正常使用translate。")),this}},I)}}function __$styleInject$2(e,t){if("undefined"==typeof document)return t;e=e||"";var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");return i.type="text/css",r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e)),t}function popupFactory$1(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.tagName,r=void 0===t?"chimee-popup":t,i=e.className,n=e.name,o=void 0===n?"popup":n,a=e.html,s=e.title,u=void 0===s?"这是一个信息框":s,c=e.body,l=void 0===c?"这里是信息内容":c,d=e.offsetAttr,f=void 0===d?"left top":d,h=e.offset,p=void 0===h?"50% 50%":h,m=e.translate,v=void 0===m?"":m,g=e.width,y=e.height,_=e.level,b=e.init,w=e.inited,E=e.data,S=e.create,T=e.beforeCreate,O=e.destroy,A=e.events,k=e.computed,D=e.methods,I=void 0===D?{}:D,x=e.penetrate,C=void 0!==x&&x,M=e.operable,P=void 0===M||M,L=e.hide,R=void 0!==L&&L,N=e.opened,j=e.closed,F=e.autoFocus,B={html:a||"\n <cm-pp-close>×</cm-pp-close>\n "+(!1!==u?"<cm-pp-head>"+u+"</cm-pp-head>":"")+"\n "+(!1!==l?"<cm-pp-body>"+l+"</cm-pp-body>":"")+"\n ",closeSelector:"._close"};return{name:o,el:r,className:i,beforeCreate:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.events,r=e.methods,i=arguments[1];isObject(i)&&(isObject(i.events)&&deepAssign(t,i.events),isObject(i.methods)&&deepAssign(r,i.methods)),T&&T.apply(this,arguments)},create:function(){var e=isObject(this.$config)?deepAssign(B,this.$config):B;(this.$domWrap=$(this.$dom).css("display","none")).html(e.html).delegate("cm-pp-close, "+e.closeSelector,"click",this.close),this.width(g).height(y).offset(p).translate(v),this._hide=R;for(var t=arguments.length,r=Array(t),i=0;i<t;i++)r[i]=arguments[i];S&&S.apply(this,r),!this._hide&&this.open()},destroy:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];O&&O.apply(this,t),this.$domWrap.undelegate(this.$config.closeSelector,"click",this.close).remove()},level:_,init:b,inited:w,data:E,events:A,computed:k,penetrate:C,operable:P,autoFocus:F,methods:deepAssign({open:function(){if(this.destroyed)return this;this.$domWrap.css("display","block"),this._hide=!1;for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.$emit("popupOpen",t,this),isFunction(N)&&N.apply(this,t),this},close:function(){if(this.destroyed)return this;this.$domWrap.css("display","none"),this._hide=!0;for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.$emit("popupClose",t,this),isFunction(j)&&j.apply(this,t),this},width:function(e){return e&&this.$domWrap.css("width",e),this},height:function(e){return e&&this.$domWrap.css("height",e),this},offset:function(e){var t=(""+(e||"")).split(" "),r={};if(t.length>2)return["top","right","bottom","left"].forEach(function(e,i){t[i]&&"auto"!==t[i]&&(r[e]=t[i])}),this.$domWrap.css(r),this;var i=_slicedToArray(t,2),n=i[0],o=i[1];if(""===n)return this;var a=o||n,s=f.split(" ");r[s[0]]=n,r[s[1]]=a,this.$domWrap.css(r);var u=[];return"50%"===n&&u.push("-50%"),"50%"===a&&u.push("-50%"),u.length>0&&this.translate(u.join(" ")),this},translate:function(e){var t=(""+(e||"")).split(" "),r=_slicedToArray(t,2),i=r[0],n=r[1];return i&&this.$domWrap.css("transform","translate("+i+", "+(n||i)+")"),this}},I)}}function __$styleInject$3(e,t){if("undefined"==typeof document)return t;e=e||"";var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");return i.type="text/css",r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e)),t}__$styleInject$1("chimee-popup{position:absolute;color:#fff;background-color:rgba(88,88,88,.5);font-size:13px;font-family:sans-serif;border:1px solid hsla(0,0%,100%,.08);padding:3px}chimee-popup cm-pp-close{float:right;color:#fff;text-decoration:none;line-height:14px;text-shadow:0 0 1px #000;font-size:15px;padding:0 3px;cursor:pointer;opacity:.8}chimee-popup cm-pp-close:hover{opacity:1}chimee-popup cm-pp-body,chimee-popup cm-pp-head{display:block;padding:3px 3px 6px}chimee-popup cm-pp-head{font-weight:700;border-bottom:1px solid hsla(0,0%,100%,.18);padding:0 5px 4px;margin-bottom:5px}chimee-popup cm-pp-body{font-size:12px}",void 0),__$styleInject$2("chimee-popup{position:absolute;color:#fff;background-color:rgba(88,88,88,.5);font-size:13px;font-family:sans-serif;border:1px solid hsla(0,0%,100%,.08);padding:3px}chimee-popup cm-pp-close{float:right;color:#fff;text-decoration:none;line-height:14px;text-shadow:0 0 1px #000;font-size:15px;padding:0 3px;cursor:pointer;opacity:.8}chimee-popup cm-pp-close:hover{opacity:1}chimee-popup cm-pp-body,chimee-popup cm-pp-head{display:block;padding:3px 3px 6px}chimee-popup cm-pp-head{font-weight:700;border-bottom:1px solid hsla(0,0%,100%,.18);padding:0 5px 4px;margin-bottom:5px}chimee-popup cm-pp-body{font-size:12px}",void 0),__$styleInject$3("chimee-menu{position:absolute;color:#fff;background-color:rgba(37,37,37,.7);font-size:13px;font-family:sans-serif;border:1px solid hsla(0,0%,100%,.08);border-radius:2px;padding:2px;box-shadow:0 1px 4px rgba(0,0,0,.6)}chimee-menu ul{margin:0;padding:0;font-size:12px}chimee-menu li{cursor:pointer;padding:0 4px;line-height:24px;list-style:none;white-space:nowrap;margin:0;border:0;font-size:12px;font-weight:400}chimee-menu li:hover{background-color:hsla(0,0%,100%,.1)}chimee-menu li[disable]{opacity:.5;cursor:default}chimee-menu li a{color:#fff;text-decoration:none}chimee-menu li a:hover{color:#fff}",void 0);var logPopupOpenEvt="openLogPopup",contextmenuConf=popupFactory$1({tagName:"chimee-menu",name:"chimeeContextmenu",html:"<ul></ul>",offset:"0",hide:!0,data:{baseMenus:[{text:"查看日志",action:logPopupOpenEvt,hide:!0},{text:"Chimee {VERSION} © 360",url:"http://chimee.org",disable:!0}]},create:function(){var e=this,t=this.$config,r=t.baseMenus,i=t.menus;isArray(r)&&(this.baseMenus=r),this.updatemenu(i),this.$domWrap.on("click",this.clickHandler),this.$plugins.chimeeLog&&this.switchLogMenu(!1),this._doc=new this.$domWrap.constructor(document),this._doc_click=function(t){return e.close()},this._doc.on("click",this._doc_click)},destroy:function(){this._doc.off("click",this._doc_click)},opened:function(){this.$bumpToTop()},events:{contextmenu:function(e){var t=e.offsetX,r=e.offsetY,i=this.$dom.parentElement;if(isFunction(i.getBoundingClientRect)){var n=i.getBoundingClientRect();t=e.pageX-n.left-(document.documentElement.scrollLeft||document.body.scrollLeft||0),r=e.pageY-n.top-(document.documentElement.scrollTop||document.body.scrollTop||0)}this.offset(t+"px "+r+"px").open(e),e.preventDefault()},logPluginDestroy:function(){this.switchLogMenu(!0)},logPluginCreate:function(){this.switchLogMenu(!1)}},methods:{switchLogMenu:function(e){var t=this.baseMenus.find(function(e){return e.action===logPopupOpenEvt});t&&(t.hide=e,this.$domWrap.find('[data-action="'+logPopupOpenEvt+'"]').css("display",e?"none":""))},updatemenu:function(e){var t=this,r=[];isArray(e)&&(r=r.concat(e));var i=r.concat(this.baseMenus).map(function(e){var r=e.hide,i=e.disable,n=e.action,o=e.className,a=e.text,s=e.url,u=i?"disable":"",c=n?'data-action="'+n+'"':"",l=o?'class="'+o+'"':"",d=r?'style="display:none"':"",f=a.replace(/\{([^)]*)\}/g,function(e,r){return t[r]});return s&&(f='<a href="'+s+'" target="_blank">'+f+"</a>"),"<li "+u+" "+c+" "+l+" "+d+">"+f+"</li>"}).join("");this.$domWrap.find("ul").html(i)},clickHandler:function(e){var t=e.target;if(!t.disable){var r=t.dataset.action;r&&(this.$emit(r),isFunction(this[r])&&this[r](e)),this.close()}e.stopPropagation()}}});function __$styleInject$4(e,t){if("undefined"==typeof document)return t;e=e||"";var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");return i.type="text/css",r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e)),t}function popupFactory$2(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.tagName,r=void 0===t?"chimee-popup":t,i=e.className,n=e.name,o=void 0===n?"popup":n,a=e.html,s=e.title,u=void 0===s?"这是一个信息框":s,c=e.body,l=void 0===c?"这里是信息内容":c,d=e.offsetAttr,f=void 0===d?"left top":d,h=e.offset,p=void 0===h?"50% 50%":h,m=e.translate,v=void 0===m?"":m,g=e.width,y=e.height,_=e.level,b=e.init,w=e.inited,E=e.data,S=e.create,T=e.beforeCreate,O=e.destroy,A=e.events,k=e.computed,D=e.methods,I=void 0===D?{}:D,x=e.penetrate,C=void 0!==x&&x,M=e.operable,P=void 0===M||M,L=e.hide,R=void 0!==L&&L,N=e.opened,j=e.closed,F=e.autoFocus,B={html:a||"\n <cm-pp-close>×</cm-pp-close>\n "+(!1!==u?"<cm-pp-head>"+u+"</cm-pp-head>":"")+"\n "+(!1!==l?"<cm-pp-body>"+l+"</cm-pp-body>":"")+"\n ",closeSelector:"._close"};return{name:o,el:r,className:i,beforeCreate:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.events,r=e.methods,i=arguments[1];isObject(i)&&(isObject(i.events)&&deepAssign(t,i.events),isObject(i.methods)&&deepAssign(r,i.methods)),T&&T.apply(this,arguments)},create:function(){var e=isObject(this.$config)?deepAssign(B,this.$config):B;(this.$domWrap=$(this.$dom).css("display","none")).html(e.html).delegate("cm-pp-close, "+e.closeSelector,"click",this.close),this.width(g).height(y).offset(p).translate(v),this._hide=R;for(var t=arguments.length,r=Array(t),i=0;i<t;i++)r[i]=arguments[i];S&&S.apply(this,r),!this._hide&&this.open()},destroy:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];O&&O.apply(this,t),this.$domWrap.undelegate(this.$config.closeSelector,"click",this.close).remove()},level:_,init:b,inited:w,data:E,events:A,computed:k,penetrate:C,operable:P,autoFocus:F,methods:deepAssign({open:function(){if(this.destroyed)return this;this.$domWrap.css("display","block"),this._hide=!1;for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.$emit("popupOpen",t,this),isFunction(N)&&N.apply(this,t),this},close:function(){if(this.destroyed)return this;this.$domWrap.css("display","none"),this._hide=!0;for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.$emit("popupClose",t,this),isFunction(j)&&j.apply(this,t),this},width:function(e){return e&&this.$domWrap.css("width",e),this},height:function(e){return e&&this.$domWrap.css("height",e),this},offset:function(e){var t=(""+(e||"")).split(" "),r={};if(t.length>2)return["top","right","bottom","left"].forEach(function(e,i){t[i]&&"auto"!==t[i]&&(r[e]=t[i])}),this.$domWrap.css(r),this;var i=_slicedToArray(t,2),n=i[0],o=i[1];if(""===n)return this;var a=o||n,s=f.split(" ");r[s[0]]=n,r[s[1]]=a,this.$domWrap.css(r);var u=[];return"50%"===n&&u.push("-50%"),"50%"===a&&u.push("-50%"),u.length>0&&this.translate(u.join(" ")),this},translate:function(e){var t=(""+(e||"")).split(" "),r=_slicedToArray(t,2),i=r[0],n=r[1];return i&&this.$domWrap.css("transform","translate("+i+", "+(n||i)+")"),this}},I)}}function __$styleInject$5(e,t){if("undefined"==typeof document)return t;e=e||"";var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");return i.type="text/css",r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e)),t}__$styleInject$4("chimee-popup{position:absolute;color:#fff;background-color:rgba(88,88,88,.5);font-size:13px;font-family:sans-serif;border:1px solid hsla(0,0%,100%,.08);padding:3px}chimee-popup cm-pp-close{float:right;color:#fff;text-decoration:none;line-height:14px;text-shadow:0 0 1px #000;font-size:15px;padding:0 3px;cursor:pointer;opacity:.8}chimee-popup cm-pp-close:hover{opacity:1}chimee-popup cm-pp-body,chimee-popup cm-pp-head{display:block;padding:3px 3px 6px}chimee-popup cm-pp-head{font-weight:700;border-bottom:1px solid hsla(0,0%,100%,.18);padding:0 5px 4px;margin-bottom:5px}chimee-popup cm-pp-body{font-size:12px}",void 0),__$styleInject$5(".chimee-log{padding:2px;box-shadow:0 1px 4px rgba(0,0,0,.6)}.chimee-log label{margin-left:10px;font-weight:100;font-size:12px}.chimee-log label input{vertical-align:middle;display:inline;width:auto;padding:0;margin:0}.chimee-log vs-pp-body{padding:3px}.chimee-log textarea{display:block;width:100%;height:200px;margin:-3px;border:1px solid hsla(0,0%,100%,.5);background-color:hsla(0,0%,100%,.9)}",void 0);var pageLoadedTimestamp=(new Date).getTime().toString();setLocalStorage("_chimee_t",pageLoadedTimestamp);var supportLS=getLocalStorage("_chimee_t")===pageLoadedTimestamp,defaultEvents=function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];var i={};return t.forEach(function(e){i[e]=function(t){for(var r=this,i=arguments.length,n=Array(i>1?i-1:0),o=1;o<i;o++)n[o-1]=arguments[o];this.writeLog(t);var a=this.box,s=this.type,u=this.src,c=this._waiting_num,l=this.currentTime,d=this._is_seek,f=void 0!==d&&d,h=this._is_play,p=void 0!==h&&h,m=this.playingTimestamp,v=this.loadstartTimestamp,g=this.waitingTimestamp;switch(e){case"loadstart":this.sendLog(e,{box:a,type:s,src:u}),this._ls_timeout=setTimeout(function(){r.sendLog("timeout",{src:u})},this.timeoutDelay),this._total_waiting_time=0;break;case"seeking":this._is_seek=!0;break;case"play":this._is_play=!0;break;case"pause":this.sendLog(e,{src:u,currentTime:l});break;case"canplay":clearTimeout(this._ls_timeout);var y=this.canplayTimestamp;this.sendLog(e,{src:u,currentTime:l,waitingNum:c,waitingTime:y-(v||g||y)});break;case"playing":clearTimeout(this._ls_timeout);var _=m-(v||g||m);this._total_waiting_time+=_,this.sendLog(e,{src:u,waitingNum:c,currentTime:l,isSeek:f,isPlay:p,waitingTime:_}),this.loadstartTimestamp=0,this.waitingTimestamp=0,this._is_seek=!1,this._is_play=!1;break;case"ended":this.sendLog(e,{src:u,waitingNum:c,totalWaitingTime:this._total_waiting_time});break;case"waiting":this._waiting_num++,this.sendLog(e,{src:u,waitingNum:c,currentTime:l,isSeek:f,isPlay:p});break;case"error":this.sendLog(e,{src:u,args:n})}}}),i}("loadstart","abort","durationchange","loadedmetadata","loadeddata","progress","canplay","canplaythrough","pause","play","playing","emptied","ended","seeking","seeked","stalled","suspend","timeupdate","waiting","error"),index$1=popupFactory$2({name:"chimeeLog",className:"chimee-log",title:"日志信息"+(supportLS?'<label><input type="checkbox">下次自动打开</label>':""),body:"<textarea>Chimee logs:</textarea>",offset:"0",width:"400px",hide:!0,autoFocus:!1,logPostUrl:void 0,beforeCreate:function(e,t){isUrl(t.logPostUrl)&&(this.logPostUrl=t.logPostUrl),t.timeoutDelay&&(this.timeoutDelay=t.timeoutDelay)},create:function(){this.logBase.ver=this.VERSION;var e=this.$domWrap;if(this.$txtEl=e.find("textarea"),supportLS){var t="1"===getLocalStorage("auto_on");e.find('input[type="checkbox"]').on("change",function(e){setLocalStorage("auto_on",+this.checked)})[0].checked=t,this._hide=!t}this.writeLog({type:"ready"}),this.$emitSync("logPluginCreate")},destroy:function(){clearTimeout(this._ls_timeout),this.$emitSync("logPluginDestroy"),this.sendLog("destroy")},inited:function(){},closed:function(){this.$txtEl.text("")},opened:function(){this.$bumpToTop()},methods:{writeLog:function(e){var t=e.type;if(this[t+"Timestamp"]=+new Date,!this._hide){var r=void 0,i="write_"+t+"_log";if(this[i]){for(var n=arguments.length,o=Array(n>1?n-1:0),a=1;a<n;a++)o[a-1]=arguments[a];r=this[i](t,o)}var s=this.$txtEl.text()+"\n["+formatDate(new Date(this[t+"Timestamp"]),"yyyy-MM-dd hh:mm:ss.i")+"] "+t+" "+(void 0!==r?_JSON$stringify(r):""),u=this.$txtEl.text(s)[0];u.scrollTop=u.scrollHeight}},write_loadstart_log:function(e){return{box:this.box,type:this.type,src:this.src}},write_durationchange_log:function(){return{duration:this.duration}},write_timeupdate_log:function(){return{currentTime:this.currentTime}},send_inited_log:function(){var e=this.box,t=this.type,r=this.src,i=this.controls,n=this.loop;return{pro:location.protocol,box:e,type:t,src:r,ctrs:i,loop:n}},sendLog:function(e,t){var r=this.logPostUrl;if(r){var i=deepAssign(t||{},this.logBase),n="send_"+e+"_log";this[n]&&deepAssign(i,this[n](e,i)),deepAssign(i,{evt:e,_t:+new Date,_r:Math.random()});var o=[];_Object$keys(i).forEach(function(e){return o.push(encodeURIComponent(e)+"="+encodeURIComponent(i[e]))});var a=new Image;a.onload=a.onerror=function(e){a=null},a.src=r+"?"+o.join("&")}}},events:deepAssign(defaultEvents,{openLogPopup:function(){this.open()}}),data:{timeoutDelay:3e4,pageLoadedTimestamp:pageLoadedTimestamp,_waiting_num:0,_total_waiting_time:0,logBase:{uid:(uid=getLocalStorage("_chimee_uid"),uid||setLocalStorage("_chimee_uid",uid=uuid()),uid),ref:location.href}},computed:{type:function(){return this.$videoConfig.isLive?"live":"vod"}}}),uid;function genTraversalHandler$2(e){return function t(r,i,n){if(isArray(r)||isObject(r)){for(var o in i=isPrimitive(i)?isObject(r)?{}:[]:i,r)i[o]=t(r[o],i[o],o);return i}return e(r,i,n)}}var _deepAssign$2=genTraversalHandler$2(function(e){return e});function deepClone$2(e){if(isPrimitive(e))throw new TypeError("deepClone only accept non primitive type");return _deepAssign$2(e)}function deepAssign$2(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(t.length<2)throw new Error("deepAssign accept two and more argument");for(var i=t.length-1;i>-1;i--)if(isPrimitive(t[i]))throw new TypeError("deepAssign only accept non primitive type");var n=t.shift();return t.forEach(function(e){return _deepAssign$2(e,n)}),n}function camelize$2(e,t){return e.replace(/(^|[^a-zA-Z]+)([a-zA-Z])/g,function(e,r,i,n){return t||0!==n?i.toUpperCase():i.toLowerCase()})}function hypenate$2(e){return camelize$2(e).replace(/([A-Z])/g,function(e){return"-"+e.toLowerCase()})}function bind$3(e,t){return e.bind?e.bind(t):e.apply?function(){for(var r=arguments.length,i=Array(r),n=0;n<r;n++)i[n]=arguments[n];return e.apply(t,i)}:function(){for(var r=arguments.length,i=Array(r),n=0;n<r;n++)i[n]=arguments[n];return e.call.apply(e,[t].concat(_toConsumableArray(i)))}}function uuid$2(){return S4$2()+S4$2()+"-"+S4$2()+"-"+S4$2()+"-"+S4$2()+"-"+S4$2()+S4$2()+S4$2()}function S4$2(){return(65536*(1+Math.random())|0).toString(16).substring(1)}function rand$2(e){for(var t="";t.length<e;)t+=S4$2();return t.slice(0,e)}function getDeepProperty$2(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=r.throwError,n=void 0!==i&&i,o=r.backup;if(isString(t)&&(t=t.split(".")),!isArray(t))throw new TypeError("keys of getDeepProperty must be string or Array<string>");for(var a=[],s=e,u=0,c=t.length;u<c;u++){var l=t[u];if(isVoid(s)){if(n)throw new Error("obj"+(a.length>0?"."+a.join("."):" itself")+" is "+s);return o}s=s[l],a.push(l)}return s}var inBrowser$1="undefined"!=typeof window&&"[object Object]"!==Object.prototype.toString.call(window);function makeArray$1(e){return _Array$from(e)}function transObjectAttrIntoArray$1(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e,t){return+e-+t};return _Object$keys(e).sort(t).reduce(function(t,r){return t.concat(e[r])},[])}function runRejectableQueue$1(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return new _Promise(function(t,i){!function n(o){if(!(o>=e.length)){var a=isFunction(e[o])?e[o].apply(e,_toConsumableArray(r)):e[o];return!1===a?i("stop"):_Promise.resolve(a).then(function(){return n(o+1)}).catch(function(e){return i(e||"stop")})}t()}(0)})}function runStoppableQueue$1(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return function t(i){return i>=e.length||!1!==(isFunction(e[i])?e[i].apply(e,_toConsumableArray(r)):e[i])&&t(++i)}(0)}function setFrozenAttr(e,t,r){if(isPrimitive(e))throw TypeError("setFrozenAttr obj parameter can not be primitive type");if(!isString(t))throw TypeError("setFrozenAttr key parameter must be String");_Object$defineProperty(e,t,{value:r,configurable:!1,enumerable:!1,writable:!1})}function setAttrGetterAndSetter(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=r.get,n=r.set,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"__";if(isPrimitive(e))throw TypeError("setFrozenAttr obj parameter can not be primitive type");if(!isString(t))throw TypeError("setAttrGetterAndSetter key parameter must be String");var a=e[t];if(!isFunction(i)&&(_Object$defineProperty(e,o+t,{value:a,configurable:!0,writable:!0,enumerable:!1}),i=function(){return this[o+t]},n&&isFunction(n))){var s=n;n=function(){for(var e=arguments.length,r=Array(e),i=0;i<e;i++)r[i]=arguments[i];this[o+t]=s.call.apply(s,[this].concat(r))}}_Object$defineProperty(e,t,{get:i,set:n})}function checkContinuation$1(e,t,r){var i=e;if(t+r<i.length){for(;r--;)if(128!=(192&i[++t]))return!1;return!0}return!1}function decodeUTF8$1(e){for(var t=[],r=e,i=0,n=e.length;i<n;)if(r[i]<128)t.push(String.fromCharCode(r[i])),++i;else{if(r[i]<192);else if(r[i]<224){if(checkContinuation$1(r,i,1)){var o=(31&r[i])<<6|63&r[i+1];if(o>=128){t.push(String.fromCharCode(65535&o)),i+=2;continue}}}else if(r[i]<240){if(checkContinuation$1(r,i,2)){var a=(15&r[i])<<12|(63&r[i+1])<<6|63&r[i+2];if(a>=2048&&55296!=(63488&a)){t.push(String.fromCharCode(65535&a)),i+=3;continue}}}else if(r[i]<248&&checkContinuation$1(r,i,3)){var s=(7&r[i])<<18|(63&r[i+1])<<12|(63&r[i+2])<<6|63&r[i+3];if(s>65536&&s<1114112){s-=65536,t.push(String.fromCharCode(s>>>10|55296)),t.push(String.fromCharCode(1023&s|56320)),i+=4;continue}}t.push(String.fromCharCode(65533)),++i}return t.join("")}function debounce$1(e,t,r){var i=void 0,n=void 0,o=void 0,a=void 0,s=void 0,u=function u(){var c=new Date-a;c<t&&c>=0?i=setTimeout(u,t-c):(i=null,r||(s=e.apply(o,n),i||(o=n=null)))};return function(){o=this,n=arguments,a=new Date;var c=r&&!i;return i||(i=setTimeout(u,t)),c&&(s=e.apply(o,n),o=n=null),s}}function throttle$1(e,t,r,i){var n=void 0,o=void 0,a=void 0,s=null,u=0;r||(r={});var c=function(){u=!1===r.leading?0:new Date-0,s=null,a=e.apply(n,o),s||(n=o=null)};return t=t||0,function(){var l=new Date;u||!1!==r.leading||(u=l);var d=t-(l-u);return n=i||this,o=arguments,d<=0||d>t?(s&&(clearTimeout(s),s=null),u=l,a=e.apply(n,o),s||(n=o=null)):s||!1===r.trailing||(s=setTimeout(c,d)),a}}var raf$1=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||window.oRequestAnimationFrame||function(e){return setTimeout(e,17)},caf$1=window.cancelAnimationFrame||window.mozCancelAnimationFrame||window.webkitCancelAnimationFrame||window.webkitCancelRequestAnimationFrame||window.msCancelAnimationFrame||window.oCancelAnimationFrame||function(e){clearTimeout(e)};function strRepeat$1(e,t){var r=t,i=(e=""+(e||"")).length;return(((t=(t||i)-i)>0?e.repeat?"0".repeat(t):new Array(t+1).join("0"):"")+e).slice(0,r)}function formatTime$1(e){var t=Math.floor(e/3600);e=Math.floor(e%3600);var r=strRepeat$1(Math.floor(e/60),2),i=strRepeat$1(e=Math.floor(e%60),2);return t>=1?t+":"+r+":"+i:r+":"+i}function addTransMethod(e){setFrozenAttr(e,"trans",function(t){return e.__fns||setFrozenAttr(e,"__fns",{}),e.__fns[t]||(e.__fns[t]=function(){if(!isFunction(e[t]))throw TypeError("obj.trans(methodName) parameter must be Function");return e[t].apply(e,arguments)}),e.__fns[t]})}function appendCSS$1(e){var t=document,r=t.querySelector("style");if(!r){r=t.createElement("style");var i=t.querySelector("head");i&&i.appendChild(r)}return r.appendChild(t.createTextNode(e)),r}function formatDate$1(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new Date,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"yyyy-MM-dd hh:mm:ss.i",r=e.getFullYear().toString(),i={M:e.getMonth()+1,d:e.getDate(),h:e.getHours(),m:e.getMinutes(),s:e.getSeconds(),i:e.getMilliseconds()};t=t.replace(/(y+)/gi,function(e,t){return r.substr(4-Math.min(4,t.length))});var n=function(e){t=t.replace(new RegExp("("+e+"+)","g"),function(t,r){return(i[e]<10&&r.length>1?"0":"")+i[e]})};for(var o in i)n(o);return t}function getLocalStorage$1(e){try{return window.localStorage.getItem(e)}catch(r){try{var t=document.cookie.match(new RegExp("(^| )"+e+"=([^;]*)(;|$)"));return isArray(t)?unescape(t[2]):""}catch(e){return""}}}function setLocalStorage$1(e,t){try{window.localStorage.setItem(e,t)}catch(i){var r=new Date;r.setTime(r.getTime()+2592e7);try{document.cookie=e+"="+escape(t)+";expires="+r.toUTCString()+";path=/;"}catch(e){}}}var lib=Object.freeze({Log:Log$1,genTraversalHandler:genTraversalHandler$2,deepClone:deepClone$2,deepAssign:deepAssign$2,camelize:camelize$2,hypenate:hypenate$2,bind:bind$3,uuid:uuid$2,S4:S4$2,rand:rand$2,getDeepProperty:getDeepProperty$2,defined:defined,isVoid:isVoid,isArray:isArray,isFunction:isFunction,isObject:isObject,isNumber:isNumber,isNumeric:isNumeric,isInteger:isInteger$2,isEmpty:isEmpty,isEvent:isEvent,isBlob:isBlob,isFile:isFile,isDate:isDate,isString:isString,isBoolean:isBoolean,isPromise:isPromise,isPrimitive:isPrimitive,isUrl:isUrl,isNode:isNode$2,isElement:isElement,isChildNode:isChildNode,isPosterityNode:isPosterityNode,isHTMLString:isHTMLString,isError:isError,isRegExp:isRegExp,inBrowser:inBrowser$1,makeArray:makeArray$1,transObjectAttrIntoArray:transObjectAttrIntoArray$1,runRejectableQueue:runRejectableQueue$1,runStoppableQueue:runStoppableQueue$1,setFrozenAttr:setFrozenAttr,setAttrGetterAndSetter:setAttrGetterAndSetter,decodeUTF8:decodeUTF8$1,debounce:debounce$1,throttle:throttle$1,raf:raf$1,caf:caf$1,strRepeat:strRepeat$1,formatTime:formatTime$1,addTransMethod:addTransMethod,appendCSS:appendCSS$1,formatDate:formatDate$1,getLocalStorage:getLocalStorage$1,setLocalStorage:setLocalStorage$1,emitEventCache:emitEventCache,addEventCache:addEventCache,removeEventCache:removeEventCache,CustEvent:CustEvent,getAttr:getAttr,setAttr:setAttr,addClassName:addClassName,removeClassName:removeClassName,hasClassName:hasClassName,get supportsPassive(){return supportsPassive},removeEvent:removeEvent,addEvent:addEvent,addDelegate:addDelegate,removeDelegate:removeDelegate,getStyle:getStyle,setStyle:setStyle,query:query,removeEl:removeEl,findParents:findParents,NodeWrap:NodeWrap,$:$}),chimeeHelper=lib;function __$styleInject$6(e,t){if("undefined"==typeof document)return t;e=e||"";var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");return i.type="text/css",i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e)),r.appendChild(i),t}function _interopDefault$1(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var _slicedToArray$1=_interopDefault$1(slicedToArray);function popupFactory$3(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.tagName,r=void 0===t?"chimee-popup":t,i=e.className,n=e.name,o=void 0===n?"popup":n,a=e.html,s=e.title,u=void 0===s?"这是一个信息框":s,c=e.body,l=void 0===c?"这里是信息内容":c,d=e.offsetAttr,f=void 0===d?"left top":d,h=e.offset,p=void 0===h?"50% 50%":h,m=e.translate,v=void 0===m?"":m,g=e.width,y=e.height,_=e.level,b=e.init,w=e.inited,E=e.data,S=e.create,T=e.beforeCreate,O=e.destroy,A=e.events,$=e.computed,k=e.methods,D=void 0===k?{}:k,I=e.penetrate,x=void 0!==I&&I,C=e.operable,M=void 0===C||C,P=e.hide,L=void 0!==P&&P,R=e.opened,N=e.closed,j=e.autoFocus,F={html:a||"\n <cm-pp-close>×</cm-pp-close>\n "+(!1!==u?"<cm-pp-head>"+u+"</cm-pp-head>":"")+"\n "+(!1!==l?"<cm-pp-body>"+l+"</cm-pp-body>":"")+"\n ",closeSelector:"._close"};return{name:o,el:r,className:i,beforeCreate:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.events,r=e.methods,i=arguments[1];chimeeHelper.isObject(i)&&(chimeeHelper.isObject(i.events)&&chimeeHelper.deepAssign(t,i.events),chimeeHelper.isObject(i.methods)&&chimeeHelper.deepAssign(r,i.methods)),T&&T.apply(this,arguments)},create:function(){var e=chimeeHelper.isObject(this.$config)?chimeeHelper.deepAssign(F,this.$config):F;(this.$domWrap=chimeeHelper.$(this.$dom).css("display","none")).html(e.html).delegate("cm-pp-close, "+e.closeSelector,"click",this.close),this.width(g).height(y).offset(p).translate(v),this._hide=L;for(var t=arguments.length,r=Array(t),i=0;i<t;i++)r[i]=arguments[i];S&&S.apply(this,r),!this._hide&&this.open()},destroy:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];O&&O.apply(this,t),this.$domWrap.undelegate(this.$config.closeSelector,"click",this.close).remove()},level:_,init:b,inited:w,data:E,events:A,computed:$,penetrate:x,operable:M,autoFocus:j,methods:chimeeHelper.deepAssign({open:function(){if(this.destroyed)return this;this.$domWrap.css("display","block"),this._hide=!1;for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.$emit("popupOpen",t,this),chimeeHelper.isFunction(R)&&R.apply(this,t),this},close:function(){if(this.destroyed)return this;this.$domWrap.css("display","none"),this._hide=!0;for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.$emit("popupClose",t,this),chimeeHelper.isFunction(N)&&N.apply(this,t),this},width:function(e){return e&&this.$domWrap.css("width",e),this},height:function(e){return e&&this.$domWrap.css("height",e),this},offset:function(e){var t=(""+(e||"")).split(" "),r={};if(t.length>2)return["top","right","bottom","left"].forEach(function(e,i){t[i]&&"auto"!==t[i]&&(r[e]=t[i])}),this.$domWrap.css(r),this;var i=_slicedToArray$1(t,2),n=i[0],o=i[1];if(""===n)return this;var a=o||n,s=f.split(" ");r[s[0]]=n,r[s[1]]=a,this.$domWrap.css(r);var u=[];return"50%"===n&&u.push("-50%"),"50%"===a&&u.push("-50%"),u.length>0&&this.translate(u.join(" ")),this},translate:function(e){var t=(""+(e||"")).split(" "),r=_slicedToArray$1(t,2),i=r[0],n=r[1];return i&&this.$domWrap.css("transform","translate("+i+", "+(n||i)+")"),this}},D)}}__$styleInject$6("chimee-popup{position:absolute;color:#fff;background-color:rgba(88,88,88,.5);font-size:13px;font-family:sans-serif;border:1px solid hsla(0,0%,100%,.08);padding:3px}chimee-popup cm-pp-close{float:right;color:#fff;text-decoration:none;opacity:.8;line-height:14px;text-shadow:0 0 1px #000;font-size:15px;padding:0 3px;cursor:pointer}chimee-popup cm-pp-close:hover{opacity:1}chimee-popup cm-pp-body,chimee-popup cm-pp-head{display:block;padding:3px 3px 6px}chimee-popup cm-pp-head{font-weight:700;border-bottom:1px solid hsla(0,0%,100%,.18);padding:0 5px 4px;margin-bottom:5px}chimee-popup cm-pp-body{font-size:12px}",void 0);var lib$1=popupFactory$3;function __$styleInject$7(e,t){if("undefined"==typeof document)return t;e=e||"";var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");return i.type="text/css",r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e)),t}__$styleInject$7('chimee-center-state{position:absolute}@keyframes a{0%{opacity:1}to{transform:scale(2);opacity:0}}@keyframes b{0%{transform:rotate(0)}to{transform:rotate(1turn)}}chimee-center-state-correct,chimee-center-state-error,chimee-center-state-loading,chimee-center-state-tip{display:none}chimee-center-state.correct chimee-center-state-correct,chimee-center-state.error chimee-center-state-error,chimee-center-state.loading chimee-center-state-loading,chimee-center-state.tip chimee-center-state-tip{display:inline-block}chimee-center-state-correct{width:104px;height:104px}chimee-center-state-tip{position:absolute;left:26px;bottom:26px;width:52px;height:52px;border-radius:26px;background:rgba(0,0,0,.5);animation:a .5s linear 1 normal forwards}chimee-center-state.play span{background-image:url("data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjQycHgiIGhlaWdodD0iNTFweCIgdmlld0JveD0iMCAwIDQyIDUxIiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCA0My4xICgzOTAxMikgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+CiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxwb2x5Z29uIGlkPSJUcmlhbmdsZSIgZmlsbD0iI0ZGRkZGRiIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMjEuMDAwMDAwLCAyNS41MDAwMDApIHJvdGF0ZSg5MC4wMDAwMDApIHRyYW5zbGF0ZSgtMjEuMDAwMDAwLCAtMjUuNTAwMDAwKSAiIHBvaW50cz0iMjEgNSA0NiA0NiAtNCA0NiI+PC9wb2x5Z29uPgogICAgPC9nPgo8L3N2Zz4=")}chimee-center-state.pause span{background-image:url("data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjUwcHgiIGhlaWdodD0iNTBweCIgdmlld0JveD0iMCAwIDUwIDUwIiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCA0My4xICgzOTAxMikgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+CiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUiIGZpbGw9IiNGRkZGRkYiIHg9IjAiIHk9IjAiIHdpZHRoPSIyMCIgaGVpZ2h0PSI1MCI+PC9yZWN0PgogICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUiIGZpbGw9IiNGRkZGRkYiIHg9IjMwIiB5PSIwIiB3aWR0aD0iMjAiIGhlaWdodD0iNTAiPjwvcmVjdD4KICAgIDwvZz4KPC9zdmc+")}chimee-center-state.back span{background-image:url("data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjczMXB4IiBoZWlnaHQ9Ijg4NHB4IiB2aWV3Qm94PSIwIDAgNzMxIDg4NCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj4KICAgIDwhLS0gR2VuZXJhdG9yOiBTa2V0Y2ggNDQuMSAoNDE0NTUpIC0gaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoIC0tPgogICAgPGRlc2M+Q3JlYXRlZCB3aXRoIFNrZXRjaC48L2Rlc2M+CiAgICA8ZGVmcz48L2RlZnM+CiAgICA8ZyBpZD0iUGFnZS0xIiBzdHJva2U9IiNmZmZmZmYiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4KICAgICAgICA8ZyBpZD0iNzcxLeWNlee6v++8jOWIt+aWsCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMzY1LjUwMDAwMCwgNDQyLjAwMDAwMCkgc2NhbGUoLTEsIDEpIHRyYW5zbGF0ZSgtMzY1LjUwMDAwMCwgLTQ0Mi4wMDAwMDApICIgZmlsbC1ydWxlPSJub256ZXJvIiBmaWxsPSIjZmZmZmZmIj4KICAgICAgICAgICAgPHBhdGggZD0iTTcwNS4xMTg1NTgsNDkyLjQxNDIwMyBDNjkwLjk4OTc2OSw0OTIuNDE0MjAzIDY3OS41MzU5MDMsNTAzLjg2ODA2OSA2NzkuNTM1OTAzLDUxNy45OTY4NTggQzY3OS41MzU5MDMsNjkxLjA2MDQ0OSA1MzguNzM3MTU3LDgzMS44NTkxOTUgMzY1LjY3MzU2Niw4MzEuODU5MTk1IEMxOTIuNjA4OTUyLDgzMS44NTkxOTUgNTEuODEyMjUyLDY5MS4wNjA0NDkgNTEuODEyMjUyLDUxNy45OTY4NTggQzUxLjgxMjI1MiwzNTUuMDM4NDE2IDE3Ni42NTI1MzgsMjIwLjcwNjk2NSAzMzUuNzE0MjMsMjA1LjU3MzI4OSBMMjIzLjYwMDgwMywzMTcuNjg2NzE2IEMyMTMuNjEwMjY1LDMyNy42NzcyNTQgMjEzLjYxMDI2NSwzNDMuODc1MTY4IDIyMy42MDA4MDMsMzUzLjg2NTcwNyBDMjI4LjU5NjU4NCwzNTguODYwNDY1IDIzNS4xNDM2OTcsMzYxLjM1ODM1NSAyNDEuNjkwODEsMzYxLjM1ODM1NSBDMjQ4LjIzNzkyMywzNjEuMzU4MzU1IDI1NC43ODUwMzYsMzU4Ljg2MDQ2NSAyNTkuNzgwODE3LDM1My44NjU3MDcgTDQxNC43MzcwMDUsMTk4LjkwOTUxOSBDNDI0LjcyNzU0MywxODguOTE4OTgxIDQyNC43Mjc1NDMsMTcyLjcyMTA2NyA0MTQuNzM3MDA1LDE2Mi43MzA1MjggTDI1OS43Nzk3OTMsNy43NzQzNDEgQzI0OS43ODgyMzEsLTIuMjE2MTk3IDIzMy41OTEzNDEsLTIuMjE2MTk3IDIyMy42MDA4MDIsNy43NzQzNDEgQzIxMy42MTAyNjQsMTcuNzY0ODc5IDIxMy42MTAyNjQsMzMuOTYyNzkzIDIyMy42MDA4MDIsNDMuOTUzMzMyIEwzMzMuOTkwOTgxLDE1NC4zNDM1MTEgQzI5NS45MDE0NzgsMTU3LjYwMjc0MSAyNTguODgyMzUzLDE2Ni43MzM3MDIgMjIzLjU4MTM1OSwxODEuNjY0NzYzIEMxODAuMTExMzEyLDIwMC4wNTE1MjkgMTQxLjA3NjI3MywyMjYuMzY3ODk0IDEwNy41NjA5NDksMjU5Ljg4MzIxOSBDNzQuMDQ1NjI1LDI5My4zOTg1NDQgNDcuNzI5MjU5LDMzMi40MzI1NTkgMjkuMzQyNDkzLDM3NS45MDM2MjkgQzEwLjMwMTgzNSw0MjAuOTIxOTM5IDAuNjQ2OTQxLDQ2OC43Mjk3ODEgMC42NDY5NDEsNTE3Ljk5NTgzNCBDMC42NDY5NDEsNTY3LjI2MzkzNCAxMC4zMDE4MzUsNjE1LjA2OTczIDI5LjM0MjQ5Myw2NjAuMDg5MDYzIEM0Ny43MjkyNTksNzAzLjU1ODA4NyA3NC4wNDU2MjQsNzQyLjU5NDE0OSAxMDcuNTYwOTQ5LDc3Ni4xMDk0NzMgQzE0MS4wNzYyNzQsODA5LjYyNDc5NyAxODAuMTEwMjg5LDgzNS45NDExNjMgMjIzLjU4MTM1OSw4NTQuMzI2OTA2IEMyNjguNTk5NjY5LDg3My4zNjg1ODggMzE2LjQwNjQ4OCw4ODMuMDIzNDgyIDM2NS42NzM1NjQsODgzLjAyMzQ4MiBDNDE0Ljk0MTY2NCw4ODMuMDIzNDgyIDQ2Mi43NDc0Niw4NzMuMzY4NTg4IDUwNy43NjY3OTMsODU0LjMyNjkwNiBDNTUxLjIzNTgxNyw4MzUuOTQxMTY0IDU5MC4yNzE4NzksODA5LjYyNDc5OCA2MjMuNzg3MjAzLDc3Ni4xMDk0NzMgQzY1Ny4zMDI1MjcsNzQyLjU5NDE0OCA2ODMuNjE4ODkzLDcwMy41NTkxMSA3MDIuMDA0NjM2LDY2MC4wODkwNjMgQzcyMS4wNDYzMTgsNjE1LjA2OTczIDczMC43MDEyMTIsNTY3LjI2MjkxMSA3MzAuNzAxMjEyLDUxNy45OTU4MzQgQzczMC43MDEyMTMsNTAzLjg2ODA2OSA3MTkuMjQ4MzcsNDkyLjQxNDIwMyA3MDUuMTE4NTU4LDQ5Mi40MTQyMDMgWiIgaWQ9IlNoYXBlIj48L3BhdGg+CiAgICAgICAgPC9nPgogICAgICAgIDx0ZXh0IGlkPSIxMCIgZm9udC1mYW1pbHk9IkhlbHZldGljYSIgZm9udC1zaXplPSIyODgiIGZvbnQtd2VpZ2h0PSJub3JtYWwiIGZpbGw9IiNmZmZmZmYiPgogICAgICAgICAgICA8dHNwYW4geD0iMjExIiB5PSI2MzQiPjEwPC90c3Bhbj4KICAgICAgICA8L3RleHQ+CiAgICA8L2c+Cjwvc3ZnPg==")}chimee-center-state.forward span{background-image:url("data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjczMXB4IiBoZWlnaHQ9Ijg4NHB4IiB2aWV3Qm94PSIwIDAgNzMxIDg4NCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj4KICAgIDwhLS0gR2VuZXJhdG9yOiBTa2V0Y2ggNDQuMSAoNDE0NTUpIC0gaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoIC0tPgogICAgPGRlc2M+Q3JlYXRlZCB3aXRoIFNrZXRjaC48L2Rlc2M+CiAgICA8ZGVmcz48L2RlZnM+CiAgICA8ZyBpZD0iUGFnZS0xIiBzdHJva2U9IiNmZmZmZmYiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4KICAgICAgICA8ZyBpZD0iNzcxLeWNlee6v++8jOWIt+aWsCIgZmlsbC1ydWxlPSJub256ZXJvIiBmaWxsPSIjZmZmZmZmIj4KICAgICAgICAgICAgPHBhdGggZD0iTTcwNS4xMTg1NTgsNDkyLjQxNDIwMyBDNjkwLjk4OTc2OSw0OTIuNDE0MjAzIDY3OS41MzU5MDMsNTAzLjg2ODA2OSA2NzkuNTM1OTAzLDUxNy45OTY4NTggQzY3OS41MzU5MDMsNjkxLjA2MDQ0OSA1MzguNzM3MTU3LDgzMS44NTkxOTUgMzY1LjY3MzU2Niw4MzEuODU5MTk1IEMxOTIuNjA4OTUyLDgzMS44NTkxOTUgNTEuODEyMjUyLDY5MS4wNjA0NDkgNTEuODEyMjUyLDUxNy45OTY4NTggQzUxLjgxMjI1MiwzNTUuMDM4NDE2IDE3Ni42NTI1MzgsMjIwLjcwNjk2NSAzMzUuNzE0MjMsMjA1LjU3MzI4OSBMMjIzLjYwMDgwMywzMTcuNjg2NzE2IEMyMTMuNjEwMjY1LDMyNy42NzcyNTQgMjEzLjYxMDI2NSwzNDMuODc1MTY4IDIyMy42MDA4MDMsMzUzLjg2NTcwNyBDMjI4LjU5NjU4NCwzNTguODYwNDY1IDIzNS4xNDM2OTcsMzYxLjM1ODM1NSAyNDEuNjkwODEsMzYxLjM1ODM1NSBDMjQ4LjIzNzkyMywzNjEuMzU4MzU1IDI1NC43ODUwMzYsMzU4Ljg2MDQ2NSAyNTkuNzgwODE3LDM1My44NjU3MDcgTDQxNC43MzcwMDUsMTk4LjkwOTUxOSBDNDI0LjcyNzU0MywxODguOTE4OTgxIDQyNC43Mjc1NDMsMTcyLjcyMTA2NyA0MTQuNzM3MDA1LDE2Mi43MzA1MjggTDI1OS43Nzk3OTMsNy43NzQzNDEgQzI0OS43ODgyMzEsLTIuMjE2MTk3IDIzMy41OTEzNDEsLTIuMjE2MTk3IDIyMy42MDA4MDIsNy43NzQzNDEgQzIxMy42MTAyNjQsMTcuNzY0ODc5IDIxMy42MTAyNjQsMzMuOTYyNzkzIDIyMy42MDA4MDIsNDMuOTUzMzMyIEwzMzMuOTkwOTgxLDE1NC4zNDM1MTEgQzI5NS45MDE0NzgsMTU3LjYwMjc0MSAyNTguODgyMzUzLDE2Ni43MzM3MDIgMjIzLjU4MTM1OSwxODEuNjY0NzYzIEMxODAuMTExMzEyLDIwMC4wNTE1MjkgMTQxLjA3NjI3MywyMjYuMzY3ODk0IDEwNy41NjA5NDksMjU5Ljg4MzIxOSBDNzQuMDQ1NjI1LDI5My4zOTg1NDQgNDcuNzI5MjU5LDMzMi40MzI1NTkgMjkuMzQyNDkzLDM3NS45MDM2MjkgQzEwLjMwMTgzNSw0MjAuOTIxOTM5IDAuNjQ2OTQxLDQ2OC43Mjk3ODEgMC42NDY5NDEsNTE3Ljk5NTgzNCBDMC42NDY5NDEsNTY3LjI2MzkzNCAxMC4zMDE4MzUsNjE1LjA2OTczIDI5LjM0MjQ5Myw2NjAuMDg5MDYzIEM0Ny43MjkyNTksNzAzLjU1ODA4NyA3NC4wNDU2MjQsNzQyLjU5NDE0OSAxMDcuNTYwOTQ5LDc3Ni4xMDk0NzMgQzE0MS4wNzYyNzQsODA5LjYyNDc5NyAxODAuMTEwMjg5LDgzNS45NDExNjMgMjIzLjU4MTM1OSw4NTQuMzI2OTA2IEMyNjguNTk5NjY5LDg3My4zNjg1ODggMzE2LjQwNjQ4OCw4ODMuMDIzNDgyIDM2NS42NzM1NjQsODgzLjAyMzQ4MiBDNDE0Ljk0MTY2NCw4ODMuMDIzNDgyIDQ2Mi43NDc0Niw4NzMuMzY4NTg4IDUwNy43NjY3OTMsODU0LjMyNjkwNiBDNTUxLjIzNTgxNyw4MzUuOTQxMTY0IDU5MC4yNzE4NzksODA5LjYyNDc5OCA2MjMuNzg3MjAzLDc3Ni4xMDk0NzMgQzY1Ny4zMDI1MjcsNzQyLjU5NDE0OCA2ODMuNjE4ODkzLDcwMy41NTkxMSA3MDIuMDA0NjM2LDY2MC4wODkwNjMgQzcyMS4wNDYzMTgsNjE1LjA2OTczIDczMC43MDEyMTIsNTY3LjI2MjkxMSA3MzAuNzAxMjEyLDUxNy45OTU4MzQgQzczMC43MDEyMTMsNTAzLjg2ODA2OSA3MTkuMjQ4MzcsNDkyLjQxNDIwMyA3MDUuMTE4NTU4LDQ5Mi40MTQyMDMgWiIgaWQ9IlNoYXBlIj48L3BhdGg+CiAgICAgICAgPC9nPgogICAgICAgIDx0ZXh0IGlkPSIxMCIgZm9udC1mYW1pbHk9IkhlbHZldGljYSIgZm9udC1zaXplPSIyODgiIGZvbnQtd2VpZ2h0PSJub3JtYWwiIGZpbGw9IiNmZmZmZmYiPgogICAgICAgICAgICA8dHNwYW4geD0iMjExIiB5PSI2MzQiPjEwPC90c3Bhbj4KICAgICAgICA8L3RleHQ+CiAgICA8L2c+Cjwvc3ZnPg==")}chimee-center-state.volume-high span{background-image:url("data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjEwN3B4IiBoZWlnaHQ9IjEwMXB4IiB2aWV3Qm94PSIwIDAgMTA3IDEwMSIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj4KICAgIDwhLS0gR2VuZXJhdG9yOiBTa2V0Y2ggNDQuMSAoNDE0NTUpIC0gaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoIC0tPgogICAgPGRlc2M+Q3JlYXRlZCB3aXRoIFNrZXRjaC48L2Rlc2M+CiAgICA8ZGVmcz48L2RlZnM+CiAgICA8ZyBpZD0iR3JvdXAiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDEuMDAwMDAwLCAwLjAwMDAwMCkiIHN0cm9rZT0iI0ZGRkZGRiI+CiAgICAgICAgPHBvbHlnb24gaWQ9IlBhdGgiIGZpbGw9IiNmZmZmZmYiIHBvaW50cz0iMC40MDczMTY0NDYgMzAgMjcuNjUwMDc3OSAzMCA1Ny4zNzM3MjkzIDIuODQyMTcwOTRlLTE0IDU4LjQ3NjI1MzIgMTAwIDI3LjY1MDA3NzkgNzAgMC40MDczMTY0NDYgNzAiPjwvcG9seWdvbj4KICAgICAgICA8cGF0aCBkPSJNNjMuNjExNjUwNSw1LjAwOTc1MjM5IEM2OS43MDc5Mjc1LDQuNzg2MTIwNTcgNzYuNjU0OTI1MSw4LjQwODU2MTQ2IDg0LjQ1MjY0MzEsMTUuODc3MDc1IEM5Ni4xNDkyMjAxLDI3LjA3OTg0NTQgMTAwLjk3MDg3NCwzNC43OTc1MTI1IDEwMC45NzA4NzQsNTAuOTYwODU1OCBDMTAwLjk3MDg3NCw2Ny4xMjQxOTkxIDk2LjI4ODcyMjUsNzMuNzkwNzQ4MiA4NC40NTI2NDMxLDgzLjgzMDY3MjQgQzc2LjU2MTkyMzQsOTAuNTIzOTU1MiA2OS42MTQ5MjU5LDk0LjAzMjA2NDQgNjMuNjExNjUwNSw5NC4zNTUiIGlkPSLlpJbnjq8iIHN0cm9rZS13aWR0aD0iMTAiPjwvcGF0aD4KICAgICAgICA8cGF0aCBkPSJNNjUuODUwNTY5OSwyOS40OTI5MTk1IEM2OC41MzY5NDM0LDI5LjM5MzExNjkgNzEuNTk4MTkzOCwzMS4wMDk3NDE2IDc1LjAzNDMyMSwzNC4zNDI3OTM0IEM4MC4xODg1MTE4LDM5LjM0MjM3MTIgODIuMzEzMjEyMyw0Mi43ODY2MTU0IDgyLjMxMzIxMjMsNTAgQzgyLjMxMzIxMjMsNTcuMjEzMzg0NiA4MC4yNDk5ODQ3LDYwLjE4ODUzNTQgNzUuMDM0MzIxLDY0LjY2OTE1NzYgQzcxLjU1NzIxMTksNjcuNjU2MjM5IDY4LjQ5NTk2MTUsNjkuMjIxODM5NyA2NS44NTA1Njk5LDY5LjM2NTk1OTUiIGlkPSLlhoXnjq8iIHN0cm9rZS13aWR0aD0iMTAiPjwvcGF0aD4KICAgIDwvZz4KPC9zdmc+")}chimee-center-state.volume-low span{background-image:url("data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9Ijg5cHgiIGhlaWdodD0iMTAxcHgiIHZpZXdCb3g9IjAgMCA4OSAxMDEiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgICA8IS0tIEdlbmVyYXRvcjogU2tldGNoIDQ0LjEgKDQxNDU1KSAtIGh0dHA6Ly93d3cuYm9oZW1pYW5jb2RpbmcuY29tL3NrZXRjaCAtLT4KICAgIDxkZXNjPkNyZWF0ZWQgd2l0aCBTa2V0Y2guPC9kZXNjPgogICAgPGRlZnM+PC9kZWZzPgogICAgPGcgaWQ9Ikdyb3VwIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxLjAwMDAwMCwgMC4wMDAwMDApIiBzdHJva2U9IiNGRkZGRkYiPgogICAgICAgIDxwb2x5Z29uIGlkPSJQYXRoIiBmaWxsPSIjZmZmZmZmIiBwb2ludHM9IjAuNDA3MzE2NDQ2IDMwIDI3LjY1MDA3NzkgMzAgNTcuMzczNzI5MyAyLjg0MjE3MDk0ZS0xNCA1OC40NzYyNTMyIDEwMCAyNy42NTAwNzc5IDcwIDAuNDA3MzE2NDQ2IDcwIj48L3BvbHlnb24+CiAgICAgICAgPHBhdGggZD0iTTY1Ljg1MDU2OTksMjkuNDkyOTE5NSBDNjguNTM2OTQzNCwyOS4zOTMxMTY5IDcxLjU5ODE5MzgsMzEuMDA5NzQxNiA3NS4wMzQzMjEsMzQuMzQyNzkzNCBDODAuMTg4NTExOCwzOS4zNDIzNzEyIDgyLjMxMzIxMjMsNDIuNzg2NjE1NCA4Mi4zMTMyMTIzLDUwIEM4Mi4zMTMyMTIzLDU3LjIxMzM4NDYgODAuMjQ5OTg0Nyw2MC4xODg1MzU0IDc1LjAzNDMyMSw2NC42NjkxNTc2IEM3MS41NTcyMTE5LDY3LjY1NjIzOSA2OC40OTU5NjE1LDY5LjIyMTgzOTcgNjUuODUwNTY5OSw2OS4zNjU5NTk1IiBpZD0i5YaF546vIiBzdHJva2Utd2lkdGg9IjEwIj48L3BhdGg+CiAgICA8L2c+Cjwvc3ZnPg==")}chimee-center-state-tip span{display:inline-block;width:24px;height:24px;margin:14px;background-origin:content-box;background-size:auto 100%;background-repeat:no-repeat;background-position:50%;box-sizing:initial}chimee-center-state.play span{background-position:110% 50%}chimee-center-state-loading{width:52px;height:52px;padding:26px;background-image:url("data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjgwcHgiIGhlaWdodD0iODBweCIgdmlld0JveD0iMCAwIDgwIDgwIiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCA0Ny4xICg0NTQyMikgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+CiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxnIGlkPSJsb2FkaW5nIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtMTAuMDAwMDAwLCAtMTAuMDAwMDAwKSIgZmlsbC1ydWxlPSJub256ZXJvIiBmaWxsPSIjRkZGRkZGIj4KICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS1wYXRoIiBmaWxsLW9wYWNpdHk9IjEiIHg9IjQ3IiB5PSIxMCIgd2lkdGg9IjYiIGhlaWdodD0iMjAiIHJ4PSIzIj48L3JlY3Q+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbC1vcGFjaXR5PSIwLjkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDY1LjAwMDAwMCwgMjQuMDE5MjM4KSByb3RhdGUoMzAuMDAwMDAwKSB0cmFuc2xhdGUoLTY1LjAwMDAwMCwgLTI0LjAxOTIzOCkgIiB4PSI2MiIgeT0iMTQuMDE5MjM3OSIgd2lkdGg9IjYiIGhlaWdodD0iMjAiIHJ4PSIzIj48L3JlY3Q+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbC1vcGFjaXR5PSIwLjgiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDc1Ljk4MDc2MiwgMzUuMDAwMDAwKSByb3RhdGUoNjAuMDAwMDAwKSB0cmFuc2xhdGUoLTc1Ljk4MDc2MiwgLTM1LjAwMDAwMCkgIiB4PSI3Mi45ODA3NjIxIiB5PSIyNSIgd2lkdGg9IjYiIGhlaWdodD0iMjAiIHJ4PSIzIj48L3JlY3Q+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbC1vcGFjaXR5PSIwLjciIHRyYW5zZm9ybT0idHJhbnNsYXRlKDgwLjAwMDAwMCwgNTAuMDAwMDAwKSByb3RhdGUoOTAuMDAwMDAwKSB0cmFuc2xhdGUoLTgwLjAwMDAwMCwgLTUwLjAwMDAwMCkgIiB4PSI3NyIgeT0iNDAiIHdpZHRoPSI2IiBoZWlnaHQ9IjIwIiByeD0iMyI+PC9yZWN0PgogICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLXBhdGgiIGZpbGwtb3BhY2l0eT0iMC42IiB0cmFuc2Zvcm09InRyYW5zbGF0ZSg3NS45ODA3NjIsIDY1LjAwMDAwMCkgcm90YXRlKDEyMC4wMDAwMDApIHRyYW5zbGF0ZSgtNzUuOTgwNzYyLCAtNjUuMDAwMDAwKSAiIHg9IjcyLjk4MDc2MjEiIHk9IjU1IiB3aWR0aD0iNiIgaGVpZ2h0PSIyMCIgcng9IjMiPjwvcmVjdD4KICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS1wYXRoIiBmaWxsLW9wYWNpdHk9IjAuNSIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoNjUuMDAwMDAwLCA3NS45ODA3NjIpIHJvdGF0ZSgxNTAuMDAwMDAwKSB0cmFuc2xhdGUoLTY1LjAwMDAwMCwgLTc1Ljk4MDc2MikgIiB4PSI2MiIgeT0iNjUuOTgwNzYyMSIgd2lkdGg9IjYiIGhlaWdodD0iMjAiIHJ4PSIzIj48L3JlY3Q+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbC1vcGFjaXR5PSIwLjQiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDUwLjAwMDAwMCwgODAuMDAwMDAwKSByb3RhdGUoMTgwLjAwMDAwMCkgdHJhbnNsYXRlKC01MC4wMDAwMDAsIC04MC4wMDAwMDApICIgeD0iNDciIHk9IjcwIiB3aWR0aD0iNiIgaGVpZ2h0PSIyMCIgcng9IjMiPjwvcmVjdD4KICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS1wYXRoIiBmaWxsLW9wYWNpdHk9IjAuMyIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMzUuMDAwMDAwLCA3NS45ODA3NjIpIHJvdGF0ZSgtMTUwLjAwMDAwMCkgdHJhbnNsYXRlKC0zNS4wMDAwMDAsIC03NS45ODA3NjIpICIgeD0iMzIiIHk9IjY1Ljk4MDc2MjEiIHdpZHRoPSI2IiBoZWlnaHQ9IjIwIiByeD0iMyI+PC9yZWN0PgogICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLXBhdGgiIGZpbGwtb3BhY2l0eT0iMC4yIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgyNC4wMTkyMzgsIDY1LjAwMDAwMCkgcm90YXRlKC0xMjAuMDAwMDAwKSB0cmFuc2xhdGUoLTI0LjAxOTIzOCwgLTY1LjAwMDAwMCkgIiB4PSIyMS4wMTkyMzc5IiB5PSI1NSIgd2lkdGg9IjYiIGhlaWdodD0iMjAiIHJ4PSIzIj48L3JlY3Q+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbC1vcGFjaXR5PSIwLjMiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDIwLjAwMDAwMCwgNTAuMDAwMDAwKSByb3RhdGUoLTkwLjAwMDAwMCkgdHJhbnNsYXRlKC0yMC4wMDAwMDAsIC01MC4wMDAwMDApICIgeD0iMTciIHk9IjQwIiB3aWR0aD0iNiIgaGVpZ2h0PSIyMCIgcng9IjMiPjwvcmVjdD4KICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS1wYXRoIiBmaWxsLW9wYWNpdHk9IjAuNCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMjQuMDE5MjM4LCAzNS4wMDAwMDApIHJvdGF0ZSgtNjAuMDAwMDAwKSB0cmFuc2xhdGUoLTI0LjAxOTIzOCwgLTM1LjAwMDAwMCkgIiB4PSIyMS4wMTkyMzc5IiB5PSIyNSIgd2lkdGg9IjYiIGhlaWdodD0iMjAiIHJ4PSIzIj48L3JlY3Q+CiAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtcGF0aCIgZmlsbC1vcGFjaXR5PSIwLjUiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDM1LjAwMDAwMCwgMjQuMDE5MjM4KSByb3RhdGUoLTMwLjAwMDAwMCkgdHJhbnNsYXRlKC0zNS4wMDAwMDAsIC0yNC4wMTkyMzgpICIgeD0iMzIiIHk9IjE0LjAxOTIzNzkiIHdpZHRoPSI2IiBoZWlnaHQ9IjIwIiByeD0iMyI+PC9yZWN0PgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+");background-origin:content-box;background-size:auto 100%;background-repeat:no-repeat;background-position:50%;animation:b 1.2s linear infinite}chimee-center-state-error{display:none;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:180px;font-size:16px;z-index:1;color:#ffcf00;text-shadow:0 0 3px red;font-weight:100;text-align:center}',void 0);var clss="correct tip play pause back forward volume-high volume-low",defaultConfig$2={errorTips:"加载失败,请刷新重试"},chimeeCenterState=lib$1({name:"chimeeCenterState",tagName:"chimee-center-state",html:"\n <chimee-center-state-correct>\n <chimee-center-state-loading></chimee-center-state-loading>\n <chimee-center-state-tip>\n <span></span>\n </chimee-center-state-tip>\n </chimee-center-state-correct>\n <chimee-center-state-error></chimee-center-state-error>\n ",offset:"50%",hide:!1,create:function(){},inited:function(){this.config=isObject(this.$config)?deepAssign$2(defaultConfig$2,this.$config):defaultConfig$2,this.$dom.querySelector("chimee-center-state-error").innerText=this.config.errorTips,this.src&&this.showLoading(!0)},penetrate:!0,operable:!1,destroy:function(){this.clearTimeout()},events:{pause:function(){this.showTip("pause"),this.showLoading(!1)},play:function(){this.showTip("play")},canplay:function(){this.playing()},playing:function(){this.playing()},loadstart:function(){this.waiting("loadstart")},waiting:function(){this.waiting()},timeupdate:function(){this.showLoading(!1),this.clearTimeout()},keydown:function(e){if(this.$videoConfig.plugin.some(function(e){return"chimeeControl"===(e.name||e)}))switch(e.stopPropagation(),e.keyCode){case 37:e.preventDefault(),!this.live&&this.showTip("back");break;case 39:e.preventDefault(),!this.live&&this.showTip("forward");break;case 38:e.preventDefault(),this.showTip("volume-high");break;case 40:e.preventDefault(),this.showTip("volume-low")}}},methods:{playing:function(){this.clearTimeout(),this.showLoading(!1),this.showError(!1)},waiting:function(e){var t=this;this.clearTimeout(),this._timeout=setTimeout(function(){return t.showError()},3e4),("loadstart"===e||!this.paused)&&this.showLoading(!0)},clearTimeout:function(e){function t(){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}(function(){this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}),showTip:function(e){var t=this;this.$domWrap.removeClass(clss).addClass("correct tip "+e),setTimeout(function(){t.$domWrap.removeClass("tip "+e)},500)},showLoading:function(e){!1===e?this.$domWrap.removeClass("loading"):this.$domWrap.addClass("correct loading")},showError:function(e){!1===e?this.$domWrap.removeClass("error"):(this.$domWrap[0].className="",this.$domWrap.addClass("error"))}}}),hls=createCommonjsModule(function(e,t){var r;r=function(){return function(e){var t={};function r(i){if(t[i])return t[i].exports;var n=t[i]={i:i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=e,r.c=t,r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:i})},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="/dist/",r(r.s=8)}([function(e,t,r){r.d(t,"a",function(){return u}),r.d(t,"b",function(){return c});var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};function n(){}var o={trace:n,debug:n,log:n,warn:n,info:n,error:n},a=o;function s(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];r.forEach(function(t){a[t]=e[t]?e[t].bind(e):function(e){var t=self.console[e];return t?function(){for(var r=arguments.length,i=Array(r),n=0;n<r;n++)i[n]=arguments[n];i[0]&&(i[0]=function(e,t){return t="["+e+"] > "+t}(e,i[0])),t.apply(self.console,i)}:n}(t)})}var u=function(e){if(!0===e||"object"===(void 0===e?"undefined":i(e))){s(e,"debug","log","info","warn","error");try{a.log()}catch(e){a=o}}else a=o},c=o},function(e,t,r){t.a={MEDIA_ATTACHING:"hlsMediaAttaching",MEDIA_ATTACHED:"hlsMediaAttached",MEDIA_DETACHING:"hlsMediaDetaching",MEDIA_DETACHED:"hlsMediaDetached",BUFFER_RESET:"hlsBufferReset",BUFFER_CODECS:"hlsBufferCodecs",BUFFER_CREATED:"hlsBufferCreated",BUFFER_APPENDING:"hlsBufferAppending",BUFFER_APPENDED:"hlsBufferAppended",BUFFER_EOS:"hlsBufferEos",BUFFER_FLUSHING:"hlsBufferFlushing",BUFFER_FLUSHED:"hlsBufferFlushed",MANIFEST_LOADING:"hlsManifestLoading",MANIFEST_LOADED:"hlsManifestLoaded",MANIFEST_PARSED:"hlsManifestParsed",LEVEL_SWITCH:"hlsLevelSwitch",LEVEL_SWITCHING:"hlsLevelSwitching",LEVEL_SWITCHED:"hlsLevelSwitched",LEVEL_LOADING:"hlsLevelLoading",LEVEL_LOADED:"hlsLevelLoaded",LEVEL_UPDATED:"hlsLevelUpdated",LEVEL_PTS_UPDATED:"hlsLevelPtsUpdated",AUDIO_TRACKS_UPDATED:"hlsAudioTracksUpdated",AUDIO_TRACK_SWITCH:"hlsAudioTrackSwitch",AUDIO_TRACK_SWITCHING:"hlsAudioTrackSwitching",AUDIO_TRACK_SWITCHED:"hlsAudioTrackSwitched",AUDIO_TRACK_LOADING:"hlsAudioTrackLoading",AUDIO_TRACK_LOADED:"hlsAudioTrackLoaded",SUBTITLE_TRACKS_UPDATED:"hlsSubtitleTracksUpdated",SUBTITLE_TRACK_SWITCH:"hlsSubtitleTrackSwitch",SUBTITLE_TRACK_LOADING:"hlsSubtitleTrackLoading",SUBTITLE_TRACK_LOADED:"hlsSubtitleTrackLoaded",SUBTITLE_FRAG_PROCESSED:"hlsSubtitleFragProcessed",INIT_PTS_FOUND:"hlsInitPtsFound",FRAG_LOADING:"hlsFragLoading",FRAG_LOAD_PROGRESS:"hlsFragLoadProgress",FRAG_LOAD_EMERGENCY_ABORTED:"hlsFragLoadEmergencyAborted",FRAG_LOADED:"hlsFragLoaded",FRAG_DECRYPTED:"hlsFragDecrypted",FRAG_PARSING_INIT_SEGMENT:"hlsFragParsingInitSegment",FRAG_PARSING_USERDATA:"hlsFragParsingUserdata",FRAG_PARSING_METADATA:"hlsFragParsingMetadata",FRAG_PARSING_DATA:"hlsFragParsingData",FRAG_PARSED:"hlsFragParsed",FRAG_BUFFERED:"hlsFragBuffered",FRAG_CHANGED:"hlsFragChanged",FPS_DROP:"hlsFpsDrop",FPS_DROP_LEVEL_CAPPING:"hlsFpsDropLevelCapping",ERROR:"hlsError",DESTROYING:"hlsDestroying",KEY_LOADING:"hlsKeyLoading",KEY_LOADED:"hlsKeyLoaded",STREAM_STATE_TRANSITION:"hlsStreamStateTransition"}},function(e,t,r){r.d(t,"b",function(){return i}),r.d(t,"a",function(){return n});var i={NETWORK_ERROR:"networkError",MEDIA_ERROR:"mediaError",MUX_ERROR:"muxError",OTHER_ERROR:"otherError"},n={MANIFEST_LOAD_ERROR:"manifestLoadError",MANIFEST_LOAD_TIMEOUT:"manifestLoadTimeOut",MANIFEST_PARSING_ERROR:"manifestParsingError",MANIFEST_INCOMPATIBLE_CODECS_ERROR:"manifestIncompatibleCodecsError",LEVEL_LOAD_ERROR:"levelLoadError",LEVEL_LOAD_TIMEOUT:"levelLoadTimeOut",LEVEL_SWITCH_ERROR:"levelSwitchError",AUDIO_TRACK_LOAD_ERROR:"audioTrackLoadError",AUDIO_TRACK_LOAD_TIMEOUT:"audioTrackLoadTimeOut",FRAG_LOAD_ERROR:"fragLoadError",FRAG_LOOP_LOADING_ERROR:"fragLoopLoadingError",FRAG_LOAD_TIMEOUT:"fragLoadTimeOut",FRAG_DECRYPT_ERROR:"fragDecryptError",FRAG_PARSING_ERROR:"fragParsingError",REMUX_ALLOC_ERROR:"remuxAllocError",KEY_LOAD_ERROR:"keyLoadError",KEY_LOAD_TIMEOUT:"keyLoadTimeOut",BUFFER_ADD_CODEC_ERROR:"bufferAddCodecError",BUFFER_APPEND_ERROR:"bufferAppendError",BUFFER_APPENDING_ERROR:"bufferAppendingError",BUFFER_STALLED_ERROR:"bufferStalledError",BUFFER_FULL_ERROR:"bufferFullError",BUFFER_SEEK_OVER_HOLE:"bufferSeekOverHole",BUFFER_NUDGE_ON_STALL:"bufferNudgeOnStall",INTERNAL_EXCEPTION:"internalException"}},function(e,t,r){r.d(t,"b",function(){return n});var i=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.isHeader=function(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128},e.isFooter=function(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128},e.getID3Data=function(t,r){for(var i=r,n=0;e.isHeader(t,r);){n+=10,n+=e._readSize(t,r+6),e.isFooter(t,r+10)&&(n+=10),r+=n}if(n>0)return t.subarray(i,i+n)},e._readSize=function(e,t){var r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,r|=(127&e[t+2])<<7,r|=127&e[t+3]},e.getTimeStamp=function(t){for(var r=e.getID3Frames(t),i=0;i<r.length;i++){var n=r[i];if(e.isTimeStampFrame(n))return e._readTimeStamp(n)}},e.isTimeStampFrame=function(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info},e._getFrameData=function(t){var r=String.fromCharCode(t[0],t[1],t[2],t[3]),i=e._readSize(t,4);return{type:r,size:i,data:t.subarray(10,10+i)}},e.getID3Frames=function(t){for(var r=0,i=[];e.isHeader(t,r);){for(var n=e._readSize(t,r+6),o=(r+=10)+n;r+8<o;){var a=e._getFrameData(t.subarray(r)),s=e._decodeFrame(a);s&&i.push(s),r+=a.size+10}e.isFooter(t,r)&&(r+=10)}return i},e._decodeFrame=function(t){return"PRIV"===t.type?e._decodePrivFrame(t):"T"===t.type[0]?e._decodeTextFrame(t):"W"===t.type[0]?e._decodeURLFrame(t):void 0},e._readTimeStamp=function(e){if(8===e.data.byteLength){var t=new Uint8Array(e.data),r=1&t[3],i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}},e._decodePrivFrame=function(t){if(!(t.size<2)){var r=e._utf8ArrayToStr(t.data,!0),i=new Uint8Array(t.data.subarray(r.length+1));return{key:t.type,info:r,data:i.buffer}}},e._decodeTextFrame=function(t){if(!(t.size<2)){if("TXXX"===t.type){var r=1,i=e._utf8ArrayToStr(t.data.subarray(r));r+=i.length+1;var n=e._utf8ArrayToStr(t.data.subarray(r));return{key:t.type,info:i,data:n}}var o=e._utf8ArrayToStr(t.data.subarray(1));return{key:t.type,data:o}}},e._decodeURLFrame=function(t){if("WXXX"===t.type){if(t.size<2)return;var r=1,i=e._utf8ArrayToStr(t.data.subarray(r));r+=i.length+1;var n=e._utf8ArrayToStr(t.data.subarray(r));return{key:t.type,info:i,data:n}}var o=e._utf8ArrayToStr(t.data);return{key:t.type,data:o}},e._utf8ArrayToStr=function(e){for(var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=e.length,i=void 0,n=void 0,o=void 0,a="",s=0;s<r;){if(0===(i=e[s++])&&t)return a;if(0!==i&&3!==i)switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:n=e[s++],a+=String.fromCharCode((31&i)<<6|63&n);break;case 14:n=e[s++],o=e[s++],a+=String.fromCharCode((15&i)<<12|(63&n)<<6|(63&o)<<0)}}return a},e}(),n=i._utf8ArrayToStr;t.a=i},function(e,t,r){var i=function(){function e(t,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.subtle=t,this.aesIV=r}return e.prototype.decrypt=function(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)},e}();var n=function(){function e(t,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.subtle=t,this.key=r}return e.prototype.expandKey=function(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])},e}();var o=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.initTable()}return e.prototype.uint8ArrayToUint32Array_=function(e){for(var t=new DataView(e),r=new Uint32Array(4),i=0;i<4;i++)r[i]=t.getUint32(4*i);return r},e.prototype.initTable=function(){var e=this.sBox,t=this.invSBox,r=this.subMix,i=r[0],n=r[1],o=r[2],a=r[3],s=this.invSubMix,u=s[0],c=s[1],l=s[2],d=s[3],f=new Uint32Array(256),h=0,p=0,m=0;for(m=0;m<256;m++)f[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){var v=p^p<<1^p<<2^p<<3^p<<4;v=v>>>8^255&v^99,e[h]=v,t[v]=h;var g=f[h],y=f[g],_=f[y],b=257*f[v]^16843008*v;i[h]=b<<24|b>>>8,n[h]=b<<16|b>>>16,o[h]=b<<8|b>>>24,a[h]=b,b=16843009*_^65537*y^257*g^16843008*h,u[v]=b<<24|b>>>8,c[v]=b<<16|b>>>16,l[v]=b<<8|b>>>24,d[v]=b,h?(h=g^f[f[f[_^g]]],p^=f[f[p]]):h=p=1}},e.prototype.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;i<t.length&&r;)r=t[i]===this.key[i],i++;if(!r){this.key=t;var n=this.keySize=t.length;if(4!==n&&6!==n&&8!==n)throw new Error("Invalid aes key size="+n);var o=this.ksRows=4*(n+6+1),a=void 0,s=void 0,u=this.keySchedule=new Uint32Array(o),c=this.invKeySchedule=new Uint32Array(o),l=this.sBox,d=this.rcon,f=this.invSubMix,h=f[0],p=f[1],m=f[2],v=f[3],g=void 0,y=void 0;for(a=0;a<o;a++)a<n?g=u[a]=t[a]:(y=g,a%n==0?(y=l[(y=y<<8|y>>>24)>>>24]<<24|l[y>>>16&255]<<16|l[y>>>8&255]<<8|l[255&y],y^=d[a/n|0]<<24):n>6&&a%n==4&&(y=l[y>>>24]<<24|l[y>>>16&255]<<16|l[y>>>8&255]<<8|l[255&y]),u[a]=g=(u[a-n]^y)>>>0);for(s=0;s<o;s++)a=o-s,y=3&s?u[a]:u[a-4],c[s]=s<4||a<=4?y:h[l[y>>>24]]^p[l[y>>>16&255]]^m[l[y>>>8&255]]^v[l[255&y]],c[s]=c[s]>>>0}},e.prototype.networkToHostOrderSwap=function(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24},e.prototype.decrypt=function(e,t,r){for(var i,n,o=this.keySize+6,a=this.invKeySchedule,s=this.invSBox,u=this.invSubMix,c=u[0],l=u[1],d=u[2],f=u[3],h=this.uint8ArrayToUint32Array_(r),p=h[0],m=h[1],v=h[2],g=h[3],y=new Int32Array(e),_=new Int32Array(y.length),b=void 0,w=void 0,E=void 0,S=void 0,T=void 0,O=void 0,A=void 0,$=void 0,k=void 0,D=void 0,I=void 0,x=void 0,C=this.networkToHostOrderSwap;t<y.length;){for(k=C(y[t]),D=C(y[t+1]),I=C(y[t+2]),x=C(y[t+3]),T=k^a[0],O=x^a[1],A=I^a[2],$=D^a[3],i=4,n=1;n<o;n++)b=c[T>>>24]^l[O>>16&255]^d[A>>8&255]^f[255&$]^a[i],w=c[O>>>24]^l[A>>16&255]^d[$>>8&255]^f[255&T]^a[i+1],E=c[A>>>24]^l[$>>16&255]^d[T>>8&255]^f[255&O]^a[i+2],S=c[$>>>24]^l[T>>16&255]^d[O>>8&255]^f[255&A]^a[i+3],T=b,O=w,A=E,$=S,i+=4;b=s[T>>>24]<<24^s[O>>16&255]<<16^s[A>>8&255]<<8^s[255&$]^a[i],w=s[O>>>24]<<24^s[A>>16&255]<<16^s[$>>8&255]<<8^s[255&T]^a[i+1],E=s[A>>>24]<<24^s[$>>16&255]<<16^s[T>>8&255]<<8^s[255&O]^a[i+2],S=s[$>>>24]<<24^s[T>>16&255]<<16^s[O>>8&255]<<8^s[255&A]^a[i+3],i+=3,_[t]=C(b^p),_[t+1]=C(S^m),_[t+2]=C(E^v),_[t+3]=C(w^g),p=k,m=D,v=I,g=x,t+=4}return _.buffer},e.prototype.destroy=function(){this.key=void 0,this.keySize=void 0,this.ksRows=void 0,this.sBox=void 0,this.invSBox=void 0,this.subMix=void 0,this.invSubMix=void 0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.rcon=void 0},e}(),a=r(2),s=r(0);var u=function(){function e(t,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.observer=t,this.config=r,this.logEnabled=!0;try{var i=crypto||self.crypto;this.subtle=i.subtle||i.webkitSubtle}catch(e){}this.disableWebCrypto=!this.subtle}return e.prototype.isSync=function(){return this.disableWebCrypto&&this.config.enableSoftwareAES},e.prototype.decrypt=function(e,t,r,a){var u=this;if(this.disableWebCrypto&&this.config.enableSoftwareAES){this.logEnabled&&(s.b.log("JS AES decrypt"),this.logEnabled=!1);var c=this.decryptor;c||(this.decryptor=c=new o),c.expandKey(t),a(c.decrypt(e,0,r))}else{this.logEnabled&&(s.b.log("WebCrypto AES decrypt"),this.logEnabled=!1);var l=this.subtle;this.key!==t&&(this.key=t,this.fastAesKey=new n(l,t)),this.fastAesKey.expandKey().then(function(n){new i(l,r).decrypt(e,n).catch(function(i){u.onWebCryptoError(i,e,t,r,a)}).then(function(e){a(e)})}).catch(function(i){u.onWebCryptoError(i,e,t,r,a)})}},e.prototype.onWebCryptoError=function(e,t,r,i,n){this.config.enableSoftwareAES?(s.b.log("WebCrypto Error, disable WebCrypto API"),this.disableWebCrypto=!0,this.logEnabled=!0,this.decrypt(t,r,i,n)):(s.b.error("decrypting error : "+e.message),this.observer.trigger(Event.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_DECRYPT_ERROR,fatal:!0,reason:e.message}))},e.prototype.destroy=function(){var e=this.decryptor;e&&(e.destroy(),this.decryptor=void 0)},e}();t.a=u},function(e,t){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(e){return"function"==typeof e}function n(e){return"object"==typeof e&&null!==e}function o(e){return void 0===e}e.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,r,a,s,u,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||n(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}if(o(r=this._events[e]))return!1;if(i(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:s=Array.prototype.slice.call(arguments,1),r.apply(this,s)}else if(n(r))for(s=Array.prototype.slice.call(arguments,1),a=(c=r.slice()).length,u=0;u<a;u++)c[u].apply(this,s);return!0},r.prototype.addListener=function(e,t){var a;if(!i(t))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,i(t.listener)?t.listener:t),this._events[e]?n(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,n(this._events[e])&&!this._events[e].warned&&(a=o(this._maxListeners)?r.defaultMaxListeners:this._maxListeners)&&a>0&&this._events[e].length>a&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){if(!i(t))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}return n.listener=t,this.on(e,n),this},r.prototype.removeListener=function(e,t){var r,o,a,s;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(a=(r=this._events[e]).length,o=-1,r===t||i(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(n(r)){for(s=a;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){o=s;break}if(o<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(o,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(i(r=this._events[e]))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){return this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},function(e,t,r){var i,n,o,a,s;i=/^((?:[^\/;?#]+:)?)(\/\/[^\/\;?#]*)?(.*?)??(;.*?)?(\?.*?)?(#.*?)?$/,n=/^([^\/;?#]*)(.*)$/,o=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/).*?(?=\/)/g,s={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.alwaysNormalize)return e;var i=this.parseURL(e);if(!a)throw new Error("Error trying to parse base URL.");return i.path=s.normalizePath(i.path),s.buildURLFromParts(i)}var o=this.parseURL(t);if(!o)throw new Error("Error trying to parse relative URL.");if(o.scheme)return r.alwaysNormalize?(o.path=s.normalizePath(o.path),s.buildURLFromParts(o)):t;var a=this.parseURL(e);if(!a)throw new Error("Error trying to parse base URL.");if(!a.netLoc&&a.path&&"/"!==a.path[0]){var u=n.exec(a.path);a.netLoc=u[1],a.path=u[2]}a.netLoc&&!a.path&&(a.path="/");var c={scheme:a.scheme,netLoc:o.netLoc,path:null,params:o.params,query:o.query,fragment:o.fragment};if(!o.netLoc&&(c.netLoc=a.netLoc,"/"!==o.path[0]))if(o.path){var l=a.path,d=l.substring(0,l.lastIndexOf("/")+1)+o.path;c.path=s.normalizePath(d)}else c.path=a.path,o.params||(c.params=a.params,o.query||(c.query=a.query));return null===c.path&&(c.path=r.alwaysNormalize?s.normalizePath(o.path):o.path),s.buildURLFromParts(c)},parseURL:function(e){var t=i.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(o,"");e.length!==(e=e.replace(a,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=s},function(e,t,r){var i=r(1),n=r(2),o=r(4),a=r(0);function s(e,t){return 255===e[t]&&240==(246&e[t+1])}function u(e,t){return 1&e[t+1]?7:9}function c(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function l(e,t){return!!(t+1<e.length&&s(e,t))}function d(e,t){if(t+1<e.length&&s(e,t)){var r=u(e,t);t+5<e.length&&(r=c(e,t));var i=t+r;if(i===e.length||i+1<e.length&&s(e,i))return!0}return!1}function f(e,t,r,i,o){if(!e.samplerate){var s=function(e,t,r,i){var o,s,u,c,l,d=navigator.userAgent.toLowerCase(),f=i,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];if(o=1+((192&t[r+2])>>>6),!((s=(60&t[r+2])>>>2)>h.length-1))return c=(1&t[r+2])<<2,c|=(192&t[r+3])>>>6,a.b.log("manifest codec:"+i+",ADTS data:type:"+o+",sampleingIndex:"+s+"["+h[s]+"Hz],channelConfig:"+c),/firefox/i.test(d)?s>=6?(o=5,l=new Array(4),u=s-3):(o=2,l=new Array(2),u=s):-1!==d.indexOf("android")?(o=2,l=new Array(2),u=s):(o=5,l=new Array(4),i&&(-1!==i.indexOf("mp4a.40.29")||-1!==i.indexOf("mp4a.40.5"))||!i&&s>=6?u=s-3:((i&&-1!==i.indexOf("mp4a.40.2")&&(s>=6&&1===c||/vivaldi/i.test(d))||!i&&1===c)&&(o=2,l=new Array(2)),u=s)),l[0]=o<<3,l[0]|=(14&s)>>1,l[1]|=(1&s)<<7,l[1]|=c<<3,5===o&&(l[1]|=(14&u)>>1,l[2]=(1&u)<<7,l[2]|=8,l[3]=0),{config:l,samplerate:h[s],channelCount:c,codec:"mp4a.40."+o,manifestCodec:f};e.trigger(Event.ERROR,{type:n.b.MEDIA_ERROR,details:n.a.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+s})}(t,r,i,o);e.config=s.config,e.samplerate=s.samplerate,e.channelCount=s.channelCount,e.codec=s.codec,e.manifestCodec=s.manifestCodec,a.b.log("parsed codec:"+e.codec+",rate:"+s.samplerate+",nb channel:"+s.channelCount)}}function h(e){return 9216e4/e}function p(e,t,r,i,n){var o=function(e,t,r,i,n){var o,a,s=e.length;if(o=u(e,t),a=c(e,t),(a-=o)>0&&t+o+a<=s)return{headerLength:o,frameLength:a,stamp:r+i*n}}(t,r,i,n,h(e.samplerate));if(o){var a=o.stamp,s=o.headerLength,l=o.frameLength,d={unit:t.subarray(r+s,r+s+l),pts:a,dts:a};return e.samples.push(d),e.len+=l,{sample:d,length:l+s}}}var m=r(3);var v=function(){function e(t,r,i){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.observer=t,this.config=i,this.remuxer=r}return e.prototype.resetInitSegment=function(e,t,r,i){this._audioTrack={container:"audio/adts",type:"audio",id:0,sequenceNumber:0,isAAC:!0,samples:[],len:0,manifestCodec:t,duration:i,inputTimeScale:9e4}},e.prototype.resetTimeStamp=function(){},e.probe=function(e){if(!e)return!1;for(var t=(m.a.getID3Data(e,0)||[]).length,r=e.length;t<r;t++)if(d(e,t))return a.b.log("ADTS sync word found !"),!0;return!1},e.prototype.append=function(e,t,r,i){for(var n=this._audioTrack,o=m.a.getID3Data(e,0)||[],s=m.a.getTimeStamp(o),u=s?90*s:9e4*t,c=0,d=u,h=e.length,v=o.length,g=[{pts:d,dts:d,data:o}];v<h-1;)if(l(e,v)&&v+5<h){f(n,this.observer,e,v,n.manifestCodec);var y=p(n,e,v,u,c);if(!y){a.b.log("Unable to parse AAC frame");break}v+=y.length,d=y.sample.pts,c++}else m.a.isHeader(e,v)?(o=m.a.getID3Data(e,v),g.push({pts:d,dts:d,data:o}),v+=o.length):v++;this.remuxer.remux(n,{samples:[]},{samples:g,inputTimeScale:9e4},{samples:[]},t,r,i)},e.prototype.destroy=function(){},e}();var g=Math.pow(2,32)-1,y=function(){function e(t,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.observer=t,this.remuxer=r}return e.prototype.resetTimeStamp=function(e){this.initPTS=e},e.prototype.resetInitSegment=function(t,r,n,o){if(t&&t.byteLength){var a=this.initData=e.parseInitSegment(t);null==r&&(r="mp4a.40.5"),null==n&&(n="avc1.42e01e");var s={};a.audio&&a.video?s.audiovideo={container:"video/mp4",codec:r+","+n,initSegment:o?t:null}:(a.audio&&(s.audio={container:"audio/mp4",codec:r,initSegment:o?t:null}),a.video&&(s.video={container:"video/mp4",codec:n,initSegment:o?t:null})),this.observer.trigger(i.a.FRAG_PARSING_INIT_SEGMENT,{tracks:s})}else r&&(this.audioCodec=r),n&&(this.videoCodec=n)},e.probe=function(t){return e.findBox({data:t,start:0,end:Math.min(t.length,16384)},["moof"]).length>0},e.bin2str=function(e){return String.fromCharCode.apply(null,e)},e.readUint32=function(e,t){e.data&&(t+=e.start,e=e.data);var r=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];return r<0?4294967296+r:r},e.writeUint32=function(e,t,r){e.data&&(t+=e.start,e=e.data),e[t]=r>>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r},e.findBox=function(t,r){var i,n,o,a,s,u,c,l=[];if(t.data?(u=t.start,a=t.end,t=t.data):(u=0,a=t.byteLength),!r.length)return null;for(i=u;i<a;)n=e.readUint32(t,i),o=e.bin2str(t.subarray(i+4,i+8)),c=n>1?i+n:a,o===r[0]&&(1===r.length?l.push({data:t,start:i+8,end:c}):(s=e.findBox({data:t,start:i+8,end:c},r.slice(1))).length&&(l=l.concat(s))),i=c;return l},e.parseInitSegment=function(t){var r=[];return e.findBox(t,["moov","trak"]).forEach(function(t){var i=e.findBox(t,["tkhd"])[0];if(i){var n=i.data[i.start],o=0===n?12:20,s=e.readUint32(i,o),u=e.findBox(t,["mdia","mdhd"])[0];if(u){o=0===(n=u.data[u.start])?12:20;var c=e.readUint32(u,o),l=e.findBox(t,["mdia","hdlr"])[0];if(l){var d={soun:"audio",vide:"video"}[e.bin2str(l.data.subarray(l.start+8,l.start+12))];if(d){var f=e.findBox(t,["mdia","minf","stbl","stsd"]);if(f.length){f=f[0];var h=e.bin2str(f.data.subarray(f.start+12,f.start+16));a.b.log("MP4Demuxer:"+d+":"+h+" found")}r[s]={timescale:c,type:d},r[d]={timescale:c,id:s}}}}}}),r},e.getStartDTS=function(t,r){var i,n,o;return i=e.findBox(r,["moof","traf"]),n=[].concat.apply([],i.map(function(r){return e.findBox(r,["tfhd"]).map(function(i){var n,o;return n=e.readUint32(i,4),o=t[n].timescale||9e4,e.findBox(r,["tfdt"]).map(function(t){var r,i;return r=t.data[t.start],i=e.readUint32(t,4),1===r&&(i*=Math.pow(2,32),i+=e.readUint32(t,8)),i})[0]/o})})),o=Math.min.apply(null,n),isFinite(o)?o:0},e.offsetStartDTS=function(t,r,i){e.findBox(r,["moof","traf"]).map(function(r){return e.findBox(r,["tfhd"]).map(function(n){var o=e.readUint32(n,4),a=t[o].timescale||9e4;e.findBox(r,["tfdt"]).map(function(t){var r=t.data[t.start],n=e.readUint32(t,4);if(0===r)e.writeUint32(t,4,n-i*a);else{n*=Math.pow(2,32),n+=e.readUint32(t,8),n-=i*a,n=Math.max(n,0);var o=Math.floor(n/(g+1)),s=Math.floor(n%(g+1));e.writeUint32(t,4,o),e.writeUint32(t,8,s)}})})})},e.prototype.append=function(t,r,n,o){var a=this.initData;a||(this.resetInitSegment(t,this.audioCodec,this.videoCodec),a=this.initData);var s,u=this.initPTS;if(void 0===u){var c=e.getStartDTS(a,t);this.initPTS=u=c-r,this.observer.trigger(i.a.INIT_PTS_FOUND,{initPTS:u})}e.offsetStartDTS(a,t,u),s=e.getStartDTS(a,t),this.remuxer.remux(a.audio,a.video,null,null,s,n,o,t)},e.prototype.destroy=function(){},e}(),_={BitratesMap:[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],SamplingRateMap:[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],SamplesCoefficients:[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],BytesInSlot:[0,1,1,4],appendFrame:function(e,t,r,i,n){if(!(r+24>t.length)){var o=this.parseHeader(t,r);if(o&&r+o.frameLength<=t.length){var a=i+n*(9e4*o.samplesPerFrame/o.sampleRate),s={unit:t.subarray(r,r+o.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=o.channelCount,e.samplerate=o.sampleRate,e.samples.push(s),e.len+=o.frameLength,{sample:s,length:o.frameLength}}}},parseHeader:function(e,t){var r=e[t+1]>>3&3,i=e[t+1]>>1&3,n=e[t+2]>>4&15,o=e[t+2]>>2&3,a=e[t+2]>>1&1;if(1!==r&&0!==n&&15!==n&&3!==o){var s=3===r?3-i:3===i?3:4,u=1e3*_.BitratesMap[14*s+n-1],c=3===r?0:2===r?1:2,l=_.SamplingRateMap[3*c+o],d=e[t+3]>>6==3?1:2,f=_.SamplesCoefficients[r][i],h=_.BytesInSlot[i],p=8*f*h;return{sampleRate:l,channelCount:d,frameLength:parseInt(f*u/l+a,10)*h,samplesPerFrame:p}}},isHeaderPattern:function(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])},isHeader:function(e,t){return!!(t+1<e.length&&this.isHeaderPattern(e,t))},probe:function(e,t){if(t+1<e.length&&this.isHeaderPattern(e,t)){var r=this.parseHeader(e,t),i=4;r&&r.frameLength&&(i=r.frameLength);var n=t+i;if(n===e.length||n+1<e.length&&this.isHeaderPattern(e,n))return!0}return!1}},b=_;var w=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}return e.prototype.loadWord=function(){var e=this.data,t=this.bytesAvailable,r=e.byteLength-t,i=new Uint8Array(4),n=Math.min(4,t);if(0===n)throw new Error("no bytes available");i.set(e.subarray(r,r+n)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n},e.prototype.skipBits=function(e){var t;this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)>>3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)},e.prototype.readBits=function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;return e>32&&a.b.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0?this.word<<=t:this.bytesAvailable>0&&this.loadWord(),(t=e-t)>0&&this.bitsAvailable?r<<t|this.readBits(t):r},e.prototype.skipLZ=function(){var e;for(e=0;e<this.bitsAvailable;++e)if(0!=(this.word&2147483648>>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()},e.prototype.skipUEG=function(){this.skipBits(1+this.skipLZ())},e.prototype.skipEG=function(){this.skipBits(1+this.skipLZ())},e.prototype.readUEG=function(){var e=this.skipLZ();return this.readBits(e+1)-1},e.prototype.readEG=function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)},e.prototype.readBoolean=function(){return 1===this.readBits(1)},e.prototype.readUByte=function(){return this.readBits(8)},e.prototype.readUShort=function(){return this.readBits(16)},e.prototype.readUInt=function(){return this.readBits(32)},e.prototype.skipScalingList=function(e){var t,r=8,i=8;for(t=0;t<e;t++)0!==i&&(i=(r+this.readEG()+256)%256),r=0===i?r:i},e.prototype.readSPS=function(){var e,t,r,i,n,o,a,s=0,u=0,c=0,l=0,d=this.readUByte.bind(this),f=this.readBits.bind(this),h=this.readUEG.bind(this),p=this.readBoolean.bind(this),m=this.skipBits.bind(this),v=this.skipEG.bind(this),g=this.skipUEG.bind(this),y=this.skipScalingList.bind(this);if(d(),e=d(),f(5),m(3),d(),g(),100===e||110===e||122===e||244===e||44===e||83===e||86===e||118===e||128===e){var _=h();if(3===_&&m(1),g(),g(),m(1),p())for(o=3!==_?8:12,a=0;a<o;a++)p()&&y(a<6?16:64)}g();var b=h();if(0===b)h();else if(1===b)for(m(1),v(),v(),t=h(),a=0;a<t;a++)v();g(),m(1),r=h(),i=h(),0===(n=f(1))&&m(1),m(1),p()&&(s=h(),u=h(),c=h(),l=h());var w=[1,1];if(p()&&p())switch(d()){case 1:w=[1,1];break;case 2:w=[12,11];break;case 3:w=[10,11];break;case 4:w=[16,11];break;case 5:w=[40,33];break;case 6:w=[24,11];break;case 7:w=[20,11];break;case 8:w=[32,11];break;case 9:w=[80,33];break;case 10:w=[18,11];break;case 11:w=[15,11];break;case 12:w=[64,33];break;case 13:w=[160,99];break;case 14:w=[4,3];break;case 15:w=[3,2];break;case 16:w=[2,1];break;case 255:w=[d()<<8|d(),d()<<8|d()]}return{width:Math.ceil(16*(r+1)-2*s-2*u),height:(2-n)*(i+1)*16-(n?2:4)*(c+l),pixelRatio:w}},e.prototype.readSliceType=function(){return this.readUByte(),this.readUEG(),this.readUEG()},e}();var E=function(){function e(t,r,i,n){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.decryptdata=i,this.discardEPB=n,this.decrypter=new o.a(t,r)}return e.prototype.decryptBuffer=function(e,t){this.decrypter.decrypt(e,this.decryptdata.key.buffer,this.decryptdata.iv.buffer,t)},e.prototype.decryptAacSample=function(e,t,r,i){var n=e[t].unit,o=n.subarray(16,n.length-n.length%16),a=o.buffer.slice(o.byteOffset,o.byteOffset+o.length),s=this;this.decryptBuffer(a,function(o){o=new Uint8Array(o),n.set(o,16),i||s.decryptAacSamples(e,t+1,r)})},e.prototype.decryptAacSamples=function(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32)){var i=this.decrypter.isSync();if(this.decryptAacSample(e,t,r,i),!i)return}}},e.prototype.getAvcEncryptedData=function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,n=32;n<=e.length-16;n+=160,i+=16)r.set(e.subarray(n,n+16),i);return r},e.prototype.getAvcDecryptedUnit=function(e,t){t=new Uint8Array(t);for(var r=0,i=32;i<=e.length-16;i+=160,r+=16)e.set(t.subarray(r,r+16),i);return e},e.prototype.decryptAvcSample=function(e,t,r,i,n,o){var a=this.discardEPB(n.data),s=this.getAvcEncryptedData(a),u=this;this.decryptBuffer(s.buffer,function(s){n.data=u.getAvcDecryptedUnit(a,s),o||u.decryptAvcSamples(e,t,r+1,i)})},e.prototype.decryptAvcSamples=function(e,t,r,i){for(;;t++,r=0){if(t>=e.length)return void i();for(var n=e[t].units;!(r>=n.length);r++){var o=n[r];if(!(o.length<=48||1!==o.type&&5!==o.type)){var a=this.decrypter.isSync();if(this.decryptAvcSample(e,t,r,i,o,a),!a)return}}}},e}();var S={video:0,audio:1,id3:2,text:3},T=function(){function e(t,r,i,n){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.observer=t,this.config=i,this.typeSupported=n,this.remuxer=r,this.sampleAes=null}return e.prototype.setDecryptData=function(e){null!=e&&null!=e.key&&"SAMPLE-AES"===e.method?this.sampleAes=new E(this.observer,this.config,e,this.discardEPB):this.sampleAes=null},e.probe=function(t){var r=e._syncOffset(t);return!(r<0)&&(r&&a.b.warn("MPEG2-TS detected but first sync word found @ offset "+r+", junk ahead ?"),!0)},e._syncOffset=function(e){for(var t=Math.min(1e3,e.length-564),r=0;r<t;){if(71===e[r]&&71===e[r+188]&&71===e[r+376])return r;r++}return-1},e.createTrack=function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:S[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],len:0,dropped:"video"===e?0:void 0,isAAC:"audio"===e||void 0,duration:"audio"===e?t:void 0}},e.prototype.resetInitSegment=function(t,r,i,n){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=e.createTrack("video",n),this._audioTrack=e.createTrack("audio",n),this._id3Track=e.createTrack("id3",n),this._txtTrack=e.createTrack("text",n),this.aacOverFlow=null,this.aacLastPTS=null,this.avcSample=null,this.audioCodec=r,this.videoCodec=i,this._duration=n},e.prototype.resetTimeStamp=function(){},e.prototype.append=function(t,r,o,s){var u,c,l,d,f,h=t.length,p=!1;this.contiguous=o;var m=this.pmtParsed,v=this._avcTrack,g=this._audioTrack,y=this._id3Track,_=v.pid,b=g.pid,w=y.pid,E=this._pmtId,S=v.pesData,T=g.pesData,O=y.pesData,A=this._parsePAT,$=this._parsePMT,k=this._parsePES,D=this._parseAVCPES.bind(this),I=this._parseAACPES.bind(this),x=this._parseMPEGPES.bind(this),C=this._parseID3PES.bind(this),M=e._syncOffset(t);for(h-=(h+M)%188,u=M;u<h;u+=188)if(71===t[u]){if(c=!!(64&t[u+1]),l=((31&t[u+1])<<8)+t[u+2],(48&t[u+3])>>4>1){if((d=u+5+t[u+4])===u+188)continue}else d=u+4;switch(l){case _:c&&(S&&(f=k(S))&&D(f,!1),S={data:[],size:0}),S&&(S.data.push(t.subarray(d,u+188)),S.size+=u+188-d);break;case b:c&&(T&&(f=k(T))&&(g.isAAC?I(f):x(f)),T={data:[],size:0}),T&&(T.data.push(t.subarray(d,u+188)),T.size+=u+188-d);break;case w:c&&(O&&(f=k(O))&&C(f),O={data:[],size:0}),O&&(O.data.push(t.subarray(d,u+188)),O.size+=u+188-d);break;case 0:c&&(d+=t[d]+1),E=this._pmtId=A(t,d);break;case E:c&&(d+=t[d]+1);var P=$(t,d,!0===this.typeSupported.mpeg||!0===this.typeSupported.mp3,null!=this.sampleAes);(_=P.avc)>0&&(v.pid=_),(b=P.audio)>0&&(g.pid=b,g.isAAC=P.isAAC),(w=P.id3)>0&&(y.pid=w),p&&!m&&(a.b.log("reparse from beginning"),p=!1,u=M-188),m=this.pmtParsed=!0;break;case 17:case 8191:break;default:p=!0}}else this.observer.trigger(i.a.ERROR,{type:n.b.MEDIA_ERROR,details:n.a.FRAG_PARSING_ERROR,fatal:!1,reason:"TS packet did not start with 0x47"});S&&(f=k(S))?(D(f,!0),v.pesData=null):v.pesData=S,T&&(f=k(T))?(g.isAAC?I(f):x(f),g.pesData=null):(T&&T.size&&a.b.log("last AAC PES packet truncated,might overlap between fragments"),g.pesData=T),O&&(f=k(O))?(C(f),y.pesData=null):y.pesData=O,null==this.sampleAes?this.remuxer.remux(g,v,y,this._txtTrack,r,o,s):this.decryptAndRemux(g,v,y,this._txtTrack,r,o,s)},e.prototype.decryptAndRemux=function(e,t,r,i,n,o,a){if(e.samples&&e.isAAC){var s=this;this.sampleAes.decryptAacSamples(e.samples,0,function(){s.decryptAndRemuxAvc(e,t,r,i,n,o,a)})}else this.decryptAndRemuxAvc(e,t,r,i,n,o,a)},e.prototype.decryptAndRemuxAvc=function(e,t,r,i,n,o,a){if(t.samples){var s=this;this.sampleAes.decryptAvcSamples(t.samples,0,0,function(){s.remuxer.remux(e,t,r,i,n,o,a)})}else this.remuxer.remux(e,t,r,i,n,o,a)},e.prototype.destroy=function(){this._initPTS=this._initDTS=void 0,this._duration=0},e.prototype._parsePAT=function(e,t){return(31&e[t+10])<<8|e[t+11]},e.prototype._parsePMT=function(e,t,r,i){var n,o,s={audio:-1,avc:-1,id3:-1,isAAC:!0};for(n=t+3+((15&e[t+1])<<8|e[t+2])-4,t+=12+((15&e[t+10])<<8|e[t+11]);t<n;){switch(o=(31&e[t+1])<<8|e[t+2],e[t]){case 207:if(!i){a.b.log("unkown stream type:"+e[t]);break}case 15:-1===s.audio&&(s.audio=o);break;case 21:-1===s.id3&&(s.id3=o);break;case 219:if(!i){a.b.log("unkown stream type:"+e[t]);break}case 27:-1===s.avc&&(s.avc=o);break;case 3:case 4:r?-1===s.audio&&(s.audio=o,s.isAAC=!1):a.b.log("MPEG audio found, not supported in this browser for now");break;case 36:a.b.warn("HEVC stream type found, not supported for now");break;default:a.b.log("unkown stream type:"+e[t])}t+=5+((15&e[t+3])<<8|e[t+4])}return s},e.prototype._parsePES=function(e){var t,r,i,n,o,s,u,c,l=0,d=e.data;if(!e||0===e.size)return null;for(;d[0].length<19&&d.length>1;){var f=new Uint8Array(d[0].length+d[1].length);f.set(d[0]),f.set(d[1],d[0].length),d[0]=f,d.splice(1,1)}if(1===((t=d[0])[0]<<16)+(t[1]<<8)+t[2]){if((i=(t[4]<<8)+t[5])&&i>e.size-6)return null;192&(r=t[7])&&((s=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2)>4294967295&&(s-=8589934592),64&r?((u=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2)>4294967295&&(u-=8589934592),s-u>54e5&&(a.b.warn(Math.round((s-u)/9e4)+"s delta between PTS and DTS, align them"),s=u)):u=s),c=(n=t[8])+9,e.size-=c,o=new Uint8Array(e.size);for(var h=0,p=d.length;h<p;h++){var m=(t=d[h]).byteLength;if(c){if(c>m){c-=m;continue}t=t.subarray(c),m-=c,c=0}o.set(t,l),l+=m}return i&&(i-=n+3),{data:o,pts:s,dts:u,len:i}}return null},e.prototype.pushAccesUnit=function(e,t){if(e.units.length&&e.frame){var r=t.samples,i=r.length;!this.config.forceKeyFrameOnDiscontinuity||!0===e.key||t.sps&&(i||this.contiguous)?(e.id=i,r.push(e)):t.dropped++}e.debug.length&&a.b.log(e.pts+"/"+e.dts+":"+e.debug)},e.prototype._parseAVCPES=function(e,t){var r,i,n,o=this,a=this._avcTrack,s=this._parseAVCNALu(e.data),u=this.avcSample,c=!1,l=this.pushAccesUnit.bind(this),d=function(e,t,r,i){return{key:e,pts:t,dts:r,units:[],debug:i}};e.data=null,u&&s.length&&!a.audFound&&(l(u,a),u=this.avcSample=d(!1,e.pts,e.dts,"")),s.forEach(function(t){switch(t.type){case 1:i=!0,u||(u=o.avcSample=d(!0,e.pts,e.dts,"")),u.frame=!0;var s=t.data;if(c&&s.length>4){var f=new w(s).readSliceType();2!==f&&4!==f&&7!==f&&9!==f||(u.key=!0)}break;case 5:i=!0,u||(u=o.avcSample=d(!0,e.pts,e.dts,"")),u.key=!0,u.frame=!0;break;case 6:i=!0,(r=new w(o.discardEPB(t.data))).readUByte();for(var h=0,p=0,m=!1,v=0;!m&&r.bytesAvailable>1;){h=0;do{h+=v=r.readUByte()}while(255===v);p=0;do{p+=v=r.readUByte()}while(255===v);if(4===h&&0!==r.bytesAvailable){if(m=!0,181===r.readUByte())if(49===r.readUShort())if(1195456820===r.readUInt())if(3===r.readUByte()){var g=r.readUByte(),y=31&g,_=[g,r.readUByte()];for(n=0;n<y;n++)_.push(r.readUByte()),_.push(r.readUByte()),_.push(r.readUByte());o._insertSampleInOrder(o._txtTrack.samples,{type:3,pts:e.pts,bytes:_})}}else if(p<r.bytesAvailable)for(n=0;n<p;n++)r.readUByte()}break;case 7:if(i=!0,c=!0,!a.sps){var b=(r=new w(t.data)).readSPS();a.width=b.width,a.height=b.height,a.pixelRatio=b.pixelRatio,a.sps=[t.data],a.duration=o._duration;var E=t.data.subarray(1,4),S="avc1.";for(n=0;n<3;n++){var T=E[n].toString(16);T.length<2&&(T="0"+T),S+=T}a.codec=S}break;case 8:i=!0,a.pps||(a.pps=[t.data]);break;case 9:i=!1,a.audFound=!0,u&&l(u,a),u=o.avcSample=d(!1,e.pts,e.dts,"");break;case 12:i=!1;break;default:i=!1,u&&(u.debug+="unknown NAL "+t.type+" ")}u&&i&&u.units.push(t)}),t&&u&&(l(u,a),this.avcSample=null)},e.prototype._insertSampleInOrder=function(e,t){var r=e.length;if(r>0){if(t.pts>=e[r-1].pts)e.push(t);else for(var i=r-1;i>=0;i--)if(t.pts<e[i].pts){e.splice(i,0,t);break}}else e.push(t)},e.prototype._getLastNalUnit=function(){var e=this.avcSample,t=void 0;if(!e||0===e.units.length){var r=this._avcTrack.samples;e=r[r.length-1]}if(e){var i=e.units;t=i[i.length-1]}return t},e.prototype._parseAVCNALu=function(e){var t,r,i,n,o=0,a=e.byteLength,s=this._avcTrack,u=s.naluState||0,c=u,l=[],d=-1;for(-1===u&&(d=0,n=31&e[0],u=0,o=1);o<a;)if(t=e[o++],u)if(1!==u)if(t)if(1===t){if(d>=0)i={data:e.subarray(d,o-u-1),type:n},l.push(i);else{var f=this._getLastNalUnit();if(f&&(c&&o<=4-c&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-c)),(r=o-u-1)>0)){var h=new Uint8Array(f.data.byteLength+r);h.set(f.data,0),h.set(e.subarray(0,r),f.data.byteLength),f.data=h}}o<a?(d=o,n=31&e[o],u=0):u=-1}else u=0;else u=3;else u=t?0:2;else u=t?0:1;if(d>=0&&u>=0&&(i={data:e.subarray(d,a),type:n,state:u},l.push(i)),0===l.length){var p=this._getLastNalUnit();if(p){var m=new Uint8Array(p.data.byteLength+e.byteLength);m.set(p.data,0),m.set(e,p.data.byteLength),p.data=m}}return s.naluState=u,l},e.prototype.discardEPB=function(e){for(var t,r,i=e.byteLength,n=[],o=1;o<i-2;)0===e[o]&&0===e[o+1]&&3===e[o+2]?(n.push(o+2),o+=2):o++;if(0===n.length)return e;t=i-n.length,r=new Uint8Array(t);var a=0;for(o=0;o<t;a++,o++)a===n[0]&&(a++,n.shift()),r[o]=e[a];return r},e.prototype._parseAACPES=function(e){var t,r,o,s,u,c,d,m=this._audioTrack,v=e.data,g=e.pts,y=this.aacOverFlow,_=this.aacLastPTS;if(y){var b=new Uint8Array(y.byteLength+v.byteLength);b.set(y,0),b.set(v,y.byteLength),v=b}for(o=0,u=v.length;o<u-1&&!l(v,o);o++);if(o&&(o<u-1?(c="AAC PES did not start with ADTS header,offset:"+o,d=!1):(c="no ADTS header found in AAC PES",d=!0),a.b.warn("parsing error:"+c),this.observer.trigger(i.a.ERROR,{type:n.b.MEDIA_ERROR,details:n.a.FRAG_PARSING_ERROR,fatal:d,reason:c}),d))return;if(f(m,this.observer,v,o,this.audioCodec),r=0,t=h(m.samplerate),y&&_){var w=_+t;Math.abs(w-g)>1&&(a.b.log("AAC: align PTS for overlapping frames by "+Math.round((w-g)/90)),g=w)}for(;o<u;)if(l(v,o)&&o+5<u){var E=p(m,v,o,g,r);if(!E)break;o+=E.length,s=E.sample.pts,r++}else o++;y=o<u?v.subarray(o,u):null,this.aacOverFlow=y,this.aacLastPTS=s},e.prototype._parseMPEGPES=function(e){for(var t=e.data,r=t.length,i=0,n=0,o=e.pts;n<r;)if(b.isHeader(t,n)){var a=b.appendFrame(this._audioTrack,t,n,o,i);if(!a)break;n+=a.length,i++}else n++},e.prototype._parseID3PES=function(e){this._id3Track.samples.push(e)},e}();var O=function(){function e(t,r,i){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.observer=t,this.config=i,this.remuxer=r}return e.prototype.resetInitSegment=function(e,t,r,i){this._audioTrack={container:"audio/mpeg",type:"audio",id:-1,sequenceNumber:0,isAAC:!1,samples:[],len:0,manifestCodec:t,duration:i,inputTimeScale:9e4}},e.prototype.resetTimeStamp=function(){},e.probe=function(e){var t,r,i=m.a.getID3Data(e,0);if(i&&void 0!==m.a.getTimeStamp(i))for(t=i.length,r=Math.min(e.length-1,t+100);t<r;t++)if(b.probe(e,t))return a.b.log("MPEG Audio sync word found !"),!0;return!1},e.prototype.append=function(e,t,r,i){for(var n=m.a.getID3Data(e,0),o=m.a.getTimeStamp(n),a=o?90*o:9e4*t,s=n.length,u=e.length,c=0,l=0,d=this._audioTrack,f=[{pts:a,dts:a,data:n}];s<u;)if(b.isHeader(e,s)){var h=b.appendFrame(d,e,s,a,c);if(!h)break;s+=h.length,l=h.sample.pts,c++}else m.a.isHeader(e,s)?(n=m.a.getID3Data(e,s),f.push({pts:l,dts:l,data:n}),s+=n.length):s++;this.remuxer.remux(d,{samples:[]},{samples:f,inputTimeScale:9e4},{samples:[]},t,r,i)},e.prototype.destroy=function(){},e}();var A=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.getSilentFrame=function(e,t){switch(e){case"mp4a.40.2":if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}return null},e}();var $=Math.pow(2,32)-1,k=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.init=function(){var t;for(t in e.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);var r=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);e.HDLR_TYPES={video:r,audio:i};var n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),o=new Uint8Array([0,0,0,0,0,0,0,0]);e.STTS=e.STSC=e.STCO=o,e.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),e.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),e.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var a=new Uint8Array([105,115,111,109]),s=new Uint8Array([97,118,99,49]),u=new Uint8Array([0,0,0,1]);e.FTYP=e.box(e.types.ftyp,a,u,a,s),e.DINF=e.box(e.types.dinf,e.box(e.types.dref,n))},e.box=function(e){for(var t,r=Array.prototype.slice.call(arguments,1),i=8,n=r.length,o=n;n--;)i+=r[n].byteLength;for((t=new Uint8Array(i))[0]=i>>24&255,t[1]=i>>16&255,t[2]=i>>8&255,t[3]=255&i,t.set(e,4),n=0,i=8;n<o;n++)t.set(r[n],i),i+=r[n].byteLength;return t},e.hdlr=function(t){return e.box(e.types.hdlr,e.HDLR_TYPES[t])},e.mdat=function(t){return e.box(e.types.mdat,t)},e.mdhd=function(t,r){r*=t;var i=Math.floor(r/($+1)),n=Math.floor(r%($+1));return e.box(e.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))},e.mdia=function(t){return e.box(e.types.mdia,e.mdhd(t.timescale,t.duration),e.hdlr(t.type),e.minf(t))},e.mfhd=function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))},e.minf=function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))},e.moof=function(t,r,i){return e.box(e.types.moof,e.mfhd(t),e.traf(i,r))},e.moov=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale,t[0].duration)].concat(i).concat(e.mvex(t)))},e.mvex=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[e.types.mvex].concat(i))},e.mvhd=function(t,r){r*=t;var i=Math.floor(r/($+1)),n=Math.floor(r%($+1)),o=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return e.box(e.types.mvhd,o)},e.sdtp=function(t){var r,i,n=t.samples||[],o=new Uint8Array(4+n.length);for(i=0;i<n.length;i++)r=n[i].flags,o[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return e.box(e.types.sdtp,o)},e.stbl=function(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.STTS),e.box(e.types.stsc,e.STSC),e.box(e.types.stsz,e.STSZ),e.box(e.types.stco,e.STCO))},e.avc1=function(t){var r,i,n,o=[],a=[];for(r=0;r<t.sps.length;r++)n=(i=t.sps[r]).byteLength,o.push(n>>>8&255),o.push(255&n),o=o.concat(Array.prototype.slice.call(i));for(r=0;r<t.pps.length;r++)n=(i=t.pps[r]).byteLength,a.push(n>>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(i));var s=e.box(e.types.avcC,new Uint8Array([1,o[3],o[4],o[5],255,224|t.sps.length].concat(o).concat([t.pps.length]).concat(a))),u=t.width,c=t.height,l=t.pixelRatio[0],d=t.pixelRatio[1];return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,u>>8&255,255&u,c>>8&255,255&c,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),s,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([l>>24,l>>16&255,l>>8&255,255&l,d>>24,d>>16&255,d>>8&255,255&d])))},e.esds=function(e){var t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))},e.mp4a=function(t){var r=t.samplerate;return e.box(e.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]),e.box(e.types.esds,e.esds(t)))},e.mp3=function(t){var r=t.samplerate;return e.box(e.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]))},e.stsd=function(t){return"audio"===t.type?t.isAAC||"mp3"!==t.codec?e.box(e.types.stsd,e.STSD,e.mp4a(t)):e.box(e.types.stsd,e.STSD,e.mp3(t)):e.box(e.types.stsd,e.STSD,e.avc1(t))},e.tkhd=function(t){var r=t.id,i=t.duration*t.timescale,n=t.width,o=t.height,a=Math.floor(i/($+1)),s=Math.floor(i%($+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,s>>24,s>>16&255,s>>8&255,255&s,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,255&n,0,0,o>>8&255,255&o,0,0]))},e.traf=function(t,r){var i=e.sdtp(t),n=t.id,o=Math.floor(r/($+1)),a=Math.floor(r%($+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,o>>24,o>>16&255,o>>8&255,255&o,a>>24,a>>16&255,a>>8&255,255&a])),e.trun(t,i.length+16+20+8+16+8+8),i)},e.trak=function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))},e.trex=function(t){var r=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},e.trun=function(t,r){var i,n,o,a,s,u,c=t.samples||[],l=c.length,d=12+16*l,f=new Uint8Array(d);for(r+=8+d,f.set([0,0,15,1,l>>>24&255,l>>>16&255,l>>>8&255,255&l,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i<l;i++)o=(n=c[i]).duration,a=n.size,s=n.flags,u=n.cts,f.set([o>>>24&255,o>>>16&255,o>>>8&255,255&o,a>>>24&255,a>>>16&255,a>>>8&255,255&a,s.isLeading<<2|s.dependsOn,s.isDependedOn<<6|s.hasRedundancy<<4|s.paddingValue<<1|s.isNonSync,61440&s.degradPrio,15&s.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*i);return e.box(e.types.trun,f)},e.initSegment=function(t){e.types||e.init();var r,i=e.moov(t);return(r=new Uint8Array(e.FTYP.byteLength+i.byteLength)).set(e.FTYP),r.set(i,e.FTYP.byteLength),r},e}();var D=function(){function e(t,r,i,n){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.observer=t,this.config=r,this.typeSupported=i;var o=navigator.userAgent;this.isSafari=n&&n.indexOf("Apple")>-1&&o&&!o.match("CriOS"),this.ISGenerated=!1}return e.prototype.destroy=function(){},e.prototype.resetTimeStamp=function(e){this._initPTS=this._initDTS=e},e.prototype.resetInitSegment=function(){this.ISGenerated=!1},e.prototype.remux=function(e,t,r,n,o,s,u){if(this.ISGenerated||this.generateIS(e,t,o),this.ISGenerated){var c=e.samples.length,l=t.samples.length,d=o,f=o;if(c&&l){var h=(e.samples[0].dts-t.samples[0].dts)/t.inputTimeScale;d+=Math.max(0,h),f+=Math.max(0,-h)}if(c){e.timescale||(a.b.warn("regenerate InitSegment as audio detected"),this.generateIS(e,t,o));var p=this.remuxAudio(e,d,s,u);if(l){var m=void 0;p&&(m=p.endPTS-p.startPTS),t.timescale||(a.b.warn("regenerate InitSegment as video detected"),this.generateIS(e,t,o)),this.remuxVideo(t,f,s,m,u)}}else{var v=void 0;l&&(v=this.remuxVideo(t,f,s,u)),v&&e.codec&&this.remuxEmptyAudio(e,d,s,v)}}r.samples.length&&this.remuxID3(r,o),n.samples.length&&this.remuxText(n,o),this.observer.trigger(i.a.FRAG_PARSED)},e.prototype.generateIS=function(e,t,r){var o,s,u=this.observer,c=e.samples,l=t.samples,d=this.typeSupported,f="audio/mp4",h={},p={tracks:h},m=void 0===this._initPTS;if(m&&(o=s=1/0),e.config&&c.length&&(e.timescale=e.samplerate,a.b.log("audio sampling rate : "+e.samplerate),e.isAAC||(d.mpeg?(f="audio/mpeg",e.codec=""):d.mp3&&(e.codec="mp3")),h.audio={container:f,codec:e.codec,initSegment:!e.isAAC&&d.mpeg?new Uint8Array:k.initSegment([e]),metadata:{channelCount:e.channelCount}},m&&(o=s=c[0].pts-e.inputTimeScale*r)),t.sps&&t.pps&&l.length){var v=t.inputTimeScale;t.timescale=v,h.video={container:"video/mp4",codec:t.codec,initSegment:k.initSegment([t]),metadata:{width:t.width,height:t.height}},m&&(o=Math.min(o,l[0].pts-v*r),s=Math.min(s,l[0].dts-v*r),this.observer.trigger(i.a.INIT_PTS_FOUND,{initPTS:o}))}Object.keys(h).length?(u.trigger(i.a.FRAG_PARSING_INIT_SEGMENT,p),this.ISGenerated=!0,m&&(this._initPTS=o,this._initDTS=s)):u.trigger(i.a.ERROR,{type:n.b.MEDIA_ERROR,details:n.a.FRAG_PARSING_ERROR,fatal:!1,reason:"no audio/video samples found"})},e.prototype.remuxVideo=function(e,t,r,o,s){var u,c,l,d,f,h,p,m=8,v=e.timescale,g=e.samples,y=[],_=g.length,b=this._PTSNormalize,w=this._initDTS,E=this.nextAvcDts,S=this.isSafari;S&&(r|=g.length&&E&&(s&&Math.abs(t-E/v)<.1||Math.abs(g[0].pts-E-w)<v/5)),r||(E=t*v),g.forEach(function(e){e.pts=b(e.pts-w,E),e.dts=b(e.dts-w,E)}),g.sort(function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||(i||e.id-t.id)});var T=g.reduce(function(e,t){return Math.max(Math.min(e,t.pts-t.dts),-18e3)},0);if(T<0){a.b.warn("PTS < DTS detected in video samples, shifting DTS by "+Math.round(T/90)+" ms to overcome this issue");for(var O=0;O<g.length;O++)g[O].dts+=T}var A=g[0];f=Math.max(A.dts,0),d=Math.max(A.pts,0);var $=Math.round((f-E)/90);r&&$&&($>1?a.b.log("AVC:"+$+" ms hole between fragments detected,filling it"):$<-1&&a.b.log("AVC:"+-$+" ms overlapping between fragments detected"),f=E,g[0].dts=f,d=Math.max(d-$,E),g[0].pts=d,a.b.log("Video/PTS/DTS adjusted: "+Math.round(d/90)+"/"+Math.round(f/90)+",delta:"+$+" ms")),A=g[g.length-1],p=Math.max(A.dts,0),h=Math.max(A.pts,0,p),S&&(u=Math.round((p-f)/(g.length-1)));for(var D=0,I=0,x=0;x<_;x++){for(var C=g[x],M=C.units,P=M.length,L=0,R=0;R<P;R++)L+=M[R].data.length;I+=L,D+=P,C.length=L,C.dts=S?f+x*u:Math.max(C.dts,f),C.pts=Math.max(C.pts,C.dts)}var N=I+4*D+8;try{c=new Uint8Array(N)}catch(e){return void this.observer.trigger(i.a.ERROR,{type:n.b.MUX_ERROR,details:n.a.REMUX_ALLOC_ERROR,fatal:!1,bytes:N,reason:"fail allocating video mdat "+N})}var j=new DataView(c.buffer);j.setUint32(0,N),c.set(k.types.mdat,4);for(var F=0;F<_;F++){for(var B=g[F],U=B.units,z=0,G=void 0,W=0,H=U.length;W<H;W++){var V=U[W],Y=V.data,K=V.data.byteLength;j.setUint32(m,K),m+=4,c.set(Y,m),m+=K,z+=4+K}if(S)G=Math.max(0,u*Math.round((B.pts-B.dts)/u));else{if(F<_-1)u=g[F+1].dts-B.dts;else{var Z=this.config,Q=B.dts-g[F>0?F-1:F].dts;if(Z.stretchShortVideoTrack){var X=Z.maxBufferHole,q=Z.maxSeekHole,J=Math.floor(Math.min(X,q)*v),ee=(o?d+o*v:this.nextAudioPts)-B.pts;ee>J?((u=ee-Q)<0&&(u=Q),a.b.log("It is approximately "+ee/90+" ms to the next segment; using duration "+u/90+" ms for the last video frame.")):u=Q}else u=Q}G=Math.round(B.pts-B.dts)}y.push({size:z,duration:u,cts:G,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:B.key?2:1,isNonSync:B.key?0:1}})}this.nextAvcDts=p+u;var te=e.dropped;if(e.len=0,e.nbNalu=0,e.dropped=0,y.length&&navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var re=y[0].flags;re.dependsOn=2,re.isNonSync=0}e.samples=y,l=k.moof(e.sequenceNumber++,f,e),e.samples=[];var ie={data1:l,data2:c,startPTS:d/v,endPTS:(h+u)/v,startDTS:f/v,endDTS:this.nextAvcDts/v,type:"video",nb:y.length,dropped:te};return this.observer.trigger(i.a.FRAG_PARSING_DATA,ie),ie},e.prototype.remuxAudio=function(e,t,r,o){var s,u,c,l,d,f,h,p=e.inputTimeScale,m=e.timescale,v=p/m,g=(e.isAAC?1024:1152)*v,y=this._PTSNormalize,_=this._initDTS,b=!e.isAAC&&this.typeSupported.mpeg,w=e.samples,E=[],S=this.nextAudioPts;if(r|=w.length&&S&&(o&&Math.abs(t-S/p)<.1||Math.abs(w[0].pts-S-_)<20*g),w.forEach(function(e){e.pts=e.dts=y(e.pts-_,t*p)}),0!==(w=w.filter(function(e){return e.pts>=0})).length){if(r||(S=o?t*p:w[0].pts),e.isAAC)for(var T=this.config.maxAudioFramesDrift,O=0,$=S;O<w.length;){var D,I=w[O];D=I.pts-$;var x=Math.abs(1e3*D/p);if(D<=-T*g)a.b.warn("Dropping 1 audio frame @ "+($/p).toFixed(3)+"s due to "+Math.round(x)+" ms overlap."),w.splice(O,1),e.len-=I.unit.length;else if(D>=T*g&&x<1e4&&$){var C=Math.round(D/g);a.b.warn("Injecting "+C+" audio frame @ "+($/p).toFixed(3)+"s due to "+Math.round(1e3*D/p)+" ms gap.");for(var M=0;M<C;M++){var P=Math.max($,0);(c=A.getSilentFrame(e.manifestCodec||e.codec,e.channelCount))||(a.b.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),c=I.unit.subarray()),w.splice(O,0,{unit:c,pts:P,dts:P}),e.len+=c.length,$+=g,O++}I.pts=I.dts=$,$+=g,O++}else I.pts=I.dts=$,$+=g,O++}for(var L=0,R=w.length;L<R;L++){var N=w[L],j=N.unit,F=N.pts;if(void 0!==h)u.duration=Math.round((F-h)/v);else{var B=Math.round(1e3*(F-S)/p),U=0;if(r&&e.isAAC&&B){if(B>0&&B<1e4)U=Math.round((F-S)/g),a.b.log(B+" ms hole between AAC samples detected,filling it"),U>0&&((c=A.getSilentFrame(e.manifestCodec||e.codec,e.channelCount))||(c=j.subarray()),e.len+=U*c.length);else if(B<-12){a.b.log("drop overlapping AAC sample, expected/parsed/delta:"+(S/p).toFixed(3)+"s/"+(F/p).toFixed(3)+"s/"+-B+"ms"),e.len-=j.byteLength;continue}F=S}if(f=F,!(e.len>0))return;var z=b?e.len:e.len+8;s=b?0:8;try{l=new Uint8Array(z)}catch(e){return void this.observer.trigger(i.a.ERROR,{type:n.b.MUX_ERROR,details:n.a.REMUX_ALLOC_ERROR,fatal:!1,bytes:z,reason:"fail allocating audio mdat "+z})}b||(new DataView(l.buffer).setUint32(0,z),l.set(k.types.mdat,4));for(var G=0;G<U;G++)(c=A.getSilentFrame(e.manifestCodec||e.codec,e.channelCount))||(a.b.log("Unable to get silent frame for given audio codec; duplicating this frame instead."),c=j.subarray()),l.set(c,s),s+=c.byteLength,u={size:c.byteLength,cts:0,duration:1024,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},E.push(u)}l.set(j,s);var W=j.byteLength;s+=W,u={size:W,cts:0,duration:0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},E.push(u),h=F}var H=0,V=E.length;if(V>=2&&(H=E[V-2].duration,u.duration=H),V){this.nextAudioPts=S=h+v*H,e.len=0,e.samples=E,d=b?new Uint8Array:k.moof(e.sequenceNumber++,f/v,e),e.samples=[];var Y=f/p,K=S/p,Z={data1:d,data2:l,startPTS:Y,endPTS:K,startDTS:Y,endDTS:K,type:"audio",nb:V};return this.observer.trigger(i.a.FRAG_PARSING_DATA,Z),Z}return null}},e.prototype.remuxEmptyAudio=function(e,t,r,i){var n=e.inputTimeScale,o=n/(e.samplerate?e.samplerate:n),s=this.nextAudioPts,u=(void 0!==s?s:i.startDTS*n)+this._initDTS,c=i.endDTS*n+this._initDTS,l=1024*o,d=Math.ceil((c-u)/l),f=A.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(a.b.warn("remux empty Audio"),f){for(var h=[],p=0;p<d;p++){var m=u+p*l;h.push({unit:f,pts:m,dts:m}),e.len+=f.length}e.samples=h,this.remuxAudio(e,t,r)}else a.b.trace("Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!")},e.prototype.remuxID3=function(e,t){var r,n=e.samples.length,o=e.inputTimeScale,a=this._initPTS,s=this._initDTS;if(n){for(var u=0;u<n;u++)(r=e.samples[u]).pts=(r.pts-a)/o,r.dts=(r.dts-s)/o;this.observer.trigger(i.a.FRAG_PARSING_METADATA,{samples:e.samples})}e.samples=[],t=t},e.prototype.remuxText=function(e,t){e.samples.sort(function(e,t){return e.pts-t.pts});var r,n=e.samples.length,o=e.inputTimeScale,a=this._initPTS;if(n){for(var s=0;s<n;s++)(r=e.samples[s]).pts=(r.pts-a)/o;this.observer.trigger(i.a.FRAG_PARSING_USERDATA,{samples:e.samples})}e.samples=[],t=t},e.prototype._PTSNormalize=function(e,t){var r;if(void 0===t)return e;for(r=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=r;return e},e}();var I=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.observer=t}return e.prototype.destroy=function(){},e.prototype.resetTimeStamp=function(){},e.prototype.resetInitSegment=function(){},e.prototype.remux=function(e,t,r,n,o,a,s,u){var c=this.observer,l="";e&&(l+="audio"),t&&(l+="video"),c.trigger(i.a.FRAG_PARSING_DATA,{data1:u,startPTS:o,startDTS:o,type:l,nb:1,dropped:0}),c.trigger(i.a.FRAG_PARSED)},e}();var x=function(){function e(t,r,i,n){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.observer=t,this.typeSupported=r,this.config=i,this.vendor=n}return e.prototype.destroy=function(){var e=this.demuxer;e&&e.destroy()},e.prototype.push=function(e,t,r,n,a,s,u,c,l,d,f,h){if(e.byteLength>0&&null!=t&&null!=t.key&&"AES-128"===t.method){var p=this.decrypter;null==p&&(p=this.decrypter=new o.a(this.observer,this.config));var m,v=this;try{m=performance.now()}catch(e){m=Date.now()}p.decrypt(e,t.key.buffer,t.iv.buffer,function(e){var o;try{o=performance.now()}catch(e){o=Date.now()}v.observer.trigger(i.a.FRAG_DECRYPTED,{stats:{tstart:m,tdecrypt:o}}),v.pushDecrypted(new Uint8Array(e),t,new Uint8Array(r),n,a,s,u,c,l,d,f,h)})}else this.pushDecrypted(new Uint8Array(e),t,new Uint8Array(r),n,a,s,u,c,l,d,f,h)},e.prototype.pushDecrypted=function(e,t,r,o,a,s,u,c,l,d,f,h){var p=this.demuxer;if(!p||u&&!this.probe(e)){for(var m=this.observer,g=this.typeSupported,_=this.config,b=[{demux:T,remux:D},{demux:y,remux:I},{demux:v,remux:D},{demux:O,remux:D}],w=0,E=b.length;w<E;w++){var S=b[w],A=S.demux.probe;if(A(e)){var $=this.remuxer=new S.remux(m,_,g,this.vendor);p=new S.demux(m,$,_,g),this.probe=A;break}}if(!p)return void m.trigger(i.a.ERROR,{type:n.b.MEDIA_ERROR,details:n.a.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"});this.demuxer=p}var k=this.remuxer;(u||c)&&(p.resetInitSegment(r,o,a,d),k.resetInitSegment()),u&&(p.resetTimeStamp(h),k.resetTimeStamp(h)),"function"==typeof p.setDecryptData&&p.setDecryptData(t),p.append(e,s,l,f)},e}();t.a=x},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i={};r.d(i,"newCue",function(){return Ee});var n=r(6),o=r.n(n),a=r(1),s=r(2),u=r(0),c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};var l=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.hls=t,this.onEvent=this.onEvent.bind(this);for(var r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];this.handledEvents=i,this.useGenericHandler=!0,this.registerListeners()}return e.prototype.destroy=function(){this.unregisterListeners()},e.prototype.isEventHandler=function(){return"object"===c(this.handledEvents)&&this.handledEvents.length&&"function"==typeof this.onEvent},e.prototype.registerListeners=function(){this.isEventHandler()&&this.handledEvents.forEach(function(e){if("hlsEventGeneric"===e)throw new Error("Forbidden event name: "+e);this.hls.on(e,this.onEvent)},this)},e.prototype.unregisterListeners=function(){this.isEventHandler()&&this.handledEvents.forEach(function(e){this.hls.off(e,this.onEvent)},this)},e.prototype.onEvent=function(e,t){this.onEventGeneric(e,t)},e.prototype.onEventGeneric=function(e,t){try{(function(e,t){var r="on"+e.replace("hls","");if("function"!=typeof this[r])throw new Error("Event "+e+" has no generic handler in this "+this.constructor.name+" class (tried "+r+")");return this[r].bind(this,t)}).call(this,e,t).call()}catch(t){u.b.error("internal error happened while processing "+e+":"+t.message),this.hls.trigger(a.a.ERROR,{type:s.b.OTHER_ERROR,details:s.a.INTERNAL_EXCEPTION,fatal:!1,event:e,err:t})}},e}();var d=/^(\d+)x(\d+)$/,f=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g,h=function(){function e(t){for(var r in function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),"string"==typeof t&&(t=e.parseAttrList(t)),t)t.hasOwnProperty(r)&&(this[r]=t[r])}return e.prototype.decimalInteger=function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t},e.prototype.hexadecimalInteger=function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var r=new Uint8Array(t.length/2),i=0;i<t.length/2;i++)r[i]=parseInt(t.slice(2*i,2*i+2),16);return r}return null},e.prototype.hexadecimalIntegerAsNumber=function(e){var t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t},e.prototype.decimalFloatingPoint=function(e){return parseFloat(this[e])},e.prototype.enumeratedString=function(e){return this[e]},e.prototype.decimalResolution=function(e){var t=d.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e){var t,r={};for(f.lastIndex=0;null!==(t=f.exec(e));){var i=t[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[t[1]]=i}return r},e}(),p={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,drac:!0,dvav:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0}};function m(e,t){return MediaSource.isTypeSupported((t||"video")+'/mp4;codecs="'+e+'"')}var v=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}();function g(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var y=/#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g,_=/#EXT-X-MEDIA:(.*)/g,b=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)(\S+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),w=/(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\d+))|(?:#EXT-X-(TARGETDURATION): *(\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)(.*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/,E=function(){function e(){g(this,e),this.method=null,this.key=null,this.iv=null,this._uri=null}return v(e,[{key:"uri",get:function(){return!this._uri&&this.reluri&&(this._uri=o.a.buildAbsoluteURL(this.baseuri,this.reluri,{alwaysNormalize:!0})),this._uri}}]),e}(),S=function(){function e(){g(this,e),this._url=null,this._byteRange=null,this._decryptdata=null,this.tagList=[]}return e.prototype.createInitializationVector=function(e){for(var t=new Uint8Array(16),r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t},e.prototype.fragmentDecryptdataFromLevelkey=function(e,t){var r=e;return e&&e.method&&e.uri&&!e.iv&&((r=new E).method=e.method,r.baseuri=e.baseuri,r.reluri=e.reluri,r.iv=this.createInitializationVector(t)),r},e.prototype.cloneObj=function(e){return JSON.parse(JSON.stringify(e))},v(e,[{key:"url",get:function(){return!this._url&&this.relurl&&(this._url=o.a.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url},set:function(e){this._url=e}},{key:"programDateTime",get:function(){return!this._programDateTime&&this.rawProgramDateTime&&(this._programDateTime=new Date(Date.parse(this.rawProgramDateTime))),this._programDateTime}},{key:"byteRange",get:function(){if(!this._byteRange){var e=this._byteRange=[];if(this.rawByteRange){var t=this.rawByteRange.split("@",2);if(1===t.length){var r=this.lastByteRangeEndOffset;e[0]=r||0}else e[0]=parseInt(t[1]);e[1]=parseInt(t[0])+e[0]}}return this._byteRange}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"decryptdata",get:function(){return this._decryptdata||(this._decryptdata=this.fragmentDecryptdataFromLevelkey(this.levelkey,this.sn)),this._decryptdata}}]),e}();function T(e,t){if(!e)return null;for(var r=null,i=0;i<e.length;i++){var n=e[i];n.id===t&&(r=n)}return r}var O=function(e){function t(r){g(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r,a.a.MANIFEST_LOADING,a.a.LEVEL_LOADING,a.a.AUDIO_TRACK_LOADING,a.a.SUBTITLE_TRACK_LOADING));return i.loaders={},i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.destroy=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy()}this.loaders={},l.prototype.destroy.call(this)},t.prototype.onManifestLoading=function(e){this.load(e.url,{type:"manifest"})},t.prototype.onLevelLoading=function(e){this.load(e.url,{type:"level",level:e.level,id:e.id})},t.prototype.onAudioTrackLoading=function(e){this.load(e.url,{type:"audioTrack",id:e.id})},t.prototype.onSubtitleTrackLoading=function(e){this.load(e.url,{type:"subtitleTrack",id:e.id})},t.prototype.load=function(e,t){var r=this.loaders[t.type];if(void 0!==r){var i=r.context;if(i&&i.url===e)return void u.b.trace("playlist request ongoing");u.b.warn("abort previous loader for type:"+t.type),r.abort()}var n=this.hls.config,o=void 0,a=void 0,s=void 0,c=void 0;"manifest"===t.type?(o=n.manifestLoadingMaxRetry,a=n.manifestLoadingTimeOut,s=n.manifestLoadingRetryDelay,c=n.manifestLoadingMaxRetryTimeout):"level"===t.type?(o=0,a=n.levelLoadingTimeOut):(o=n.levelLoadingMaxRetry,a=n.levelLoadingTimeOut,s=n.levelLoadingRetryDelay,c=n.levelLoadingMaxRetryTimeout,u.b.log("loading playlist for "+t.type+" "+(t.level||t.id))),r=this.loaders[t.type]=t.loader=void 0!==n.pLoader?new n.pLoader(n):new n.loader(n),t.url=e,t.responseType="";var l,d;l={timeout:a,maxRetry:o,retryDelay:s,maxRetryDelay:c},d={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)},r.load(t,l,d)},t.prototype.resolve=function(e,t){return o.a.buildAbsoluteURL(t,e,{alwaysNormalize:!0})},t.prototype.parseMasterPlaylist=function(e,t){var r=[],i=void 0;function n(e,t){["video","audio"].forEach(function(r){var i=e.filter(function(e){return function(e,t){var r=p[t];return!!r&&!0===r[e.slice(0,4)]}(e,r)});if(i.length){var n=i.filter(function(e){return 0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)});t[r+"Codec"]=n.length>0?n[0]:i[0],e=e.filter(function(e){return-1===i.indexOf(e)})}}),t.unknownCodecs=e}for(y.lastIndex=0;null!=(i=y.exec(e));){var o={},a=o.attrs=new h(i[1]);o.url=this.resolve(i[2],t);var s=a.decimalResolution("RESOLUTION");s&&(o.width=s.width,o.height=s.height),o.bitrate=a.decimalInteger("AVERAGE-BANDWIDTH")||a.decimalInteger("BANDWIDTH"),o.name=a.NAME,n([].concat((a.CODECS||"").split(/[ ,]+/)),o),o.videoCodec&&-1!==o.videoCodec.indexOf("avc1")&&(o.videoCodec=this.avc1toavcoti(o.videoCodec)),r.push(o)}return r},t.prototype.parseMasterPlaylistMedia=function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],n=void 0,o=[],a=0;for(_.lastIndex=0;null!==(n=_.exec(e));){var s={},u=new h(n[1]);if(u.TYPE===r){if(s.groupId=u["GROUP-ID"],s.name=u.NAME,s.type=r,s.default="YES"===u.DEFAULT,s.autoselect="YES"===u.AUTOSELECT,s.forced="YES"===u.FORCED,u.URI&&(s.url=this.resolve(u.URI,t)),s.lang=u.LANGUAGE,s.name||(s.name=s.lang),i.length){var c=T(i,s.groupId);s.audioCodec=c?c.codec:i[0].codec}s.id=a++,o.push(s)}}return o},t.prototype.avc1toavcoti=function(e){var t,r=e.split(".");return r.length>2?(t=r.shift()+".",t+=parseInt(r.shift()).toString(16),t+=("000"+parseInt(r.shift()).toString(16)).substr(-4)):t=e,t},t.prototype.parseLevelPlaylist=function(e,t,r,i){var n,o,a=0,s=0,c={type:null,version:null,url:t,fragments:[],live:!0,startSN:0},l=new E,d=0,f=null,p=new S;for(b.lastIndex=0;null!==(n=b.exec(e));){var m=n[1];if(m){p.duration=parseFloat(m);var v=(" "+n[2]).slice(1);p.title=v||null,p.tagList.push(v?["INF",m,v]:["INF",m])}else if(n[3]){if(!isNaN(p.duration)){var g=a++;p.type=i,p.start=s,p.levelkey=l,p.sn=g,p.level=r,p.cc=d,p.baseurl=t,p.relurl=(" "+n[3]).slice(1),c.fragments.push(p),f=p,s+=p.duration,p=new S}}else if(n[4]){if(p.rawByteRange=(" "+n[4]).slice(1),f){var y=f.byteRangeEndOffset;y&&(p.lastByteRangeEndOffset=y)}}else if(n[5])p.rawProgramDateTime=(" "+n[5]).slice(1),p.tagList.push(["PROGRAM-DATE-TIME",p.rawProgramDateTime]),void 0===c.programDateTime&&(c.programDateTime=new Date(new Date(Date.parse(n[5]))-1e3*s));else{for(n=n[0].match(w),o=1;o<n.length&&void 0===n[o];o++);var _=(" "+n[o+1]).slice(1),T=(" "+n[o+2]).slice(1);switch(n[o]){case"#":p.tagList.push(T?[_,T]:[_]);break;case"PLAYLIST-TYPE":c.type=_.toUpperCase();break;case"MEDIA-SEQUENCE":a=c.startSN=parseInt(_);break;case"TARGETDURATION":c.targetduration=parseFloat(_);break;case"VERSION":c.version=parseInt(_);break;case"EXTM3U":break;case"ENDLIST":c.live=!1;break;case"DIS":d++,p.tagList.push(["DIS"]);break;case"DISCONTINUITY-SEQ":d=parseInt(_);break;case"KEY":var O=new h(_),A=O.enumeratedString("METHOD"),$=O.URI,k=O.hexadecimalInteger("IV");A&&(l=new E,$&&["AES-128","SAMPLE-AES"].indexOf(A)>=0&&(l.method=A,l.baseuri=t,l.reluri=$,l.key=null,l.iv=k));break;case"START":var D=new h(_).decimalFloatingPoint("TIME-OFFSET");isNaN(D)||(c.startTimeOffset=D);break;case"MAP":var I=new h(_);p.relurl=I.URI,p.rawByteRange=I.BYTERANGE,p.baseurl=t,p.level=r,p.type=i,p.sn="initSegment",c.initSegment=p,p=new S;break;default:u.b.warn("line parsed but not handled: "+n)}}}return(p=f)&&!p.relurl&&(c.fragments.pop(),s-=p.duration),c.totalduration=s,c.averagetargetduration=s/c.fragments.length,c.endSN=a-1,c.startCC=c.fragments[0]?c.fragments[0].cc:0,c.endCC=d,c},t.prototype.loadsuccess=function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,n=e.data,o=e.url,c=r.type,l=r.id,d=r.level,f=this.hls;if(this.loaders[c]=void 0,void 0!==o&&0!==o.indexOf("data:")||(o=r.url),t.tload=performance.now(),0===n.indexOf("#EXTM3U"))if(n.indexOf("#EXTINF:")>0){var h="audioTrack"!==c&&"subtitleTrack"!==c,p=isNaN(d)?isNaN(l)?0:l:d,m=this.parseLevelPlaylist(n,o,p,"audioTrack"===c?"audio":"subtitleTrack"===c?"subtitle":"main");m.tload=t.tload,"manifest"===c&&f.trigger(a.a.MANIFEST_LOADED,{levels:[{url:o,details:m}],audioTracks:[],url:o,stats:t,networkDetails:i}),t.tparsed=performance.now(),m.targetduration?h?f.trigger(a.a.LEVEL_LOADED,{details:m,level:d||0,id:l||0,stats:t,networkDetails:i}):"audioTrack"===c?f.trigger(a.a.AUDIO_TRACK_LOADED,{details:m,id:l,stats:t,networkDetails:i}):"subtitleTrack"===c&&f.trigger(a.a.SUBTITLE_TRACK_LOADED,{details:m,id:l,stats:t,networkDetails:i}):f.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.MANIFEST_PARSING_ERROR,fatal:!0,url:o,reason:"invalid targetduration",networkDetails:i})}else{var v=this.parseMasterPlaylist(n,o);if(v.length){var g=v.map(function(e){return{id:e.attrs.AUDIO,codec:e.audioCodec}}),y=this.parseMasterPlaylistMedia(n,o,"AUDIO",g),_=this.parseMasterPlaylistMedia(n,o,"SUBTITLES");if(y.length){var b=!1;y.forEach(function(e){e.url||(b=!0)}),!1===b&&v[0].audioCodec&&!v[0].attrs.AUDIO&&(u.b.log("audio codec signaled in quality level, but no embedded audio track signaled, create one"),y.unshift({type:"main",name:"main"}))}f.trigger(a.a.MANIFEST_LOADED,{levels:v,audioTracks:y,subtitles:_,url:o,stats:t,networkDetails:i})}else f.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.MANIFEST_PARSING_ERROR,fatal:!0,url:o,reason:"no level found in manifest",networkDetails:i})}else f.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.MANIFEST_PARSING_ERROR,fatal:!0,url:o,reason:"no EXTM3U delimiter",networkDetails:i})},t.prototype.loaderror=function(e,t){var r,i,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,o=t.loader;switch(t.type){case"manifest":r=s.a.MANIFEST_LOAD_ERROR,i=!0;break;case"level":r=s.a.LEVEL_LOAD_ERROR,i=!1;break;case"audioTrack":r=s.a.AUDIO_TRACK_LOAD_ERROR,i=!1}o&&(o.abort(),this.loaders[t.type]=void 0),this.hls.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:r,fatal:i,url:o.url,loader:o,response:e,context:t,networkDetails:n})},t.prototype.loadtimeout=function(e,t){var r,i,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,o=t.loader;switch(t.type){case"manifest":r=s.a.MANIFEST_LOAD_TIMEOUT,i=!0;break;case"level":r=s.a.LEVEL_LOAD_TIMEOUT,i=!1;break;case"audioTrack":r=s.a.AUDIO_TRACK_LOAD_TIMEOUT,i=!1}o&&(o.abort(),this.loaders[t.type]=void 0),this.hls.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:r,fatal:i,url:o.url,loader:o,context:t,networkDetails:n})},t}(l);var A=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r,a.a.FRAG_LOADING));return i.loaders={},i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.destroy=function(){var e=this.loaders;for(var t in e){var r=e[t];r&&r.destroy()}this.loaders={},l.prototype.destroy.call(this)},t.prototype.onFragLoading=function(e){var t=e.frag,r=t.type,i=this.loaders[r],n=this.hls.config;t.loaded=0,i&&(u.b.warn("abort previous fragment loader for type:"+r),i.abort()),i=this.loaders[r]=t.loader=void 0!==n.fLoader?new n.fLoader(n):new n.loader(n);var o,a,s=void 0;s={url:t.url,frag:t,responseType:"arraybuffer",progressData:!1};var c=t.byteRangeStartOffset,l=t.byteRangeEndOffset;isNaN(c)||isNaN(l)||(s.rangeStart=c,s.rangeEnd=l),o={timeout:n.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:n.fragLoadingMaxRetryTimeout},a={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this),onProgress:this.loadprogress.bind(this)},i.load(s,o,a)},t.prototype.loadsuccess=function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,n=e.data,o=r.frag;o.loader=void 0,this.loaders[o.type]=void 0,this.hls.trigger(a.a.FRAG_LOADED,{payload:n,frag:o,stats:t,networkDetails:i})},t.prototype.loaderror=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=t.loader;i&&i.abort(),this.loaders[t.type]=void 0,this.hls.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t.frag,response:e,networkDetails:r})},t.prototype.loadtimeout=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=t.loader;i&&i.abort(),this.loaders[t.type]=void 0,this.hls.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t.frag,networkDetails:r})},t.prototype.loadprogress=function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,n=t.frag;n.loaded=e.loaded,this.hls.trigger(a.a.FRAG_LOAD_PROGRESS,{frag:n,stats:e,networkDetails:i})},t}(l);var $=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r,a.a.KEY_LOADING));return i.loaders={},i.decryptkey=null,i.decrypturl=null,i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.destroy=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy()}this.loaders={},l.prototype.destroy.call(this)},t.prototype.onKeyLoading=function(e){var t=e.frag,r=t.type,i=this.loaders[r],n=t.decryptdata,o=n.uri;if(o!==this.decrypturl||null===this.decryptkey){var s=this.hls.config;i&&(u.b.warn("abort previous key loader for type:"+r),i.abort()),t.loader=this.loaders[r]=new s.loader(s),this.decrypturl=o,this.decryptkey=null;var c,l,d;c={url:o,frag:t,responseType:"arraybuffer"},l={timeout:s.fragLoadingTimeOut,maxRetry:s.fragLoadingMaxRetry,retryDelay:s.fragLoadingRetryDelay,maxRetryDelay:s.fragLoadingMaxRetryTimeout},d={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)},t.loader.load(c,l,d)}else this.decryptkey&&(n.key=this.decryptkey,this.hls.trigger(a.a.KEY_LOADED,{frag:t}))},t.prototype.loadsuccess=function(e,t,r){var i=r.frag;this.decryptkey=i.decryptdata.key=new Uint8Array(e.data),i.loader=void 0,this.loaders[i.type]=void 0,this.hls.trigger(a.a.KEY_LOADED,{frag:i})},t.prototype.loaderror=function(e,t){var r=t.frag,i=r.loader;i&&i.abort(),this.loaders[t.type]=void 0,this.hls.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.KEY_LOAD_ERROR,fatal:!1,frag:r,response:e})},t.prototype.loadtimeout=function(e,t){var r=t.frag,i=r.loader;i&&i.abort(),this.loaders[t.type]=void 0,this.hls.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})},t}(l),k={search:function(e,t){for(var r=0,i=e.length-1,n=null,o=null;r<=i;){var a=t(o=e[n=(r+i)/2|0]);if(a>0)r=n+1;else{if(!(a<0))return o;i=n-1}}return null}},D={isBuffered:function(e,t){try{if(e)for(var r=e.buffered,i=0;i<r.length;i++)if(t>=r.start(i)&&t<=r.end(i))return!0}catch(e){}return!1},bufferInfo:function(e,t,r){try{if(e){var i,n=e.buffered,o=[];for(i=0;i<n.length;i++)o.push({start:n.start(i),end:n.end(i)});return this.bufferedInfo(o,t,r)}}catch(e){}return{len:0,start:t,end:t,nextStart:void 0}},bufferedInfo:function(e,t,r){var i,n,o,a,s,u=[];for(e.sort(function(e,t){var r=e.start-t.start;return r||t.end-e.end}),s=0;s<e.length;s++){var c=u.length;if(c){var l=u[c-1].end;e[s].start-l<r?e[s].end>l&&(u[c-1].end=e[s].end):u.push(e[s])}else u.push(e[s])}for(s=0,i=0,n=o=t;s<u.length;s++){var d=u[s].start,f=u[s].end;if(t+r>=d&&t<f)n=d,i=(o=f)-t;else if(t+r<d){a=d;break}}return{len:i,start:n,end:o,nextStart:a}}},I=r(7),x=r(5),C=r.n(x),M=r(9),P=r.n(M);function L(){if("undefined"!=typeof window)return window.MediaSource||window.WebKitMediaSource}var R=L(),N=function(){function e(t,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.hls=t,this.id=r;var i=this.observer=new C.a,n=t.config;i.trigger=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];i.emit.apply(i,[e,e].concat(r))},i.off=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];i.removeListener.apply(i,[e].concat(r))};var o=function(e,r){(r=r||{}).frag=this.frag,r.id=this.id,t.trigger(e,r)}.bind(this);i.on(a.a.FRAG_DECRYPTED,o),i.on(a.a.FRAG_PARSING_INIT_SEGMENT,o),i.on(a.a.FRAG_PARSING_DATA,o),i.on(a.a.FRAG_PARSED,o),i.on(a.a.ERROR,o),i.on(a.a.FRAG_PARSING_METADATA,o),i.on(a.a.FRAG_PARSING_USERDATA,o),i.on(a.a.INIT_PTS_FOUND,o);var c={mp4:R.isTypeSupported("video/mp4"),mpeg:R.isTypeSupported("audio/mpeg"),mp3:R.isTypeSupported('audio/mp4; codecs="mp3"')},l=navigator.vendor;if(n.enableWorker&&"undefined"!=typeof Worker){u.b.log("demuxing in webworker");var d=void 0;try{d=this.w=P()(10),this.onwmsg=this.onWorkerMessage.bind(this),d.addEventListener("message",this.onwmsg),d.onerror=function(e){t.trigger(a.a.ERROR,{type:s.b.OTHER_ERROR,details:s.a.INTERNAL_EXCEPTION,fatal:!0,event:"demuxerWorker",err:{message:e.message+" ("+e.filename+":"+e.lineno+")"}})},d.postMessage({cmd:"init",typeSupported:c,vendor:l,id:r,config:JSON.stringify(n)})}catch(e){u.b.error("error while initializing DemuxerWorker, fallback on DemuxerInline"),d&&URL.revokeObjectURL(d.objectURL),this.demuxer=new I.a(i,c,n,l),this.w=void 0}}else this.demuxer=new I.a(i,c,n,l)}return e.prototype.destroy=function(){var e=this.w;if(e)e.removeEventListener("message",this.onwmsg),e.terminate(),this.w=null;else{var t=this.demuxer;t&&(t.destroy(),this.demuxer=null)}var r=this.observer;r&&(r.removeAllListeners(),this.observer=null)},e.prototype.push=function(e,t,r,i,n,o,a,s){var c=this.w,l=isNaN(n.startDTS)?n.start:n.startDTS,d=n.decryptdata,f=this.frag,h=!(f&&n.cc===f.cc),p=!(f&&n.level===f.level),m=f&&n.sn===f.sn+1,v=!p&&m;if(h&&u.b.log(this.id+":discontinuity detected"),p&&u.b.log(this.id+":switch detected"),this.frag=n,c)c.postMessage({cmd:"demux",data:e,decryptdata:d,initSegment:t,audioCodec:r,videoCodec:i,timeOffset:l,discontinuity:h,trackSwitch:p,contiguous:v,duration:o,accurateTimeOffset:a,defaultInitPTS:s},e instanceof ArrayBuffer?[e]:[]);else{var g=this.demuxer;g&&g.push(e,d,t,r,i,l,h,p,v,o,a,s)}},e.prototype.onWorkerMessage=function(e){var t=e.data,r=this.hls;switch(t.event){case"init":URL.revokeObjectURL(this.w.objectURL);break;case a.a.FRAG_PARSING_DATA:t.data.data1=new Uint8Array(t.data1),t.data2&&(t.data.data2=new Uint8Array(t.data2));default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,r.trigger(t.event,t.data)}},e}();function j(e,t,r){var i=e[t],n=e[r],o=n.startPTS;isNaN(o)?n.start=r>t?i.start+i.duration:Math.max(i.start-n.duration,0):r>t?(i.duration=o-i.start,i.duration<0&&u.b.warn("negative duration computed for frag "+i.sn+",level "+i.level+", there should be some duration drift between playlist and fragment!")):(n.duration=i.start-o,n.duration<0&&u.b.warn("negative duration computed for frag "+n.sn+",level "+n.level+", there should be some duration drift between playlist and fragment!"))}function F(e,t,r,i,n,o){var a=r;if(!isNaN(t.startPTS)){var s=Math.abs(t.startPTS-r);isNaN(t.deltaPTS)?t.deltaPTS=s:t.deltaPTS=Math.max(s,t.deltaPTS),a=Math.max(r,t.startPTS),r=Math.min(r,t.startPTS),i=Math.max(i,t.endPTS),n=Math.min(n,t.startDTS),o=Math.max(o,t.endDTS)}var u=r-t.start;t.start=t.startPTS=r,t.maxStartPTS=a,t.endPTS=i,t.startDTS=n,t.endDTS=o,t.duration=i-r;var c,l,d,f=t.sn;if(!e||f<e.startSN||f>e.endSN)return 0;for(c=f-e.startSN,(l=e.fragments)[c]=t,d=c;d>0;d--)j(l,d,d-1);for(d=c;d<l.length-1;d++)j(l,d,d+1);return e.PTSKnown=!0,u}function B(e,t){var r,i=Math.max(e.startSN,t.startSN)-t.startSN,n=Math.min(e.endSN,t.endSN)-t.startSN,o=t.startSN-e.startSN,a=e.fragments,s=t.fragments,c=0;if(n<i)t.PTSKnown=!1;else{for(var l=i;l<=n;l++){var d=a[o+l],f=s[l];f&&d&&(c=d.cc-f.cc,isNaN(d.startPTS)||(f.start=f.startPTS=d.startPTS,f.endPTS=d.endPTS,f.duration=d.duration,f.backtracked=d.backtracked,f.dropped=d.dropped,r=f))}if(c)for(u.b.log("discontinuity sliding from playlist, take drift into account"),l=0;l<s.length;l++)s[l].cc+=c;if(r)F(t,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS);else if(o>=0&&o<a.length){var h=a[o].start;for(l=0;l<s.length;l++)s[l].start+=h}t.PTSKnown=e.PTSKnown}}var U={toString:function(e){for(var t="",r=e.length,i=0;i<r;i++)t+="["+e.start(i).toFixed(3)+","+e.end(i).toFixed(3)+"]";return t}};function z(e,t){t.fragments.forEach(function(t){if(t){var r=t.start+e;t.start=t.startPTS=r,t.endPTS=r+t.duration}}),t.PTSKnown=!0}function G(e,t,r){if(function(e,t,r){var i=!1;return t&&t.details&&r&&(r.endCC>r.startCC||e&&e.cc<r.startCC)&&(i=!0),i}(e,t,r)){var i=function(e,t){var r=e.fragments,i=t.fragments;if(i.length&&r.length){var n=function(e,t){for(var r=null,i=0;i<e.length;i+=1){var n=e[i];if(n&&n.cc===t){r=n;break}}return r}(r,i[0].cc);if(n&&(!n||n.startPTS))return n;u.b.log("No frag in previous level to align on")}else u.b.log("No fragments to align")}(t.details,r);i&&(u.b.log("Adjusting PTS using last level due to CC increase within current level"),z(i.start,r))}if(!1===r.PTSKnown&&t&&t.details){var n=t.details.programDateTime,o=(r.programDateTime-n)/1e3+t.details.fragments[0].start;isNaN(o)||(u.b.log("adjusting PTS using programDateTime delta, sliding:"+o.toFixed(3)),z(o,r))}}var W=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}();var H={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_LEVEL:"WAITING_LEVEL",PARSING:"PARSING",PARSED:"PARSED",BUFFER_FLUSHING:"BUFFER_FLUSHING",ENDED:"ENDED",ERROR:"ERROR"},V=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r,a.a.MEDIA_ATTACHED,a.a.MEDIA_DETACHING,a.a.MANIFEST_LOADING,a.a.MANIFEST_PARSED,a.a.LEVEL_LOADED,a.a.KEY_LOADED,a.a.FRAG_LOADED,a.a.FRAG_LOAD_EMERGENCY_ABORTED,a.a.FRAG_PARSING_INIT_SEGMENT,a.a.FRAG_PARSING_DATA,a.a.FRAG_PARSED,a.a.ERROR,a.a.AUDIO_TRACK_SWITCHING,a.a.AUDIO_TRACK_SWITCHED,a.a.BUFFER_CREATED,a.a.BUFFER_APPENDED,a.a.BUFFER_FLUSHED));return i.config=r.config,i.audioCodecSwap=!1,i.ticks=0,i._state=H.STOPPED,i.ontick=i.tick.bind(i),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.destroy=function(){this.stopLoad(),this.timer&&(clearInterval(this.timer),this.timer=null),l.prototype.destroy.call(this),this.state=H.STOPPED},t.prototype.startLoad=function(e){if(this.levels){var t=this.lastCurrentTime,r=this.hls;if(this.stopLoad(),this.timer||(this.timer=setInterval(this.ontick,100)),this.level=-1,this.fragLoadError=0,!this.startFragRequested){var i=r.startLevel;-1===i&&(i=0,this.bitrateTest=!0),this.level=r.nextLoadLevel=i,this.loadedmetadata=!1}t>0&&-1===e&&(u.b.log("override startPosition with lastCurrentTime @"+t.toFixed(3)),e=t),this.state=H.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this.forceStartLoad=!0,this.state=H.STOPPED},t.prototype.stopLoad=function(){var e=this.fragCurrent;e&&(e.loader&&e.loader.abort(),this.fragCurrent=null),this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.state=H.STOPPED,this.forceStartLoad=!1},t.prototype.tick=function(){this.ticks++,1===this.ticks&&(this.doTick(),this.ticks>1&&setTimeout(this.tick,1),this.ticks=0)},t.prototype.doTick=function(){switch(this.state){case H.ERROR:break;case H.BUFFER_FLUSHING:this.fragLoadError=0;break;case H.IDLE:this._doTickIdle();break;case H.WAITING_LEVEL:var e=this.levels[this.level];e&&e.details&&(this.state=H.IDLE);break;case H.FRAG_LOADING_WAITING_RETRY:var t=performance.now(),r=this.retryDate;(!r||t>=r||this.media&&this.media.seeking)&&(u.b.log("mediaController: retryDate reached, switch back to IDLE state"),this.state=H.IDLE);break;case H.ERROR:case H.STOPPED:case H.FRAG_LOADING:case H.PARSING:case H.PARSED:case H.ENDED:}this._checkBuffer(),this._checkFragmentChanged()},t.prototype._doTickIdle=function(){var e=this.hls,t=e.config,r=this.media;if(void 0!==this.levelLastLoaded&&(r||!this.startFragRequested&&t.startFragPrefetch)){var i=void 0;i=this.loadedmetadata?r.currentTime:this.nextLoadPosition;var n=e.nextLoadLevel,o=this.levels[n];if(o){var s=o.bitrate,c=void 0;c=s?Math.max(8*t.maxBufferSize/s,t.maxBufferLength):t.maxBufferLength,c=Math.min(c,t.maxMaxBufferLength);var l=D.bufferInfo(this.mediaBuffer?this.mediaBuffer:r,i,t.maxBufferHole),d=l.len;if(!(d>=c)){u.b.trace("buffer length of "+d.toFixed(3)+" is below max of "+c.toFixed(3)+". checking for more payload ..."),this.level=e.nextLoadLevel=n;var f=o.details;if(void 0===f||!0===f.live&&this.levelLastLoaded!==n)this.state=H.WAITING_LEVEL;else{var h=this.fragPrevious;if(!f.live&&h&&!h.backtracked&&h.sn===f.endSN&&!l.nextStart)if(Math.min(r.duration,h.start+h.duration)-Math.max(l.end,h.start)<=Math.max(.2,h.duration)){var p={};return this.altAudio&&(p.type="video"),this.hls.trigger(a.a.BUFFER_EOS,p),void(this.state=H.ENDED)}this._fetchPayloadOrEos(i,l,f)}}}}},t.prototype._fetchPayloadOrEos=function(e,t,r){var i=this.fragPrevious,n=this.level,o=r.fragments,a=o.length;if(0!==a){var s=o[0].start,c=o[a-1].start+o[a-1].duration,l=t.end,d=void 0;if(r.initSegment&&!r.initSegment.data)d=r.initSegment;else if(r.live){var f=this.config.initialLiveManifestSize;if(a<f)return void u.b.warn("Can not start playback of a level, reason: not enough fragments "+a+" < "+f);if(null===(d=this._ensureFragmentAtLivePoint(r,l,s,c,i,o,a)))return}else l<s&&(d=o[0]);d||(d=this._findFragment(s,i,a,o,l,c,r)),d&&this._loadFragmentOrKey(d,n,r,e,l)}},t.prototype._ensureFragmentAtLivePoint=function(e,t,r,i,n,o,a){var s=this.hls.config,c=this.media,l=void 0,d=void 0!==s.liveMaxLatencyDuration?s.liveMaxLatencyDuration:s.liveMaxLatencyDurationCount*e.targetduration;if(t<Math.max(r-s.maxFragLookUpTolerance,i-d)){var f=this.liveSyncPosition=this.computeLivePosition(r,e);u.b.log("buffer end: "+t.toFixed(3)+" is located too far from the end of live sliding playlist, reset currentTime to : "+f.toFixed(3)),t=f,c&&c.readyState&&c.duration>f&&(c.currentTime=f),this.nextLoadPosition=f}if(e.PTSKnown&&t>i&&c&&c.readyState)return null;if(this.startFragRequested&&!e.PTSKnown){if(n){var h=n.sn+1;if(h>=e.startSN&&h<=e.endSN){var p=o[h-e.startSN];n.cc===p.cc&&(l=p,u.b.log("live playlist, switching playlist, load frag with next SN: "+l.sn))}l||(l=k.search(o,function(e){return n.cc-e.cc}))&&u.b.log("live playlist, switching playlist, load frag with same CC: "+l.sn)}l||(l=o[Math.min(a-1,Math.round(a/2))],u.b.log("live playlist, switching playlist, unknown, load middle frag : "+l.sn))}return l},t.prototype._findFragment=function(e,t,r,i,n,o,a){var s=this.hls.config,c=void 0,l=void 0,d=s.maxFragLookUpTolerance,f=t?i[t.sn-i[0].sn+1]:void 0,h=function(e){var t=Math.min(d,e.duration+(e.deltaPTS?e.deltaPTS:0));return e.start+e.duration-t<=n?1:e.start-t>n&&e.start?-1:0};if(n<o?(n>o-d&&(d=0),l=f&&!h(f)?f:k.search(i,h)):l=i[r-1],l){var p=(c=l).sn-a.startSN,m=t&&c.level===t.level,v=i[p-1],g=i[p+1];if(t&&c.sn===t.sn)if(m&&!c.backtracked)if(c.sn<a.endSN){var y=t.deltaPTS;y&&y>s.maxBufferHole&&t.dropped&&p?(c=v,u.b.warn("SN just loaded, with large PTS gap between audio and video, maybe frag is not starting with a keyframe ? load previous one to try to overcome this"),t.loadCounter--):(c=g,u.b.log("SN just loaded, load next one: "+c.sn))}else c=null;else c.backtracked&&(g&&g.backtracked?(u.b.warn("Already backtracked from fragment "+g.sn+", will not backtrack to fragment "+c.sn+". Loading fragment "+g.sn),c=g):(u.b.warn("Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe"),c.dropped=0,v?(v.loadCounter&&v.loadCounter--,(c=v).backtracked=!0):p&&(c=null)))}return c},t.prototype._loadFragmentOrKey=function(e,t,r,i,n){var o=this.hls,c=o.config;if(!e.decryptdata||null==e.decryptdata.uri||null!=e.decryptdata.key){if(u.b.log("Loading "+e.sn+" of ["+r.startSN+" ,"+r.endSN+"],level "+t+", currentTime:"+i.toFixed(3)+",bufferEnd:"+n.toFixed(3)),void 0!==this.fragLoadIdx?this.fragLoadIdx++:this.fragLoadIdx=0,e.loadCounter){e.loadCounter++;var l=c.fragLoadingLoopThreshold;if(e.loadCounter>l&&Math.abs(this.fragLoadIdx-e.loadIdx)<l)return void o.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.FRAG_LOOP_LOADING_ERROR,fatal:!1,frag:e})}else e.loadCounter=1;return e.loadIdx=this.fragLoadIdx,e.autoLevel=o.autoLevelEnabled,e.bitrateTest=this.bitrateTest,this.fragCurrent=e,this.startFragRequested=!0,isNaN(e.sn)||e.bitrateTest||(this.nextLoadPosition=e.start+e.duration),o.trigger(a.a.FRAG_LOADING,{frag:e}),this.demuxer||(this.demuxer=new N(o,"main")),void(this.state=H.FRAG_LOADING)}u.b.log("Loading key for "+e.sn+" of ["+r.startSN+" ,"+r.endSN+"],level "+t),this.state=H.KEY_LOADING,o.trigger(a.a.KEY_LOADING,{frag:e})},t.prototype.getBufferedFrag=function(e){return k.search(this._bufferedFrags,function(t){return e<t.startPTS?-1:e>t.endPTS?1:0})},t.prototype.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.endPTS+.5):null},t.prototype._checkFragmentChanged=function(){var e,t,r=this.media;if(r&&r.readyState&&!1===r.seeking&&((t=r.currentTime)>r.playbackRate*this.lastCurrentTime&&(this.lastCurrentTime=t),D.isBuffered(r,t)?e=this.getBufferedFrag(t):D.isBuffered(r,t+.1)&&(e=this.getBufferedFrag(t+.1)),e)){var i=e;if(i!==this.fragPlaying){this.hls.trigger(a.a.FRAG_CHANGED,{frag:i});var n=i.level;this.fragPlaying&&this.fragPlaying.level===n||this.hls.trigger(a.a.LEVEL_SWITCHED,{level:n}),this.fragPlaying=i}}},t.prototype.immediateLevelSwitch=function(){if(u.b.log("immediateLevelSwitch"),!this.immediateSwitch){this.immediateSwitch=!0;var e=this.media,t=void 0;e?(t=e.paused,e.pause()):t=!0,this.previouslyPaused=t}var r=this.fragCurrent;r&&r.loader&&r.loader.abort(),this.fragCurrent=null,void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},t.prototype.immediateLevelSwitchEnd=function(){var e=this.media;e&&e.buffered.length&&(this.immediateSwitch=!1,D.isBuffered(e,e.currentTime)&&(e.currentTime-=1e-4),this.previouslyPaused||e.play())},t.prototype.nextLevelSwitch=function(){var e=this.media;if(e&&e.readyState){var t,r=void 0,i=void 0;if(void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold),(t=this.getBufferedFrag(e.currentTime))&&t.startPTS>1&&this.flushMainBuffer(0,t.startPTS-1),e.paused)r=0;else{var n=this.hls.nextLoadLevel,o=this.levels[n],a=this.fragLastKbps;r=a&&this.fragCurrent?this.fragCurrent.duration*o.bitrate/(1e3*a)+1:0}if((i=this.getBufferedFrag(e.currentTime+r))&&(i=this.followingBufferedFrag(i))){var s=this.fragCurrent;s&&s.loader&&s.loader.abort(),this.fragCurrent=null,this.flushMainBuffer(i.maxStartPTS,Number.POSITIVE_INFINITY)}}},t.prototype.flushMainBuffer=function(e,t){this.state=H.BUFFER_FLUSHING;var r={startOffset:e,endOffset:t};this.altAudio&&(r.type="video"),this.hls.trigger(a.a.BUFFER_FLUSHING,r)},t.prototype.onMediaAttached=function(e){var t=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),this.onvended=this.onMediaEnded.bind(this),t.addEventListener("seeking",this.onvseeking),t.addEventListener("seeked",this.onvseeked),t.addEventListener("ended",this.onvended);var r=this.config;this.levels&&r.autoStartLoad&&this.hls.startLoad(r.startPosition)},t.prototype.onMediaDetaching=function(){var e=this.media;e&&e.ended&&(u.b.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0);var t=this.levels;t&&t.forEach(function(e){e.details&&e.details.fragments.forEach(function(e){e.loadCounter=void 0,e.backtracked=void 0})}),e&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("seeked",this.onvseeked),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvseeked=this.onvended=null),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.stopLoad()},t.prototype.onMediaSeeking=function(){var e=this.media,t=e?e.currentTime:void 0,r=this.config;isNaN(t)||u.b.log("media seeking to "+t.toFixed(3));var i=this.mediaBuffer?this.mediaBuffer:e,n=D.bufferInfo(i,t,this.config.maxBufferHole);if(this.state===H.FRAG_LOADING){var o=this.fragCurrent;if(0===n.len&&o){var a=r.maxFragLookUpTolerance,s=o.start-a,c=o.start+o.duration+a;t<s||t>c?(o.loader&&(u.b.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),o.loader.abort()),this.fragCurrent=null,this.fragPrevious=null,this.state=H.IDLE):u.b.log("seeking outside of buffer but within currently loaded fragment range")}}else this.state===H.ENDED&&(0===n.len&&(this.fragPrevious=0),this.state=H.IDLE);e&&(this.lastCurrentTime=t),this.state!==H.FRAG_LOADING&&void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*r.fragLoadingLoopThreshold),this.loadedmetadata||(this.nextLoadPosition=this.startPosition=t),this.tick()},t.prototype.onMediaSeeked=function(){var e=this.media,t=e?e.currentTime:void 0;isNaN(t)||u.b.log("media seeked to "+t.toFixed(3)),this.tick()},t.prototype.onMediaEnded=function(){u.b.log("media ended"),this.startPosition=this.lastCurrentTime=0},t.prototype.onManifestLoading=function(){u.b.log("trigger BUFFER_RESET"),this.hls.trigger(a.a.BUFFER_RESET),this._bufferedFrags=[],this.stalled=!1,this.startPosition=this.lastCurrentTime=0},t.prototype.onManifestParsed=function(e){var t,r=!1,i=!1;e.levels.forEach(function(e){(t=e.audioCodec)&&(-1!==t.indexOf("mp4a.40.2")&&(r=!0),-1!==t.indexOf("mp4a.40.5")&&(i=!0))}),this.audioCodecSwitch=r&&i,this.audioCodecSwitch&&u.b.log("both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1;var n=this.config;(n.autoStartLoad||this.forceStartLoad)&&this.hls.startLoad(n.startPosition)},t.prototype.onLevelLoaded=function(e){var t=e.details,r=e.level,i=this.levels[this.levelLastLoaded],n=this.levels[r],o=t.totalduration,s=0;if(u.b.log("level "+r+" loaded ["+t.startSN+","+t.endSN+"],duration:"+o),t.live){var c=n.details;c&&t.fragments.length>0?(B(c,t),s=t.fragments[0].start,this.liveSyncPosition=this.computeLivePosition(s,c),t.PTSKnown&&!isNaN(s)?u.b.log("live playlist sliding:"+s.toFixed(3)):(u.b.log("live playlist - outdated PTS, unknown sliding"),G(this.fragPrevious,i,t))):(u.b.log("live playlist - first load, unknown sliding"),t.PTSKnown=!1,G(this.fragPrevious,i,t))}else t.PTSKnown=!1;if(n.details=t,this.levelLastLoaded=r,this.hls.trigger(a.a.LEVEL_UPDATED,{details:t,level:r}),!1===this.startFragRequested){if(-1===this.startPosition||-1===this.lastCurrentTime){var l=t.startTimeOffset;isNaN(l)?t.live?(this.startPosition=this.computeLivePosition(s,t),u.b.log("configure startPosition to "+this.startPosition)):this.startPosition=0:(l<0&&(u.b.log("negative start time offset "+l+", count from end of last fragment"),l=s+o+l),u.b.log("start time offset found in playlist, adjust startPosition to "+l),this.startPosition=l),this.lastCurrentTime=this.startPosition}this.nextLoadPosition=this.startPosition}this.state===H.WAITING_LEVEL&&(this.state=H.IDLE),this.tick()},t.prototype.onKeyLoaded=function(){this.state===H.KEY_LOADING&&(this.state=H.IDLE,this.tick())},t.prototype.onFragLoaded=function(e){var t=this.fragCurrent,r=e.frag;if(this.state===H.FRAG_LOADING&&t&&"main"===r.type&&r.level===t.level&&r.sn===t.sn){var i=e.stats,n=this.levels[t.level],o=n.details;if(u.b.log("Loaded "+t.sn+" of ["+o.startSN+" ,"+o.endSN+"],level "+t.level),this.bitrateTest=!1,this.stats=i,!0===r.bitrateTest&&this.hls.nextLoadLevel)this.state=H.IDLE,this.startFragRequested=!1,i.tparsed=i.tbuffered=performance.now(),this.hls.trigger(a.a.FRAG_BUFFERED,{stats:i,frag:t,id:"main"}),this.tick();else if("initSegment"===r.sn)this.state=H.IDLE,i.tparsed=i.tbuffered=performance.now(),o.initSegment.data=e.payload,this.hls.trigger(a.a.FRAG_BUFFERED,{stats:i,frag:t,id:"main"}),this.tick();else{this.state=H.PARSING;var s=o.totalduration,c=t.level,l=t.sn,d=this.config.defaultAudioCodec||n.audioCodec;this.audioCodecSwap&&(u.b.log("swapping playlist audio codec"),void 0===d&&(d=this.lastAudioCodec),d&&(d=-1!==d.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5")),this.pendingBuffering=!0,this.appended=!1,u.b.log("Parsing "+l+" of ["+o.startSN+" ,"+o.endSN+"],level "+c+", cc "+t.cc);var f=this.demuxer;f||(f=this.demuxer=new N(this.hls,"main"));var h=this.media,p=!(h&&h.seeking)&&(o.PTSKnown||!o.live),m=o.initSegment?o.initSegment.data:[];f.push(e.payload,m,d,n.videoCodec,t,s,p,void 0)}}this.fragLoadError=0},t.prototype.onFragParsingInitSegment=function(e){var t=this.fragCurrent,r=e.frag;if(t&&"main"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===H.PARSING){var i,n,o=e.tracks;if(o.audio&&this.altAudio&&delete o.audio,n=o.audio){var s=this.levels[this.level].audioCodec,c=navigator.userAgent.toLowerCase();s&&this.audioCodecSwap&&(u.b.log("swapping playlist audio codec"),s=-1!==s.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),this.audioCodecSwitch&&1!==n.metadata.channelCount&&-1===c.indexOf("firefox")&&(s="mp4a.40.5"),-1!==c.indexOf("android")&&"audio/mpeg"!==n.container&&(s="mp4a.40.2",u.b.log("Android: force audio codec to "+s)),n.levelCodec=s,n.id=e.id}for(i in(n=o.video)&&(n.levelCodec=this.levels[this.level].videoCodec,n.id=e.id),this.hls.trigger(a.a.BUFFER_CODECS,o),o){n=o[i],u.b.log("main track:"+i+",container:"+n.container+",codecs[level/parsed]=["+n.levelCodec+"/"+n.codec+"]");var l=n.initSegment;l&&(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(a.a.BUFFER_APPENDING,{type:i,data:l,parent:"main",content:"initSegment"}))}this.tick()}},t.prototype.onFragParsingData=function(e){var t=this,r=this.fragCurrent,i=e.frag;if(r&&"main"===e.id&&i.sn===r.sn&&i.level===r.level&&("audio"!==e.type||!this.altAudio)&&this.state===H.PARSING){var n=this.levels[this.level],o=r;if(isNaN(e.endPTS)&&(e.endPTS=e.startPTS+r.duration,e.endDTS=e.startDTS+r.duration),u.b.log("Parsed "+e.type+",PTS:["+e.startPTS.toFixed(3)+","+e.endPTS.toFixed(3)+"],DTS:["+e.startDTS.toFixed(3)+"/"+e.endDTS.toFixed(3)+"],nb:"+e.nb+",dropped:"+(e.dropped||0)),"video"===e.type)if(o.dropped=e.dropped,o.dropped)if(o.backtracked)u.b.warn("Already backtracked on this fragment, appending with the gap");else{var s=n.details;if(!s||o.sn!==s.startSN)return u.b.warn("missing video frame(s), backtracking fragment"),o.backtracked=!0,this.nextLoadPosition=e.startPTS,this.state=H.IDLE,this.fragPrevious=o,void this.tick();u.b.warn("missing video frame(s) on first frag, appending with gap")}else o.backtracked=!1;var c=F(n.details,o,e.startPTS,e.endPTS,e.startDTS,e.endDTS),l=this.hls;l.trigger(a.a.LEVEL_PTS_UPDATED,{details:n.details,level:this.level,drift:c,type:e.type,start:e.startPTS,end:e.endPTS}),[e.data1,e.data2].forEach(function(r){r&&r.length&&t.state===H.PARSING&&(t.appended=!0,t.pendingBuffering=!0,l.trigger(a.a.BUFFER_APPENDING,{type:e.type,data:r,parent:"main",content:"data"}))}),this.tick()}},t.prototype.onFragParsed=function(e){var t=this.fragCurrent,r=e.frag;t&&"main"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===H.PARSING&&(this.stats.tparsed=performance.now(),this.state=H.PARSED,this._checkAppendedParsed())},t.prototype.onAudioTrackSwitching=function(e){var t=!!e.url,r=e.id;if(!t){if(this.mediaBuffer!==this.media){u.b.log("switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var i=this.fragCurrent;i.loader&&(u.b.log("switching to main audio track, cancel main fragment load"),i.loader.abort()),this.fragCurrent=null,this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.state=H.IDLE}var n=this.hls;n.trigger(a.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),n.trigger(a.a.AUDIO_TRACK_SWITCHED,{id:r}),this.altAudio=!1}},t.prototype.onAudioTrackSwitched=function(e){var t=e.id,r=!!this.hls.audioTracks[t].url;if(r){var i=this.videoBuffer;i&&this.mediaBuffer!==i&&(u.b.log("switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=r,this.tick()},t.prototype.onBufferCreated=function(e){var t=e.tracks,r=void 0,i=void 0,n=!1;for(var o in t){var a=t[o];"main"===a.id?(i=o,r=a,"video"===o&&(this.videoBuffer=t[o].buffer)):n=!0}n&&r?(u.b.log("alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},t.prototype.onBufferAppended=function(e){if("main"===e.parent){var t=this.state;t!==H.PARSING&&t!==H.PARSED||(this.pendingBuffering=e.pending>0,this._checkAppendedParsed())}},t.prototype._checkAppendedParsed=function(){if(!(this.state!==H.PARSED||this.appended&&this.pendingBuffering)){var e=this.fragCurrent;if(e){var t=this.mediaBuffer?this.mediaBuffer:this.media;u.b.log("main buffered : "+U.toString(t.buffered));var r=this._bufferedFrags.filter(function(e){return D.isBuffered(t,(e.startPTS+e.endPTS)/2)});r.push(e),this._bufferedFrags=r.sort(function(e,t){return e.startPTS-t.startPTS}),this.fragPrevious=e;var i=this.stats;i.tbuffered=performance.now(),this.fragLastKbps=Math.round(8*i.total/(i.tbuffered-i.tfirst)),this.hls.trigger(a.a.FRAG_BUFFERED,{stats:i,frag:e,id:"main"}),this.state=H.IDLE}this.tick()}},t.prototype.onError=function(e){var t=e.frag||this.fragCurrent;if(!t||"main"===t.type){var r=!!this.media&&D.isBuffered(this.media,this.media.currentTime)&&D.isBuffered(this.media,this.media.currentTime+.5);switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:case s.a.KEY_LOAD_ERROR:case s.a.KEY_LOAD_TIMEOUT:if(!e.fatal)if(this.fragLoadError+1<=this.config.fragLoadingMaxRetry){var i=Math.min(Math.pow(2,this.fragLoadError)*this.config.fragLoadingRetryDelay,this.config.fragLoadingMaxRetryTimeout);t.loadCounter=0,u.b.warn("mediaController: frag loading failed, retry in "+i+" ms"),this.retryDate=performance.now()+i,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.fragLoadError++,this.state=H.FRAG_LOADING_WAITING_RETRY}else u.b.error("mediaController: "+e.details+" reaches max retry, redispatch as fatal ..."),e.fatal=!0,this.state=H.ERROR;break;case s.a.FRAG_LOOP_LOADING_ERROR:e.fatal||(r?(this._reduceMaxBufferLength(t.duration),this.state=H.IDLE):t.autoLevel&&0!==t.level||(e.fatal=!0,this.state=H.ERROR));break;case s.a.LEVEL_LOAD_ERROR:case s.a.LEVEL_LOAD_TIMEOUT:this.state!==H.ERROR&&(e.fatal?(this.state=H.ERROR,u.b.warn("streamController: "+e.details+",switch to "+this.state+" state ...")):e.levelRetry||this.state!==H.WAITING_LEVEL||(this.state=H.IDLE));break;case s.a.BUFFER_FULL_ERROR:"main"!==e.parent||this.state!==H.PARSING&&this.state!==H.PARSED||(r?(this._reduceMaxBufferLength(this.config.maxBufferLength),this.state=H.IDLE):(u.b.warn("buffer full error also media.currentTime is not buffered, flush everything"),this.fragCurrent=null,this.flushMainBuffer(0,Number.POSITIVE_INFINITY)))}}},t.prototype._reduceMaxBufferLength=function(e){var t=this.config;t.maxMaxBufferLength>=e&&(t.maxMaxBufferLength/=2,u.b.warn("main:reduce max buffer length to "+t.maxMaxBufferLength+"s"),void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*t.fragLoadingLoopThreshold))},t.prototype._checkBuffer=function(){var e=this.media,t=this.config;if(e&&e.readyState){var r=e.currentTime,i=this.mediaBuffer?this.mediaBuffer:e,n=i.buffered;if(!this.loadedmetadata&&n.length){this.loadedmetadata=!0;var o=e.seeking?r:this.startPosition,c=D.isBuffered(i,o),l=n.start(0),d=!c&&Math.abs(o-l)<t.maxSeekHole;(r!==o||d)&&(u.b.log("target start position:"+o),d&&(o=l,u.b.log("target start position not buffered, seek to buffered.start(0) "+o)),u.b.log("adjust currentTime from "+r+" to "+o),e.currentTime=o)}else if(this.immediateSwitch)this.immediateLevelSwitchEnd();else{var f=D.bufferInfo(e,r,0),h=!(e.paused||e.ended||0===e.buffered.length);if(r!==this.lastCurrentTime)this.stallReported&&(u.b.warn("playback not stuck anymore @"+r+", after "+Math.round(performance.now()-this.stalled)+"ms"),this.stallReported=!1),this.stalled=void 0,this.nudgeRetry=0;else if(h){var p=performance.now(),m=this.hls;if(this.stalled){var v=p-this.stalled,g=f.len,y=this.nudgeRetry||0;if(g<=.5&&v>1e3*t.lowBufferWatchdogPeriod){this.stallReported||(this.stallReported=!0,u.b.warn("playback stalling in low buffer @"+r),m.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_STALLED_ERROR,fatal:!1,buffer:g}));var _=f.nextStart,b=_-r;if(_&&b<t.maxSeekHole&&b>0){this.nudgeRetry=++y;var w=y*t.nudgeOffset;u.b.log("adjust currentTime from "+e.currentTime+" to next buffered @ "+_+" + nudge "+w),e.currentTime=_+w,this.stalled=void 0,m.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_SEEK_OVER_HOLE,fatal:!1,hole:_+w-r})}}else if(g>.5&&v>1e3*t.highBufferWatchdogPeriod)if(this.stallReported||(this.stallReported=!0,u.b.warn("playback stalling in high buffer @"+r),m.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_STALLED_ERROR,fatal:!1,buffer:g})),this.stalled=void 0,this.nudgeRetry=++y,y<t.nudgeMaxRetry){var E=e.currentTime,S=E+y*t.nudgeOffset;u.b.log("adjust currentTime from "+E+" to "+S),e.currentTime=S,m.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_NUDGE_ON_STALL,fatal:!1})}else u.b.error("still stuck in high buffer @"+r+" after "+t.nudgeMaxRetry+", raise fatal error"),m.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_STALLED_ERROR,fatal:!0})}else this.stalled=p,this.stallReported=!1}}}},t.prototype.onFragLoadEmergencyAborted=function(){this.state=H.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tick()},t.prototype.onBufferFlushed=function(){var e=this.mediaBuffer?this.mediaBuffer:this.media;this._bufferedFrags=this._bufferedFrags.filter(function(t){return D.isBuffered(e,(t.startPTS+t.endPTS)/2)}),void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold),this.state=H.IDLE,this.fragPrevious=null},t.prototype.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},t.prototype.computeLivePosition=function(e,t){var r=void 0!==this.config.liveSyncDuration?this.config.liveSyncDuration:this.config.liveSyncDurationCount*t.targetduration;return e+Math.max(0,t.totalduration-r)},W(t,[{key:"state",set:function(e){if(this.state!==e){var t=this.state;this._state=e,u.b.log("main stream:"+t+"->"+e),this.hls.trigger(a.a.STREAM_STATE_TRANSITION,{previousState:t,nextState:e})}},get:function(){return this._state}},{key:"currentLevel",get:function(){var e=this.media;if(e){var t=this.getBufferedFrag(e.currentTime);if(t)return t.level}return-1}},{key:"nextBufferedFrag",get:function(){var e=this.media;return e?this.followingBufferedFrag(this.getBufferedFrag(e.currentTime)):null}},{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"liveSyncPosition",get:function(){return this._liveSyncPosition},set:function(e){this._liveSyncPosition=e}}]),t}(l),Y=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}();var K=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r,a.a.MANIFEST_LOADED,a.a.LEVEL_LOADED,a.a.FRAG_LOADED,a.a.ERROR));return i.canload=!1,i.currentLevelIndex=null,i.manualLevelIndex=-1,i.timer=null,i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.destroy=function(){this.cleanTimer(),this.manualLevelIndex=-1},t.prototype.cleanTimer=function(){null!==this.timer&&(clearTimeout(this.timer),this.timer=null)},t.prototype.startLoad=function(){var e=this._levels;this.canload=!0,this.levelRetryCount=0,e&&e.forEach(function(e){e.loadError=0;var t=e.details;t&&t.live&&(e.details=void 0)}),null!==this.timer&&this.loadLevel()},t.prototype.stopLoad=function(){this.canload=!1},t.prototype.onManifestLoaded=function(e){var t=[],r=void 0,i={},n=null,o=!1,c=!1,l=/chrome|firefox/.test(navigator.userAgent.toLowerCase()),d=[];if(e.levels.forEach(function(e){e.loadError=0,e.fragmentError=!1,o=o||!!e.videoCodec,c=c||!!e.audioCodec||!(!e.attrs||!e.attrs.AUDIO),!0===l&&e.audioCodec&&-1!==e.audioCodec.indexOf("mp4a.40.34")&&(e.audioCodec=void 0),void 0===(n=i[e.bitrate])?(e.url=[e.url],e.urlId=0,i[e.bitrate]=e,t.push(e)):n.url.push(e.url)}),!0===o&&!0===c&&(t=t.filter(function(e){return!!e.videoCodec})),t=t.filter(function(e){var t=e.audioCodec,r=e.videoCodec;return(!t||m(t))&&(!r||m(r))}),e.audioTracks&&(d=e.audioTracks.filter(function(e){return!e.audioCodec||m(e.audioCodec,"audio")})),t.length>0){r=t[0].bitrate,t.sort(function(e,t){return e.bitrate-t.bitrate}),this._levels=t;for(var f=0;f<t.length;f++)if(t[f].bitrate===r){this._firstLevel=f,u.b.log("manifest loaded,"+t.length+" level(s) found, first bitrate:"+r);break}this.hls.trigger(a.a.MANIFEST_PARSED,{levels:t,audioTracks:d,firstLevel:this._firstLevel,stats:e.stats,audio:c,video:o,altAudio:d.length>0})}else this.hls.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:this.hls.url,reason:"no level with compatible codecs found in manifest"})},t.prototype.setLevelInternal=function(e){var t=this._levels,r=this.hls;if(e>=0&&e<t.length){if(this.cleanTimer(),this.currentLevelIndex!==e){u.b.log("switching to level "+e),this.currentLevelIndex=e;var i=t[e];i.level=e,r.trigger(a.a.LEVEL_SWITCH,i),r.trigger(a.a.LEVEL_SWITCHING,i)}var n=t[e],o=n.details;if(!o||!0===o.live){var c=n.urlId;r.trigger(a.a.LEVEL_LOADING,{url:n.url[c],level:e,id:c})}}else r.trigger(a.a.ERROR,{type:s.b.OTHER_ERROR,details:s.a.LEVEL_SWITCH_ERROR,level:e,fatal:!1,reason:"invalid level idx"})},t.prototype.onError=function(e){if(!0!==e.fatal){var t=!1,r=!1,i=void 0;switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:case s.a.FRAG_LOOP_LOADING_ERROR:case s.a.KEY_LOAD_ERROR:case s.a.KEY_LOAD_TIMEOUT:i=e.frag.level,r=!0;break;case s.a.LEVEL_LOAD_ERROR:case s.a.LEVEL_LOAD_TIMEOUT:i=e.context.level,t=!0;break;case s.a.REMUX_ALLOC_ERROR:i=e.level,t=!0}void 0!==i&&this.recoverLevel(e,i,t,r)}else e.type===s.b.NETWORK_ERROR&&this.cleanTimer()},t.prototype.recoverLevel=function(e,t,r,i){var n=this,o=this.hls.config,a=e.details,s=this._levels[t],c=void 0,l=void 0,d=void 0;if(s.loadError++,s.fragmentError=i,!0===r){if(!(this.levelRetryCount+1<=o.levelLoadingMaxRetry))return u.b.error("level controller, cannot recover from "+a+" error"),this.currentLevelIndex=null,this.cleanTimer(),void(e.fatal=!0);l=Math.min(Math.pow(2,this.levelRetryCount)*o.levelLoadingRetryDelay,o.levelLoadingMaxRetryTimeout),this.timer=setTimeout(function(){return n.loadLevel()},l),e.levelRetry=!0,this.levelRetryCount++,u.b.warn("level controller, "+a+", retry in "+l+" ms, current retry count is "+this.levelRetryCount)}!0!==r&&!0!==i||((c=s.url.length)>1&&s.loadError<c?(u.b.warn("level controller, "+a+" for level "+t+": switching to redundant stream id "+s.urlId),s.urlId=(s.urlId+1)%c,s.details=void 0):-1===this.manualLevelIndex?(d=0===t?this._levels.length-1:t-1,u.b.warn("level controller, "+a+": switch to "+d),this.hls.nextAutoLevel=this.currentLevelIndex=d):!0===i&&(u.b.warn("level controller, "+a+": reload a fragment"),this.currentLevelIndex=null))},t.prototype.onFragLoaded=function(e){var t=e.frag;if(void 0!==t&&"main"===t.type){var r=this._levels[t.level];void 0!==r&&(r.fragmentError=!1,r.loadError=0,this.levelRetryCount=0)}},t.prototype.onLevelLoaded=function(e){var t=this,r=e.level;if(r===this.currentLevelIndex){var i=this._levels[r];!1===i.fragmentError&&(i.loadError=0,this.levelRetryCount=0);var n=e.details;if(n.live){var o=1e3*(n.averagetargetduration?n.averagetargetduration:n.targetduration),a=i.details;a&&n.endSN===a.endSN&&(o/=2,u.b.log("same live playlist, reload twice faster")),o-=performance.now()-e.stats.trequest,o=Math.max(1e3,Math.round(o)),u.b.log("live playlist, reload in "+o+" ms"),this.timer=setTimeout(function(){return t.loadLevel()},o)}else this.cleanTimer()}},t.prototype.loadLevel=function(){var e=void 0,t=void 0;null!==this.currentLevelIndex&&!0===this.canload&&void 0!==(e=this._levels[this.currentLevelIndex])&&e.url.length>0&&(t=e.urlId,this.hls.trigger(a.a.LEVEL_LOADING,{url:e.url[t],level:this.currentLevelIndex,id:t}))},Y(t,[{key:"levels",get:function(){return this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;t&&(e=Math.min(e,t.length-1),this.currentLevelIndex===e&&void 0!==t[e].details||this.setLevelInternal(e))}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this._firstLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}}]),t}(l),Z=r(3);var Q=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r,a.a.MEDIA_ATTACHED,a.a.MEDIA_DETACHING,a.a.FRAG_PARSING_METADATA));return i.id3Track=void 0,i.media=void 0,i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.destroy=function(){l.prototype.destroy.call(this)},t.prototype.onMediaAttached=function(e){this.media=e.media,this.media},t.prototype.onMediaDetaching=function(){this.media=void 0},t.prototype.onFragParsingMetadata=function(e){var t=e.frag,r=e.samples;this.id3Track||(this.id3Track=this.media.addTextTrack("metadata","id3"),this.id3Track.mode="hidden");for(var i=window.WebKitDataCue||window.VTTCue||window.TextTrackCue,n=0;n<r.length;n++){var o=Z.a.getID3Frames(r[n].data);if(o){var a=r[n].pts,s=n<r.length-1?r[n+1].pts:t.endPTS;a===s&&(s+=1e-4);for(var u=0;u<o.length;u++){var c=o[u];if(!Z.a.isTimeStampFrame(c)){var l=new i(a,s,"");l.value=c,this.id3Track.addCue(l)}}}}},t}(l);var X=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=0,this.totalWeight_=0}return e.prototype.sample=function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e},e.prototype.getTotalWeight=function(){return this.totalWeight_},e.prototype.getEstimate=function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);return this.estimate_/e}return this.estimate_},e}();var q=function(){function e(t,r,i,n){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.hls=t,this.defaultEstimate_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new X(r),this.fast_=new X(i)}return e.prototype.sample=function(e,t){var r=8e3*t/(e=Math.max(e,this.minDelayMs_)),i=e/1e3;this.fast_.sample(i,r),this.slow_.sample(i,r)},e.prototype.canEstimate=function(){var e=this.fast_;return e&&e.getTotalWeight()>=this.minWeight_},e.prototype.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},e.prototype.destroy=function(){},e}(),J=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}();var ee=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r,a.a.FRAG_LOADING,a.a.FRAG_LOADED,a.a.FRAG_BUFFERED,a.a.ERROR));return i.lastLoadedFragLevel=0,i._nextAutoLevel=-1,i.hls=r,i.timer=null,i._bwEstimator=null,i.onCheck=i._abandonRulesCheck.bind(i),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.destroy=function(){this.clearTimer(),l.prototype.destroy.call(this)},t.prototype.onFragLoading=function(e){var t=e.frag;if("main"===t.type){if(this.timer||(this.timer=setInterval(this.onCheck,100)),!this._bwEstimator){var r=this.hls,i=e.frag.level,n=r.levels[i].details.live,o=r.config,a=void 0,s=void 0;n?(a=o.abrEwmaFastLive,s=o.abrEwmaSlowLive):(a=o.abrEwmaFastVoD,s=o.abrEwmaSlowVoD),this._bwEstimator=new q(r,s,a,o.abrEwmaDefaultEstimate)}this.fragCurrent=t}},t.prototype._abandonRulesCheck=function(){var e=this.hls,t=e.media,r=this.fragCurrent,i=r.loader,n=e.minAutoLevel;if(!i||i.stats&&i.stats.aborted)return u.b.warn("frag loader destroy or aborted, disarm abandonRules"),this.clearTimer(),void(this._nextAutoLevel=-1);var o=i.stats;if(t&&o&&(!t.paused&&0!==t.playbackRate||!t.readyState)&&r.autoLevel&&r.level){var s=performance.now()-o.trequest,c=Math.abs(t.playbackRate);if(s>500*r.duration/c){var l=e.levels,d=Math.max(1,o.bw?o.bw/8:1e3*o.loaded/s),f=l[r.level],h=f.realBitrate?Math.max(f.realBitrate,f.bitrate):f.bitrate,p=o.total?o.total:Math.max(o.loaded,Math.round(r.duration*h/8)),m=t.currentTime,v=(p-o.loaded)/d,g=(D.bufferInfo(t,m,e.config.maxBufferHole).end-m)/c;if(g<2*r.duration/c&&v>g){var y=void 0,_=void 0;for(_=r.level-1;_>n;_--){var b=l[_].realBitrate?Math.max(l[_].realBitrate,l[_].bitrate):l[_].bitrate;if((y=r.duration*b/(6.4*d))<g)break}y<v&&(u.b.warn("loading too slow, abort fragment loading and switch to level "+_+":fragLoadedDelay["+_+"]<fragLoadedDelay["+(r.level-1)+"];bufferStarvationDelay:"+y.toFixed(1)+"<"+v.toFixed(1)+":"+g.toFixed(1)),e.nextLoadLevel=_,this._bwEstimator.sample(s,o.loaded),i.abort(),this.clearTimer(),e.trigger(a.a.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,stats:o}))}}}},t.prototype.onFragLoaded=function(e){var t=e.frag;if("main"===t.type&&!isNaN(t.sn)){if(this.clearTimer(),this.lastLoadedFragLevel=t.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){var r=this.hls.levels[t.level],i=(r.loaded?r.loaded.bytes:0)+e.stats.loaded,n=(r.loaded?r.loaded.duration:0)+e.frag.duration;r.loaded={bytes:i,duration:n},r.realBitrate=Math.round(8*i/n)}if(e.frag.bitrateTest){var o=e.stats;o.tparsed=o.tbuffered=o.tload,this.onFragBuffered(e)}}},t.prototype.onFragBuffered=function(e){var t=e.stats,r=e.frag;if(!(!0===t.aborted||1!==r.loadCounter||"main"!==r.type||isNaN(r.sn)||r.bitrateTest&&t.tload!==t.tbuffered)){var i=t.tparsed-t.trequest;u.b.log("latency/loading/parsing/append/kbps:"+Math.round(t.tfirst-t.trequest)+"/"+Math.round(t.tload-t.tfirst)+"/"+Math.round(t.tparsed-t.tload)+"/"+Math.round(t.tbuffered-t.tparsed)+"/"+Math.round(8*t.loaded/(t.tbuffered-t.trequest))),this._bwEstimator.sample(i,t.loaded),t.bwEstimate=this._bwEstimator.getEstimate(),r.bitrateTest?this.bitrateTestDelay=i/1e3:this.bitrateTestDelay=0}},t.prototype.onError=function(e){switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:this.clearTimer()}},t.prototype.clearTimer=function(){clearInterval(this.timer),this.timer=null},t.prototype._findBestLevel=function(e,t,r,i,n,o,a,s,c){for(var l=n;l>=i;l--){var d=c[l].details,f=d?d.totalduration/d.fragments.length:t,h=!!d&&d.live,p=void 0;p=l<=e?a*r:s*r;var m=c[l].realBitrate?Math.max(c[l].realBitrate,c[l].bitrate):c[l].bitrate,v=m*f/p;if(u.b.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+l+"/"+Math.round(p)+"/"+m+"/"+f+"/"+o+"/"+v),p>m&&(!v||h&&!this.bitrateTestDelay||v<o))return l}return-1},J(t,[{key:"nextAutoLevel",get:function(){var e=this._nextAutoLevel,t=this._bwEstimator;if(!(-1===e||t&&t.canEstimate()))return e;var r=this._nextABRAutoLevel;return-1!==e&&(r=Math.min(e,r)),r},set:function(e){this._nextAutoLevel=e}},{key:"_nextABRAutoLevel",get:function(){var e=this.hls,t=e.maxAutoLevel,r=e.levels,i=e.config,n=e.minAutoLevel,o=e.media,a=this.lastLoadedFragLevel,s=this.fragCurrent?this.fragCurrent.duration:0,c=o?o.currentTime:0,l=o&&0!==o.playbackRate?Math.abs(o.playbackRate):1,d=this._bwEstimator?this._bwEstimator.getEstimate():i.abrEwmaDefaultEstimate,f=(D.bufferInfo(o,c,i.maxBufferHole).end-c)/l,h=this._findBestLevel(a,s,d,n,t,f,i.abrBandWidthFactor,i.abrBandWidthUpFactor,r);if(h>=0)return h;u.b.trace("rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering");var p=s?Math.min(s,i.maxStarvationDelay):i.maxStarvationDelay,m=i.abrBandWidthFactor,v=i.abrBandWidthUpFactor;if(0===f){var g=this.bitrateTestDelay;if(g)p=(s?Math.min(s,i.maxLoadingDelay):i.maxLoadingDelay)-g,u.b.trace("bitrate test took "+Math.round(1e3*g)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*p)+" ms"),m=v=1}return h=this._findBestLevel(a,s,d,n,t,f+p,m,v,r),Math.max(h,0)}}]),t}(l);var te=L(),re=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r,a.a.MEDIA_ATTACHING,a.a.MEDIA_DETACHING,a.a.MANIFEST_PARSED,a.a.BUFFER_RESET,a.a.BUFFER_APPENDING,a.a.BUFFER_CODECS,a.a.BUFFER_EOS,a.a.BUFFER_FLUSHING,a.a.LEVEL_PTS_UPDATED,a.a.LEVEL_UPDATED));return i._msDuration=null,i._levelDuration=null,i._live=null,i._objectUrl=null,i.onsbue=i.onSBUpdateEnd.bind(i),i.onsbe=i.onSBUpdateError.bind(i),i.pendingTracks={},i.tracks={},i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.destroy=function(){l.prototype.destroy.call(this)},t.prototype.onLevelPtsUpdated=function(e){var t=e.type,r=this.tracks.audio;if("audio"===t&&r&&"audio/mpeg"===r.container){var i=this.sourceBuffer.audio;if(Math.abs(i.timestampOffset-e.start)>.1){var n=i.updating;try{i.abort()}catch(e){n=!0,u.b.warn("can not abort audio buffer: "+e)}n?this.audioTimestampOffset=e.start:(u.b.warn("change mpeg audio timestamp offset from "+i.timestampOffset+" to "+e.start),i.timestampOffset=e.start)}}},t.prototype.onManifestParsed=function(e){var t=e.audio,r=e.video||e.levels.length&&e.audio,i=0;e.altAudio&&(t||r)&&(i=(t?1:0)+(r?1:0),u.b.log(i+" sourceBuffer(s) expected")),this.sourceBufferNb=i},t.prototype.onMediaAttaching=function(e){var t=this.media=e.media;if(t){var r=this.mediaSource=new te;this.onmso=this.onMediaSourceOpen.bind(this),this.onmse=this.onMediaSourceEnded.bind(this),this.onmsc=this.onMediaSourceClose.bind(this),r.addEventListener("sourceopen",this.onmso),r.addEventListener("sourceended",this.onmse),r.addEventListener("sourceclose",this.onmsc),t.src=URL.createObjectURL(r),this._objectUrl=t.src}},t.prototype.onMediaDetaching=function(){u.b.log("media source detaching");var e=this.mediaSource;if(e){if("open"===e.readyState)try{e.endOfStream()}catch(e){u.b.warn("onMediaDetaching:"+e.message+" while calling endOfStream")}e.removeEventListener("sourceopen",this.onmso),e.removeEventListener("sourceended",this.onmse),e.removeEventListener("sourceclose",this.onmsc),this.media&&(URL.revokeObjectURL(this._objectUrl),this.media.src===this._objectUrl?(this.media.removeAttribute("src"),this.media.load()):u.b.warn("media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.pendingTracks={},this.tracks={},this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0}this.onmso=this.onmse=this.onmsc=null,this.hls.trigger(a.a.MEDIA_DETACHED)},t.prototype.onMediaSourceOpen=function(){u.b.log("media source opened"),this.hls.trigger(a.a.MEDIA_ATTACHED,{media:this.media});var e=this.mediaSource;e&&e.removeEventListener("sourceopen",this.onmso),this.checkPendingTracks()},t.prototype.checkPendingTracks=function(){var e=this.pendingTracks,t=Object.keys(e).length;t&&(this.sourceBufferNb<=t||0===this.sourceBufferNb)&&(this.createSourceBuffers(e),this.pendingTracks={},this.doAppending())},t.prototype.onMediaSourceClose=function(){u.b.log("media source closed")},t.prototype.onMediaSourceEnded=function(){u.b.log("media source ended")},t.prototype.onSBUpdateEnd=function(){if(this.audioTimestampOffset){var e=this.sourceBuffer.audio;u.b.warn("change mpeg audio timestamp offset from "+e.timestampOffset+" to "+this.audioTimestampOffset),e.timestampOffset=this.audioTimestampOffset,delete this.audioTimestampOffset}this._needsFlush&&this.doFlush(),this._needsEos&&this.checkEos(),this.appending=!1;var t=this.parent,r=this.segments.reduce(function(e,r){return r.parent===t?e+1:e},0);this.hls.trigger(a.a.BUFFER_APPENDED,{parent:t,pending:r}),this._needsFlush||this.doAppending(),this.updateMediaElementDuration()},t.prototype.onSBUpdateError=function(e){u.b.error("sourceBuffer error:",e),this.hls.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_APPENDING_ERROR,fatal:!1})},t.prototype.onBufferReset=function(){var e=this.sourceBuffer;for(var t in e){var r=e[t];try{this.mediaSource.removeSourceBuffer(r),r.removeEventListener("updateend",this.onsbue),r.removeEventListener("error",this.onsbe)}catch(e){}}this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0},t.prototype.onBufferCodecs=function(e){if(0===Object.keys(this.sourceBuffer).length){for(var t in e)this.pendingTracks[t]=e[t];var r=this.mediaSource;r&&"open"===r.readyState&&this.checkPendingTracks()}},t.prototype.createSourceBuffers=function(e){var t=this.sourceBuffer,r=this.mediaSource;for(var i in e)if(!t[i]){var n=e[i],o=n.levelCodec||n.codec,c=n.container+";codecs="+o;u.b.log("creating sourceBuffer("+c+")");try{var l=t[i]=r.addSourceBuffer(c);l.addEventListener("updateend",this.onsbue),l.addEventListener("error",this.onsbe),this.tracks[i]={codec:o,container:n.container},n.buffer=l}catch(e){u.b.error("error while trying to add sourceBuffer:"+e.message),this.hls.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_ADD_CODEC_ERROR,fatal:!1,err:e,mimeType:c})}}this.hls.trigger(a.a.BUFFER_CREATED,{tracks:e})},t.prototype.onBufferAppending=function(e){this._needsFlush||(this.segments?this.segments.push(e):this.segments=[e],this.doAppending())},t.prototype.onBufferAppendFail=function(e){u.b.error("sourceBuffer error:",e.event),this.hls.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_APPENDING_ERROR,fatal:!1})},t.prototype.onBufferEos=function(e){var t=this.sourceBuffer,r=e.type;for(var i in t)r&&i!==r||t[i].ended||(t[i].ended=!0,u.b.log(i+" sourceBuffer now EOS"));this.checkEos()},t.prototype.checkEos=function(){var e=this.sourceBuffer,t=this.mediaSource;if(t&&"open"===t.readyState){for(var r in e){var i=e[r];if(!i.ended)return;if(i.updating)return void(this._needsEos=!0)}u.b.log("all media data available, signal endOfStream() to MediaSource and stop loading fragment");try{t.endOfStream()}catch(e){u.b.warn("exception while calling mediaSource.endOfStream()")}this._needsEos=!1}else this._needsEos=!1},t.prototype.onBufferFlushing=function(e){this.flushRange.push({start:e.startOffset,end:e.endOffset,type:e.type}),this.flushBufferCounter=0,this.doFlush()},t.prototype.onLevelUpdated=function(e){var t=e.details;t.fragments.length>0&&(this._levelDuration=t.totalduration+t.fragments[0].start,this._live=t.live,this.updateMediaElementDuration())},t.prototype.updateMediaElementDuration=function(){var e,t=this.hls.config;if(null!==this._levelDuration&&this.media&&this.mediaSource&&this.sourceBuffer&&0!==this.media.readyState&&"open"===this.mediaSource.readyState){for(var r in this.sourceBuffer)if(!0===this.sourceBuffer[r].updating)return;e=this.media.duration,null===this._msDuration&&(this._msDuration=this.mediaSource.duration),!0===this._live&&!0===t.liveDurationInfinity?(u.b.log("Media Source duration is set to Infinity"),this._msDuration=this.mediaSource.duration=1/0):(this._levelDuration>this._msDuration&&this._levelDuration>e||e===1/0||isNaN(e))&&(u.b.log("Updating Media Source duration to "+this._levelDuration.toFixed(3)),this._msDuration=this.mediaSource.duration=this._levelDuration)}},t.prototype.doFlush=function(){for(;this.flushRange.length;){var e=this.flushRange[0];if(!this.flushBuffer(e.start,e.end,e.type))return void(this._needsFlush=!0);this.flushRange.shift(),this.flushBufferCounter=0}if(0===this.flushRange.length){this._needsFlush=!1;var t=0,r=this.sourceBuffer;try{for(var i in r)t+=r[i].buffered.length}catch(e){u.b.error("error while accessing sourceBuffer.buffered")}this.appended=t,this.hls.trigger(a.a.BUFFER_FLUSHED)}},t.prototype.doAppending=function(){var e=this.hls,t=this.sourceBuffer,r=this.segments;if(Object.keys(t).length){if(this.media.error)return this.segments=[],void u.b.error("trying to append although a media error occured, flush segment and abort");if(this.appending)return;if(r&&r.length){var i=r.shift();try{var n=t[i.type];n?n.updating?r.unshift(i):(n.ended=!1,this.parent=i.parent,n.appendBuffer(i.data),this.appendError=0,this.appended++,this.appending=!0):this.onSBUpdateEnd()}catch(t){u.b.error("error while trying to append buffer:"+t.message),r.unshift(i);var o={type:s.b.MEDIA_ERROR,parent:i.parent};if(22===t.code)return this.segments=[],o.details=s.a.BUFFER_FULL_ERROR,o.fatal=!1,void e.trigger(a.a.ERROR,o);if(this.appendError?this.appendError++:this.appendError=1,o.details=s.a.BUFFER_APPEND_ERROR,this.appendError>e.config.appendErrorMaxRetry)return u.b.log("fail "+e.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),r=[],o.fatal=!0,void e.trigger(a.a.ERROR,o);o.fatal=!1,e.trigger(a.a.ERROR,o)}}}},t.prototype.flushBuffer=function(e,t,r){var i,n,o,a,s,c,l=this.sourceBuffer;if(Object.keys(l).length){if(u.b.log("flushBuffer,pos/start/end: "+this.media.currentTime.toFixed(3)+"/"+e+"/"+t),this.flushBufferCounter<this.appended){for(var d in l)if(!r||d===r){if((i=l[d]).ended=!1,i.updating)return u.b.warn("cannot flush, sb updating in progress"),!1;try{for(n=0;n<i.buffered.length;n++)if(o=i.buffered.start(n),a=i.buffered.end(n),-1!==navigator.userAgent.toLowerCase().indexOf("firefox")&&t===Number.POSITIVE_INFINITY?(s=e,c=t):(s=Math.max(o,e),c=Math.min(a,t)),Math.min(c,a)-s>.5)return this.flushBufferCounter++,u.b.log("flush "+d+" ["+s+","+c+"], of ["+o+","+a+"], pos:"+this.media.currentTime),i.remove(s,c),!1}catch(e){u.b.warn("exception while accessing sourcebuffer, it might have been removed from MediaSource")}}}else u.b.warn("abort flushing too many retries");u.b.log("buffer flushed")}return!0},t}(l),ie=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}();var ne=function(e){function t(r){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r,a.a.FPS_DROP_LEVEL_CAPPING,a.a.MEDIA_ATTACHING,a.a.MANIFEST_PARSED))}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.destroy=function(){this.hls.config.capLevelToPlayerSize&&(this.media=this.restrictedLevels=null,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(this.timer=clearInterval(this.timer)))},t.prototype.onFpsDropLevelCapping=function(e){t.isLevelAllowed(e.droppedLevel,this.restrictedLevels)&&this.restrictedLevels.push(e.droppedLevel)},t.prototype.onMediaAttaching=function(e){this.media=e.media instanceof HTMLVideoElement?e.media:null},t.prototype.onManifestParsed=function(e){var t=this.hls;this.restrictedLevels=[],t.config.capLevelToPlayerSize&&(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.levels=e.levels,t.firstLevel=this.getMaxLevel(e.firstLevel),clearInterval(this.timer),this.timer=setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},t.prototype.detectPlayerSize=function(){if(this.media){var e=this.levels?this.levels.length:0;if(e){var t=this.hls;t.autoLevelCapping=this.getMaxLevel(e-1),t.autoLevelCapping>this.autoLevelCapping&&t.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}},t.prototype.getMaxLevel=function(e){var r=this;if(!this.levels)return-1;var i=this.levels.filter(function(i,n){return t.isLevelAllowed(n,r.restrictedLevels)&&n<=e});return t.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)},t.isLevelAllowed=function(e){return-1===(arguments.length>1&&void 0!==arguments[1]?arguments[1]:[]).indexOf(e)},t.getMaxLevelByMediaSize=function(e,t,r){if(!e||e&&!e.length)return-1;for(var i,n,o=e.length-1,a=0;a<e.length;a+=1){var s=e[a];if((s.width>=t||s.height>=r)&&(i=s,!(n=e[a+1])||i.width!==n.width||i.height!==n.height)){o=a;break}}return o},ie(t,[{key:"mediaWidth",get:function(){var e=void 0,r=this.media;return r&&(e=r.width||r.clientWidth||r.offsetWidth,e*=t.contentScaleFactor),e}},{key:"mediaHeight",get:function(){var e=void 0,r=this.media;return r&&(e=r.height||r.clientHeight||r.offsetHeight,e*=t.contentScaleFactor),e}}],[{key:"contentScaleFactor",get:function(){var e=1;try{e=window.devicePixelRatio}catch(e){}return e}}]),t}(l);var oe=function(e){function t(r){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r,a.a.MEDIA_ATTACHING))}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.destroy=function(){this.timer&&clearInterval(this.timer),this.isVideoPlaybackQualityAvailable=!1},t.prototype.onMediaAttaching=function(e){var t=this.hls.config;t.capLevelOnFPSDrop&&("function"==typeof(this.video=e.media instanceof HTMLVideoElement?e.media:null).getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),clearInterval(this.timer),this.timer=setInterval(this.checkFPSInterval.bind(this),t.fpsDroppedMonitoringPeriod))},t.prototype.checkFPS=function(e,t,r){var i=performance.now();if(t){if(this.lastTime){var n=i-this.lastTime,o=r-this.lastDroppedFrames,s=t-this.lastDecodedFrames,c=1e3*o/n,l=this.hls;if(l.trigger(a.a.FPS_DROP,{currentDropped:o,currentDecoded:s,totalDroppedFrames:r}),c>0&&o>l.config.fpsDroppedMonitoringThreshold*s){var d=l.currentLevel;u.b.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=d)&&(d-=1,l.trigger(a.a.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:l.currentLevel}),l.autoLevelCapping=d,l.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}},t.prototype.checkFPSInterval=function(){var e=this.video;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)},t}(l);var ae=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),t&&t.xhrSetup&&(this.xhrSetup=t.xhrSetup)}return e.prototype.destroy=function(){this.abort(),this.loader=null},e.prototype.abort=function(){var e=this.loader;e&&4!==e.readyState&&(this.stats.aborted=!0,e.abort()),window.clearTimeout(this.requestTimeout),this.requestTimeout=null,window.clearTimeout(this.retryTimeout),this.retryTimeout=null},e.prototype.load=function(e,t,r){this.context=e,this.config=t,this.callbacks=r,this.stats={trequest:performance.now(),retry:0},this.retryDelay=t.retryDelay,this.loadInternal()},e.prototype.loadInternal=function(){var e,t=this.context;e=this.loader=new XMLHttpRequest;var r=this.stats;r.tfirst=0,r.loaded=0;var i=this.xhrSetup;try{if(i)try{i(e,t.url)}catch(r){e.open("GET",t.url,!0),i(e,t.url)}e.readyState||e.open("GET",t.url,!0)}catch(r){return void this.callbacks.onError({code:e.status,text:r.message},t,e)}t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,this.requestTimeout=window.setTimeout(this.loadtimeout.bind(this),this.config.timeout),e.send()},e.prototype.readystatechange=function(e){var t=e.currentTarget,r=t.readyState,i=this.stats,n=this.context,o=this.config;if(!i.aborted&&r>=2)if(window.clearTimeout(this.requestTimeout),0===i.tfirst&&(i.tfirst=Math.max(performance.now(),i.trequest)),4===r){var a=t.status;if(a>=200&&a<300){i.tload=Math.max(i.tfirst,performance.now());var s=void 0,c=void 0;c="arraybuffer"===n.responseType?(s=t.response).byteLength:(s=t.responseText).length,i.loaded=i.total=c;var l={url:t.responseURL,data:s};this.callbacks.onSuccess(l,i,n,t)}else i.retry>=o.maxRetry||a>=400&&a<499?(u.b.error(a+" while loading "+n.url),this.callbacks.onError({code:a,text:t.statusText},n,t)):(u.b.warn(a+" while loading "+n.url+", retrying in "+this.retryDelay+"..."),this.destroy(),this.retryTimeout=window.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,o.maxRetryDelay),i.retry++)}else this.requestTimeout=window.setTimeout(this.loadtimeout.bind(this),o.timeout)},e.prototype.loadtimeout=function(){u.b.warn("timeout while loading "+this.context.url),this.callbacks.onTimeout(this.stats,this.context,null)},e.prototype.loadprogress=function(e){var t=e.currentTarget,r=this.stats;r.loaded=e.loaded,e.lengthComputable&&(r.total=e.total);var i=this.callbacks.onProgress;i&&i(r,this.context,null,t)},e}(),se=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}();var ue=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r,a.a.MANIFEST_LOADING,a.a.MANIFEST_PARSED,a.a.AUDIO_TRACK_LOADED,a.a.ERROR));return i.ticks=0,i.ontick=i.tick.bind(i),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.destroy=function(){this.cleanTimer(),l.prototype.destroy.call(this)},t.prototype.cleanTimer=function(){this.timer&&(clearTimeout(this.timer),this.timer=null)},t.prototype.tick=function(){this.ticks++,1===this.ticks&&(this.doTick(),this.ticks>1&&setTimeout(this.tick,1),this.ticks=0)},t.prototype.doTick=function(){this.updateTrack(this.trackId)},t.prototype.onError=function(e){e.fatal&&e.type===s.b.NETWORK_ERROR&&this.cleanTimer()},t.prototype.onManifestLoading=function(){this.tracks=[],this.trackId=-1},t.prototype.onManifestParsed=function(e){var t=this,r=e.audioTracks||[],i=!1;this.tracks=r,this.hls.trigger(a.a.AUDIO_TRACKS_UPDATED,{audioTracks:r});var n=0;r.forEach(function(e){if(e.default&&!i)return t.audioTrack=n,void(i=!0);n++}),!1===i&&r.length&&(u.b.log("no default audio track defined, use first audio track as default"),this.audioTrack=0)},t.prototype.onAudioTrackLoaded=function(e){e.id<this.tracks.length&&(u.b.log("audioTrack "+e.id+" loaded"),this.tracks[e.id].details=e.details,e.details.live&&!this.timer&&(this.timer=setInterval(this.ontick,1e3*e.details.targetduration)),!e.details.live&&this.timer&&this.cleanTimer())},t.prototype.setAudioTrackInternal=function(e){if(e>=0&&e<this.tracks.length){this.cleanTimer(),this.trackId=e,u.b.log("switching to audioTrack "+e);var t=this.tracks[e],r=this.hls,i=t.type,n=t.url,o={id:e,type:i,url:n};r.trigger(a.a.AUDIO_TRACK_SWITCH,o),r.trigger(a.a.AUDIO_TRACK_SWITCHING,o);var s=t.details;!n||void 0!==s&&!0!==s.live||(u.b.log("(re)loading playlist for audioTrack "+e),r.trigger(a.a.AUDIO_TRACK_LOADING,{url:n,id:e}))}},t.prototype.updateTrack=function(e){if(e>=0&&e<this.tracks.length){this.cleanTimer(),this.trackId=e,u.b.log("updating audioTrack "+e);var t=this.tracks[e],r=t.url,i=t.details;!r||void 0!==i&&!0!==i.live||(u.b.log("(re)loading playlist for audioTrack "+e),this.hls.trigger(a.a.AUDIO_TRACK_LOADING,{url:r,id:e}))}},se(t,[{key:"audioTracks",get:function(){return this.tracks}},{key:"audioTrack",get:function(){return this.trackId},set:function(e){this.trackId===e&&void 0!==this.tracks[e].details||this.setAudioTrackInternal(e)}}]),t}(l),ce=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}();var le={STOPPED:"STOPPED",STARTING:"STARTING",IDLE:"IDLE",PAUSED:"PAUSED",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",BUFFER_FLUSHING:"BUFFER_FLUSHING",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS"},de=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r,a.a.MEDIA_ATTACHED,a.a.MEDIA_DETACHING,a.a.AUDIO_TRACKS_UPDATED,a.a.AUDIO_TRACK_SWITCHING,a.a.AUDIO_TRACK_LOADED,a.a.KEY_LOADED,a.a.FRAG_LOADED,a.a.FRAG_PARSING_INIT_SEGMENT,a.a.FRAG_PARSING_DATA,a.a.FRAG_PARSED,a.a.ERROR,a.a.BUFFER_RESET,a.a.BUFFER_CREATED,a.a.BUFFER_APPENDED,a.a.BUFFER_FLUSHED,a.a.INIT_PTS_FOUND));return i.config=r.config,i.audioCodecSwap=!1,i.ticks=0,i._state=le.STOPPED,i.ontick=i.tick.bind(i),i.initPTS=[],i.waitingFragment=null,i.videoTrackCC=null,i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.destroy=function(){this.stopLoad(),this.timer&&(clearInterval(this.timer),this.timer=null),l.prototype.destroy.call(this),this.state=le.STOPPED},t.prototype.onInitPtsFound=function(e){var t=e.id,r=e.frag.cc,i=e.initPTS;"main"===t&&(this.initPTS[r]=i,this.videoTrackCC=r,u.b.log("InitPTS for cc:"+r+" found from video track:"+i),this.state===le.WAITING_INIT_PTS&&this.tick())},t.prototype.startLoad=function(e){if(this.tracks){var t=this.lastCurrentTime;this.stopLoad(),this.timer||(this.timer=setInterval(this.ontick,100)),this.fragLoadError=0,t>0&&-1===e?(u.b.log("audio:override startPosition with lastCurrentTime @"+t.toFixed(3)),this.state=le.IDLE):(this.lastCurrentTime=this.startPosition?this.startPosition:e,this.state=le.STARTING),this.nextLoadPosition=this.startPosition=this.lastCurrentTime,this.tick()}else this.startPosition=e,this.state=le.STOPPED},t.prototype.stopLoad=function(){var e=this.fragCurrent;e&&(e.loader&&e.loader.abort(),this.fragCurrent=null),this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.state=le.STOPPED},t.prototype.tick=function(){this.ticks++,1===this.ticks&&(this.doTick(),this.ticks>1&&setTimeout(this.tick,1),this.ticks=0)},t.prototype.doTick=function(){var e,t,r,i=this.hls,n=i.config;switch(this.state){case le.ERROR:case le.PAUSED:case le.BUFFER_FLUSHING:break;case le.STARTING:this.state=le.WAITING_TRACK,this.loadedmetadata=!1;break;case le.IDLE:var o=this.tracks;if(!o)break;if(!this.media&&(this.startFragRequested||!n.startFragPrefetch))break;if(this.loadedmetadata)e=this.media.currentTime;else if(void 0===(e=this.nextLoadPosition))break;var c=this.mediaBuffer?this.mediaBuffer:this.media,l=this.videoBuffer?this.videoBuffer:this.media,d=D.bufferInfo(c,e,n.maxBufferHole),f=D.bufferInfo(l,e,n.maxBufferHole),h=d.len,p=d.end,m=this.fragPrevious,v=Math.max(n.maxBufferLength,f.len),g=this.audioSwitch,y=this.trackId;if((h<v||g)&&y<o.length){if(void 0===(r=o[y].details)){this.state=le.WAITING_TRACK;break}if(!g&&!r.live&&m&&m.sn===r.endSN&&!d.nextStart&&(!this.media.seeking||this.media.duration-p<m.duration/2)){this.hls.trigger(a.a.BUFFER_EOS,{type:"audio"}),this.state=le.ENDED;break}var _=r.fragments,b=_.length,w=_[0].start,E=_[b-1].start+_[b-1].duration,S=void 0;if(g)if(r.live&&!r.PTSKnown)u.b.log("switching audiotrack, live stream, unknown PTS,load first fragment"),p=0;else if(p=e,r.PTSKnown&&e<w){if(!(d.end>w||d.nextStart))return;u.b.log("alt audio track ahead of main track, seek to start of alt audio track"),this.media.currentTime=w+.05}if(r.initSegment&&!r.initSegment.data)S=r.initSegment;else if(p<=w){if(S=_[0],null!==this.videoTrackCC&&S.cc!==this.videoTrackCC&&(S=function(e,t){return k.search(e,function(e){return e.cc<t?1:e.cc>t?-1:0})}(_,this.videoTrackCC)),r.live&&S.loadIdx&&S.loadIdx===this.fragLoadIdx){var T=d.nextStart?d.nextStart:w;return u.b.log("no alt audio available @currentTime:"+this.media.currentTime+", seeking @"+(T+.05)),void(this.media.currentTime=T+.05)}}else{var O=void 0,A=n.maxFragLookUpTolerance,$=m?_[m.sn-_[0].sn+1]:void 0,I=function(e){var t=Math.min(A,e.duration);return e.start+e.duration-t<=p?1:e.start-t>p&&e.start?-1:0};p<E?(p>E-A&&(A=0),O=$&&!I($)?$:k.search(_,I)):O=_[b-1],O&&(S=O,w=O.start,m&&S.level===m.level&&S.sn===m.sn&&(S.sn<r.endSN?(S=_[S.sn+1-r.startSN],u.b.log("SN just loaded, load next one: "+S.sn)):S=null))}if(S)if(S.decryptdata&&null!=S.decryptdata.uri&&null==S.decryptdata.key)u.b.log("Loading key for "+S.sn+" of ["+r.startSN+" ,"+r.endSN+"],track "+y),this.state=le.KEY_LOADING,i.trigger(a.a.KEY_LOADING,{frag:S});else{if(u.b.log("Loading "+S.sn+", cc: "+S.cc+" of ["+r.startSN+" ,"+r.endSN+"],track "+y+", currentTime:"+e+",bufferEnd:"+p.toFixed(3)),void 0!==this.fragLoadIdx?this.fragLoadIdx++:this.fragLoadIdx=0,S.loadCounter){S.loadCounter++;var x=n.fragLoadingLoopThreshold;if(S.loadCounter>x&&Math.abs(this.fragLoadIdx-S.loadIdx)<x)return void i.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.FRAG_LOOP_LOADING_ERROR,fatal:!1,frag:S})}else S.loadCounter=1;S.loadIdx=this.fragLoadIdx,this.fragCurrent=S,this.startFragRequested=!0,isNaN(S.sn)||(this.nextLoadPosition=S.start+S.duration),i.trigger(a.a.FRAG_LOADING,{frag:S}),this.state=le.FRAG_LOADING}}break;case le.WAITING_TRACK:(t=this.tracks[this.trackId])&&t.details&&(this.state=le.IDLE);break;case le.FRAG_LOADING_WAITING_RETRY:var C=performance.now(),M=this.retryDate,P=(c=this.media)&&c.seeking;(!M||C>=M||P)&&(u.b.log("audioStreamController: retryDate reached, switch back to IDLE state"),this.state=le.IDLE);break;case le.WAITING_INIT_PTS:var L=this.videoTrackCC;if(void 0===this.initPTS[L])break;var R=this.waitingFragment;if(R){var N=R.frag.cc;L!==N?(t=this.tracks[this.trackId]).details&&t.details.live&&(u.b.warn("Waiting fragment CC ("+N+") does not match video track CC ("+L+")"),this.waitingFragment=null,this.state=le.IDLE):(this.state=le.FRAG_LOADING,this.onFragLoaded(this.waitingFragment),this.waitingFragment=null)}else this.state=le.IDLE;break;case le.STOPPED:case le.FRAG_LOADING:case le.PARSING:case le.PARSED:case le.ENDED:}},t.prototype.onMediaAttached=function(e){var t=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),t.addEventListener("seeking",this.onvseeking),t.addEventListener("ended",this.onvended);var r=this.config;this.tracks&&r.autoStartLoad&&this.startLoad(r.startPosition)},t.prototype.onMediaDetaching=function(){var e=this.media;e&&e.ended&&(u.b.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0);var t=this.tracks;t&&t.forEach(function(e){e.details&&e.details.fragments.forEach(function(e){e.loadCounter=void 0})}),e&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvseeked=this.onvended=null),this.media=this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1,this.stopLoad()},t.prototype.onMediaSeeking=function(){this.state===le.ENDED&&(this.state=le.IDLE),this.media&&(this.lastCurrentTime=this.media.currentTime),void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold),this.tick()},t.prototype.onMediaEnded=function(){this.startPosition=this.lastCurrentTime=0},t.prototype.onAudioTracksUpdated=function(e){u.b.log("audio tracks updated"),this.tracks=e.audioTracks},t.prototype.onAudioTrackSwitching=function(e){var t=!!e.url;this.trackId=e.id,this.fragCurrent=null,this.state=le.PAUSED,this.waitingFragment=null,t?this.timer||(this.timer=setInterval(this.ontick,100)):this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),t&&(this.audioSwitch=!0,this.state=le.IDLE,void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold)),this.tick()},t.prototype.onAudioTrackLoaded=function(e){var t=e.details,r=e.id,i=this.tracks[r],n=t.totalduration,o=0;if(u.b.log("track "+r+" loaded ["+t.startSN+","+t.endSN+"],duration:"+n),t.live){var a=i.details;a&&t.fragments.length>0?(B(a,t),o=t.fragments[0].start,t.PTSKnown?u.b.log("live audio playlist sliding:"+o.toFixed(3)):u.b.log("live audio playlist - outdated PTS, unknown sliding")):(t.PTSKnown=!1,u.b.log("live audio playlist - first load, unknown sliding"))}else t.PTSKnown=!1;if(i.details=t,!this.startFragRequested){if(-1===this.startPosition){var s=t.startTimeOffset;isNaN(s)?this.startPosition=0:(u.b.log("start time offset found in playlist, adjust startPosition to "+s),this.startPosition=s)}this.nextLoadPosition=this.startPosition}this.state===le.WAITING_TRACK&&(this.state=le.IDLE),this.tick()},t.prototype.onKeyLoaded=function(){this.state===le.KEY_LOADING&&(this.state=le.IDLE,this.tick())},t.prototype.onFragLoaded=function(e){var t=this.fragCurrent,r=e.frag;if(this.state===le.FRAG_LOADING&&t&&"audio"===r.type&&r.level===t.level&&r.sn===t.sn){var i=this.tracks[this.trackId],n=i.details,o=n.totalduration,s=t.level,c=t.sn,l=t.cc,d=this.config.defaultAudioCodec||i.audioCodec||"mp4a.40.2",f=this.stats=e.stats;if("initSegment"===c)this.state=le.IDLE,f.tparsed=f.tbuffered=performance.now(),n.initSegment.data=e.payload,this.hls.trigger(a.a.FRAG_BUFFERED,{stats:f,frag:t,id:"audio"}),this.tick();else{this.state=le.PARSING,this.appended=!1,this.demuxer||(this.demuxer=new N(this.hls,"audio"));var h=this.initPTS[l],p=n.initSegment?n.initSegment.data:[];if(n.initSegment||void 0!==h){this.pendingBuffering=!0,u.b.log("Demuxing "+c+" of ["+n.startSN+" ,"+n.endSN+"],track "+s);this.demuxer.push(e.payload,p,d,null,t,o,!1,h)}else u.b.log("unknown video PTS for continuity counter "+l+", waiting for video PTS before demuxing audio frag "+c+" of ["+n.startSN+" ,"+n.endSN+"],track "+s),this.waitingFragment=e,this.state=le.WAITING_INIT_PTS}}this.fragLoadError=0},t.prototype.onFragParsingInitSegment=function(e){var t=this.fragCurrent,r=e.frag;if(t&&"audio"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===le.PARSING){var i=e.tracks,n=void 0;if(i.video&&delete i.video,n=i.audio){n.levelCodec=n.codec,n.id=e.id,this.hls.trigger(a.a.BUFFER_CODECS,i),u.b.log("audio track:audio,container:"+n.container+",codecs[level/parsed]=["+n.levelCodec+"/"+n.codec+"]");var o=n.initSegment;if(o){var s={type:"audio",data:o,parent:"audio",content:"initSegment"};this.audioSwitch?this.pendingData=[s]:(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(a.a.BUFFER_APPENDING,s))}this.tick()}}},t.prototype.onFragParsingData=function(e){var t=this,r=this.fragCurrent,i=e.frag;if(r&&"audio"===e.id&&"audio"===e.type&&i.sn===r.sn&&i.level===r.level&&this.state===le.PARSING){var n=this.trackId,o=this.tracks[n],s=this.hls;isNaN(e.endPTS)&&(e.endPTS=e.startPTS+r.duration,e.endDTS=e.startDTS+r.duration),u.b.log("parsed "+e.type+",PTS:["+e.startPTS.toFixed(3)+","+e.endPTS.toFixed(3)+"],DTS:["+e.startDTS.toFixed(3)+"/"+e.endDTS.toFixed(3)+"],nb:"+e.nb),F(o.details,r,e.startPTS,e.endPTS);var c=this.audioSwitch,l=this.media,d=!1;if(c&&l)if(l.readyState){var f=l.currentTime;u.b.log("switching audio track : currentTime:"+f),f>=e.startPTS&&(u.b.log("switching audio track : flushing all audio"),this.state=le.BUFFER_FLUSHING,s.trigger(a.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),d=!0,this.audioSwitch=!1,s.trigger(a.a.AUDIO_TRACK_SWITCHED,{id:n}))}else this.audioSwitch=!1,s.trigger(a.a.AUDIO_TRACK_SWITCHED,{id:n});var h=this.pendingData;this.audioSwitch||([e.data1,e.data2].forEach(function(t){t&&t.length&&h.push({type:e.type,data:t,parent:"audio",content:"data"})}),!d&&h.length&&(h.forEach(function(e){t.state===le.PARSING&&(t.pendingBuffering=!0,t.hls.trigger(a.a.BUFFER_APPENDING,e))}),this.pendingData=[],this.appended=!0)),this.tick()}},t.prototype.onFragParsed=function(e){var t=this.fragCurrent,r=e.frag;t&&"audio"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===le.PARSING&&(this.stats.tparsed=performance.now(),this.state=le.PARSED,this._checkAppendedParsed())},t.prototype.onBufferReset=function(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1},t.prototype.onBufferCreated=function(e){var t=e.tracks.audio;t&&(this.mediaBuffer=t.buffer,this.loadedmetadata=!0),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer)},t.prototype.onBufferAppended=function(e){if("audio"===e.parent){var t=this.state;t!==le.PARSING&&t!==le.PARSED||(this.pendingBuffering=e.pending>0,this._checkAppendedParsed())}},t.prototype._checkAppendedParsed=function(){if(!(this.state!==le.PARSED||this.appended&&this.pendingBuffering)){var e=this.fragCurrent,t=this.stats,r=this.hls;if(e){this.fragPrevious=e,t.tbuffered=performance.now(),r.trigger(a.a.FRAG_BUFFERED,{stats:t,frag:e,id:"audio"});var i=this.mediaBuffer?this.mediaBuffer:this.media;u.b.log("audio buffered : "+U.toString(i.buffered)),this.audioSwitch&&this.appended&&(this.audioSwitch=!1,r.trigger(a.a.AUDIO_TRACK_SWITCHED,{id:this.trackId})),this.state=le.IDLE}this.tick()}},t.prototype.onError=function(e){var t=e.frag;if(!t||"audio"===t.type)switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:if(!e.fatal){var r=this.fragLoadError;r?r++:r=1;var i=this.config;if(r<=i.fragLoadingMaxRetry){this.fragLoadError=r,t.loadCounter=0;var n=Math.min(Math.pow(2,r-1)*i.fragLoadingRetryDelay,i.fragLoadingMaxRetryTimeout);u.b.warn("audioStreamController: frag loading failed, retry in "+n+" ms"),this.retryDate=performance.now()+n,this.state=le.FRAG_LOADING_WAITING_RETRY}else u.b.error("audioStreamController: "+e.details+" reaches max retry, redispatch as fatal ..."),e.fatal=!0,this.state=le.ERROR}break;case s.a.FRAG_LOOP_LOADING_ERROR:case s.a.AUDIO_TRACK_LOAD_ERROR:case s.a.AUDIO_TRACK_LOAD_TIMEOUT:case s.a.KEY_LOAD_ERROR:case s.a.KEY_LOAD_TIMEOUT:this.state!==le.ERROR&&(this.state=e.fatal?le.ERROR:le.IDLE,u.b.warn("audioStreamController: "+e.details+" while loading frag,switch to "+this.state+" state ..."));break;case s.a.BUFFER_FULL_ERROR:if("audio"===e.parent&&(this.state===le.PARSING||this.state===le.PARSED)){var o=this.mediaBuffer,c=this.media.currentTime;if(o&&D.isBuffered(o,c)&&D.isBuffered(o,c+.5)){var l=this.config;l.maxMaxBufferLength>=l.maxBufferLength&&(l.maxMaxBufferLength/=2,u.b.warn("audio:reduce max buffer length to "+l.maxMaxBufferLength+"s"),this.fragLoadIdx+=2*l.fragLoadingLoopThreshold),this.state=le.IDLE}else u.b.warn("buffer full error also media.currentTime is not buffered, flush audio buffer"),this.fragCurrent=null,this.state=le.BUFFER_FLUSHING,this.hls.trigger(a.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"})}}},t.prototype.onBufferFlushed=function(){var e=this,t=this.pendingData;t&&t.length?(u.b.log("appending pending audio data on Buffer Flushed"),t.forEach(function(t){e.hls.trigger(a.a.BUFFER_APPENDING,t)}),this.appended=!0,this.pendingData=[],this.state=le.PARSED):(this.state=le.IDLE,this.fragPrevious=null,this.tick())},ce(t,[{key:"state",set:function(e){if(this.state!==e){var t=this.state;this._state=e,u.b.log("audio stream:"+t+"->"+e)}},get:function(){return this._state}}]),t}(l),fe=function(){if("undefined"!=typeof window&&window.VTTCue)return window.VTTCue;var e="auto",t={"":!0,lr:!0,rl:!0},r={start:!0,middle:!0,end:!0,left:!0,right:!0};function i(e){return"string"==typeof e&&(!!r[e.toLowerCase()]&&e.toLowerCase())}function n(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)e[i]=r[i]}return e}function o(r,o,a){var s=this,u=function(){if("undefined"!=typeof navigator)return/MSIE\s8\.0/.test(navigator.userAgent)}(),c={};u?s=document.createElement("custom"):c.enumerable=!0,s.hasBeenReset=!1;var l="",d=!1,f=r,h=o,p=a,m=null,v="",g=!0,y="auto",_="start",b=50,w="middle",E=50,S="middle";if(Object.defineProperty(s,"id",n({},c,{get:function(){return l},set:function(e){l=""+e}})),Object.defineProperty(s,"pauseOnExit",n({},c,{get:function(){return d},set:function(e){d=!!e}})),Object.defineProperty(s,"startTime",n({},c,{get:function(){return f},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");f=e,this.hasBeenReset=!0}})),Object.defineProperty(s,"endTime",n({},c,{get:function(){return h},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");h=e,this.hasBeenReset=!0}})),Object.defineProperty(s,"text",n({},c,{get:function(){return p},set:function(e){p=""+e,this.hasBeenReset=!0}})),Object.defineProperty(s,"region",n({},c,{get:function(){return m},set:function(e){m=e,this.hasBeenReset=!0}})),Object.defineProperty(s,"vertical",n({},c,{get:function(){return v},set:function(e){var r=function(e){return"string"==typeof e&&!!t[e.toLowerCase()]&&e.toLowerCase()}(e);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");v=r,this.hasBeenReset=!0}})),Object.defineProperty(s,"snapToLines",n({},c,{get:function(){return g},set:function(e){g=!!e,this.hasBeenReset=!0}})),Object.defineProperty(s,"line",n({},c,{get:function(){return y},set:function(t){if("number"!=typeof t&&t!==e)throw new SyntaxError("An invalid number or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(s,"lineAlign",n({},c,{get:function(){return _},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");_=t,this.hasBeenReset=!0}})),Object.defineProperty(s,"position",n({},c,{get:function(){return b},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");b=e,this.hasBeenReset=!0}})),Object.defineProperty(s,"positionAlign",n({},c,{get:function(){return w},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");w=t,this.hasBeenReset=!0}})),Object.defineProperty(s,"size",n({},c,{get:function(){return E},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(s,"align",n({},c,{get:function(){return S},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),s.displayState=void 0,u)return s}return o.prototype.getCueAsHTML=function(){return window.WebVTT.convertCueToDOMTree(window,this.text)},o}(),he=function(){return{decode:function(e){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}};function pe(){this.window=window,this.state="INITIAL",this.buffer="",this.decoder=new he,this.regionList=[]}function me(){this.values=Object.create(null)}function ve(e,t,r,i){var n=i?e.split(i):[e];for(var o in n)if("string"==typeof n[o]){var a=n[o].split(r);if(2===a.length)t(a[0],a[1])}}me.prototype={set:function(e,t){this.get(e)||""===t||(this.values[e]=t)},get:function(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t},has:function(e){return e in this.values},alt:function(e,t,r){for(var i=0;i<r.length;++i)if(t===r[i]){this.set(e,t);break}},integer:function(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))},percent:function(e,t){return!!(t.match(/^([\d]{1,3})(\.[\d]*)?%$/)&&(t=parseFloat(t))>=0&&t<=100)&&(this.set(e,t),!0)}};var ge=new fe(0,0,0),ye="middle"===ge.align?"middle":"center";function _e(e,t,r){var i=e;function n(){var t=function(e){function t(e,t,r,i){return 3600*(0|e)+60*(0|t)+(0|r)+(0|i)/1e3}var r=e.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);return r?r[3]?t(r[1],r[2],r[3].replace(":",""),r[4]):r[1]>59?t(r[1],r[2],0,r[4]):t(0,r[1],r[2],r[4]):null}(e);if(null===t)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function o(){e=e.replace(/^\s+/,"")}if(o(),t.startTime=n(),o(),"--\x3e"!==e.substr(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);e=e.substr(3),o(),t.endTime=n(),o(),function(e,t){var i=new me;ve(e,function(e,t){switch(e){case"region":for(var n=r.length-1;n>=0;n--)if(r[n].id===t){i.set(e,r[n].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":var o=t.split(","),a=o[0];i.integer(e,a),i.percent(e,a)&&i.set("snapToLines",!1),i.alt(e,a,["auto"]),2===o.length&&i.alt("lineAlign",o[1],["start",ye,"end"]);break;case"position":o=t.split(","),i.percent(e,o[0]),2===o.length&&i.alt("positionAlign",o[1],["start",ye,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",ye,"end","left","right"])}},/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");var n=i.get("line","auto");"auto"===n&&-1===ge.line&&(n=-1),t.line=n,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",ye);var o=i.get("position","auto");"auto"===o&&50===ge.position&&(o="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=o}(e,t)}function be(e){return e.replace(/<br(?: \/)?>/gi,"\n")}pe.prototype={parse:function(e){var t=this;function r(){var e=t.buffer,r=0;for(e=be(e);r<e.length&&"\r"!==e[r]&&"\n"!==e[r];)++r;var i=e.substr(0,r);return"\r"===e[r]&&++r,"\n"===e[r]&&++r,t.buffer=e.substr(r),i}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{var i;if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;var n=(i=r()).match(/^()?WEBVTT([ \t].*)?$/);if(!n||!n[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}for(var o=!1;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(o?o=!1:i=r(),t.state){case"HEADER":/:/.test(i)?ve(i,function(e,t){switch(e){case"Region":console.log("parse region",t)}},/:/):i||(t.state="ID");continue;case"NOTE":i||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(i)){t.state="NOTE";break}if(!i)continue;if(t.cue=new fe(0,0,""),t.state="CUE",-1===i.indexOf("--\x3e")){t.cue.id=i;continue}case"CUE":try{_e(i,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":var a=-1!==i.indexOf("--\x3e");if(!i||a&&(o=!0)){t.oncue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}t.cue.text&&(t.cue.text+="\n"),t.cue.text+=i;continue;case"BADCUE":i||(t.state="ID");continue}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this},flush:function(){try{if(this.buffer+=this.decoder.decode(),(this.cue||"HEADER"===this.state)&&(this.buffer+="\n\n",this.parse()),"INITIAL"===this.state)throw new Error("Malformed WebVTT signature.")}catch(e){throw e}return this.onflush&&this.onflush(),this}};var we=pe;function Ee(e,t,r,i){for(var n,o,a,s,u,c=window.VTTCue||window.TextTrackCue,l=0;l<i.rows.length;l++)if(a=!0,s=0,u="",!(n=i.rows[l]).isEmpty()){for(var d=0;d<n.chars.length;d++)n.chars[d].uchar.match(/\s/)&&a?s++:(u+=n.chars[d].uchar,a=!1);n.cueStartTime=t,t===r&&(r+=1e-4),o=new c(t,r,be(u.trim())),s>=16?s--:s++,navigator.userAgent.match(/Firefox\//)?o.line=l+1:o.line=l>7?l-2:l+1,o.align="left",o.position=Math.max(0,Math.min(100,s/32*100+(navigator.userAgent.match(/Firefox\//)?50:0))),e.addCue(o)}}function Se(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var Te={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Oe=function(e){var t=e;return Te.hasOwnProperty(e)&&(t=Te[e]),String.fromCharCode(t)},Ae=15,$e=100,ke={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},De={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Ie={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},xe={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Ce=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Me={verboseFilter:{DATA:3,DEBUG:3,INFO:2,WARNING:2,TEXT:1,ERROR:0},time:null,verboseLevel:0,setTime:function(e){this.time=e},log:function(e,t){var r=this.verboseFilter[e];this.verboseLevel>=r&&console.log(this.time+" ["+e+"] "+t)}},Pe=function(e){for(var t=[],r=0;r<e.length;r++)t.push(e[r].toString(16));return t},Le=function(){function e(t,r,i,n,o){Se(this,e),this.foreground=t||"white",this.underline=r||!1,this.italics=i||!1,this.background=n||"black",this.flash=o||!1}return e.prototype.reset=function(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1},e.prototype.setStyles=function(e){for(var t=["foreground","underline","italics","background","flash"],r=0;r<t.length;r++){var i=t[r];e.hasOwnProperty(i)&&(this[i]=e[i])}},e.prototype.isDefault=function(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash},e.prototype.equals=function(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash},e.prototype.copy=function(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash},e.prototype.toString=function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash},e}(),Re=function(){function e(t,r,i,n,o,a){Se(this,e),this.uchar=t||" ",this.penState=new Le(r,i,n,o,a)}return e.prototype.reset=function(){this.uchar=" ",this.penState.reset()},e.prototype.setChar=function(e,t){this.uchar=e,this.penState.copy(t)},e.prototype.setPenState=function(e){this.penState.copy(e)},e.prototype.equals=function(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)},e.prototype.copy=function(e){this.uchar=e.uchar,this.penState.copy(e.penState)},e.prototype.isEmpty=function(){return" "===this.uchar&&this.penState.isDefault()},e}(),Ne=function(){function e(){Se(this,e),this.chars=[];for(var t=0;t<$e;t++)this.chars.push(new Re);this.pos=0,this.currPenState=new Le}return e.prototype.equals=function(e){for(var t=!0,r=0;r<$e;r++)if(!this.chars[r].equals(e.chars[r])){t=!1;break}return t},e.prototype.copy=function(e){for(var t=0;t<$e;t++)this.chars[t].copy(e.chars[t])},e.prototype.isEmpty=function(){for(var e=!0,t=0;t<$e;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e},e.prototype.setCursor=function(e){this.pos!==e&&(this.pos=e),this.pos<0?(Me.log("ERROR","Negative cursor position "+this.pos),this.pos=0):this.pos>$e&&(Me.log("ERROR","Too large cursor position "+this.pos),this.pos=$e)},e.prototype.moveCursor=function(e){var t=this.pos+e;if(e>1)for(var r=this.pos+1;r<t+1;r++)this.chars[r].setPenState(this.currPenState);this.setCursor(t)},e.prototype.backSpace=function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)},e.prototype.insertChar=function(e){e>=144&&this.backSpace();var t=Oe(e);this.pos>=$e?Me.log("ERROR","Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))},e.prototype.clearFromPos=function(e){var t;for(t=e;t<$e;t++)this.chars[t].reset()},e.prototype.clear=function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()},e.prototype.clearToEndOfRow=function(){this.clearFromPos(this.pos)},e.prototype.getTextString=function(){for(var e=[],t=!0,r=0;r<$e;r++){var i=this.chars[r].uchar;" "!==i&&(t=!1),e.push(i)}return t?"":e.join("")},e.prototype.setPenStyles=function(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)},e}(),je=function(){function e(){Se(this,e),this.rows=[];for(var t=0;t<Ae;t++)this.rows.push(new Ne);this.currRow=Ae-1,this.nrRollUpRows=null,this.reset()}return e.prototype.reset=function(){for(var e=0;e<Ae;e++)this.rows[e].clear();this.currRow=Ae-1},e.prototype.equals=function(e){for(var t=!0,r=0;r<Ae;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t},e.prototype.copy=function(e){for(var t=0;t<Ae;t++)this.rows[t].copy(e.rows[t])},e.prototype.isEmpty=function(){for(var e=!0,t=0;t<Ae;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e},e.prototype.backSpace=function(){this.rows[this.currRow].backSpace()},e.prototype.clearToEndOfRow=function(){this.rows[this.currRow].clearToEndOfRow()},e.prototype.insertChar=function(e){this.rows[this.currRow].insertChar(e)},e.prototype.setPen=function(e){this.rows[this.currRow].setPenStyles(e)},e.prototype.moveCursor=function(e){this.rows[this.currRow].moveCursor(e)},e.prototype.setCursor=function(e){Me.log("INFO","setCursor: "+e),this.rows[this.currRow].setCursor(e)},e.prototype.setPAC=function(e){Me.log("INFO","pacData = "+JSON.stringify(e));var t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(var r=0;r<Ae;r++)this.rows[r].clear();var i=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){var o=n.rows[i].cueStartTime;if(o&&o<Me.time)for(var a=0;a<this.nrRollUpRows;a++)this.rows[t-this.nrRollUpRows+a+1].copy(n.rows[i+a])}}this.currRow=t;var s=this.rows[this.currRow];if(null!==e.indent){var u=e.indent,c=Math.max(u-1,0);s.setCursor(e.indent),e.color=s.chars[c].penState.foreground}var l={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(l)},e.prototype.setBkgData=function(e){Me.log("INFO","bkgData = "+JSON.stringify(e)),this.backSpace(),this.setPen(e),this.insertChar(32)},e.prototype.setRollUpRows=function(e){this.nrRollUpRows=e},e.prototype.rollUp=function(){if(null!==this.nrRollUpRows){Me.log("TEXT",this.getDisplayText());var e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),Me.log("INFO","Rolling up")}else Me.log("DEBUG","roll_up but nrRollUpRows not set yet")},e.prototype.getDisplayText=function(e){e=e||!1;for(var t=[],r="",i=-1,n=0;n<Ae;n++){var o=this.rows[n].getTextString();o&&(i=n+1,e?t.push("Row "+i+": '"+o+"'"):t.push(o.trim()))}return t.length>0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r},e.prototype.getTextAndFormat=function(){return this.rows},e}(),Fe=function(){function e(t,r){Se(this,e),this.chNr=t,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new je,this.nonDisplayedMemory=new je,this.lastOutputScreen=new je,this.currRollUpRow=this.displayedMemory.rows[Ae-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}return e.prototype.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.currRollUpRow=this.displayedMemory.rows[Ae-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.lastCueEndTime=null},e.prototype.getHandler=function(){return this.outputFilter},e.prototype.setHandler=function(e){this.outputFilter=e},e.prototype.setPAC=function(e){this.writeScreen.setPAC(e)},e.prototype.setBkgData=function(e){this.writeScreen.setBkgData(e)},e.prototype.setMode=function(e){e!==this.mode&&(this.mode=e,Me.log("INFO","MODE="+e),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)},e.prototype.insertChars=function(e){for(var t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);var r=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";Me.log("INFO",r+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(Me.log("TEXT","DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())},e.prototype.ccRCL=function(){Me.log("INFO","RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")},e.prototype.ccBS=function(){Me.log("INFO","BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())},e.prototype.ccAOF=function(){},e.prototype.ccAON=function(){},e.prototype.ccDER=function(){Me.log("INFO","DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()},e.prototype.ccRU=function(e){Me.log("INFO","RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)},e.prototype.ccFON=function(){Me.log("INFO","FON - Flash On"),this.writeScreen.setPen({flash:!0})},e.prototype.ccRDC=function(){Me.log("INFO","RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")},e.prototype.ccTR=function(){Me.log("INFO","TR"),this.setMode("MODE_TEXT")},e.prototype.ccRTD=function(){Me.log("INFO","RTD"),this.setMode("MODE_TEXT")},e.prototype.ccEDM=function(){Me.log("INFO","EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)},e.prototype.ccCR=function(){Me.log("CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)},e.prototype.ccENM=function(){Me.log("INFO","ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()},e.prototype.ccEOC=function(){if(Me.log("INFO","EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,Me.log("TEXT","DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)},e.prototype.ccTO=function(e){Me.log("INFO","TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)},e.prototype.ccMIDROW=function(e){var t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{var r=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][r]}Me.log("INFO","MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)},e.prototype.outputDataUpdate=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=Me.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue&&(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),!0===e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue()),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))},e.prototype.cueSplitAtTime=function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))},e}(),Be=function(){function e(t,r,i){Se(this,e),this.field=t||1,this.outputs=[r,i],this.channels=[new Fe(1,r),new Fe(2,i)],this.currChNr=-1,this.lastCmdA=null,this.lastCmdB=null,this.bufferedData=[],this.startTime=null,this.lastTime=null,this.dataCounters={padding:0,char:0,cmd:0,other:0}}return e.prototype.getHandler=function(e){return this.channels[e].getHandler()},e.prototype.setHandler=function(e,t){this.channels[e].setHandler(t)},e.prototype.addData=function(e,t){var r,i,n,o=!1;this.lastTime=e,Me.setTime(e);for(var a=0;a<t.length;a+=2)if(i=127&t[a],n=127&t[a+1],0!==i||0!==n){if(Me.log("DATA","["+Pe([t[a],t[a+1]])+"] -> ("+Pe([i,n])+")"),(r=this.parseCmd(i,n))||(r=this.parseMidrow(i,n)),r||(r=this.parsePAC(i,n)),r||(r=this.parseBackgroundAttributes(i,n)),!r)if(o=this.parseChars(i,n))if(this.currChNr&&this.currChNr>=0)this.channels[this.currChNr-1].insertChars(o);else Me.log("WARNING","No channel found yet. TEXT-MODE?");r?this.dataCounters.cmd+=2:o?this.dataCounters.char+=2:(this.dataCounters.other+=2,Me.log("WARNING","Couldn't parse cleaned data "+Pe([i,n])+" orig: "+Pe([t[a],t[a+1]])))}else this.dataCounters.padding+=2},e.prototype.parseCmd=function(e,t){var r=null;if(!((20===e||28===e)&&32<=t&&t<=47)&&!((23===e||31===e)&&33<=t&&t<=35))return!1;if(e===this.lastCmdA&&t===this.lastCmdB)return this.lastCmdA=null,this.lastCmdB=null,Me.log("DEBUG","Repeated command ("+Pe([e,t])+") is dropped"),!0;r=20===e||23===e?1:2;var i=this.channels[r-1];return 20===e||28===e?32===t?i.ccRCL():33===t?i.ccBS():34===t?i.ccAOF():35===t?i.ccAON():36===t?i.ccDER():37===t?i.ccRU(2):38===t?i.ccRU(3):39===t?i.ccRU(4):40===t?i.ccFON():41===t?i.ccRDC():42===t?i.ccTR():43===t?i.ccRTD():44===t?i.ccEDM():45===t?i.ccCR():46===t?i.ccENM():47===t&&i.ccEOC():i.ccTO(t-32),this.lastCmdA=e,this.lastCmdB=t,this.currChNr=r,!0},e.prototype.parseMidrow=function(e,t){var r=null;return(17===e||25===e)&&32<=t&&t<=47&&((r=17===e?1:2)!==this.currChNr?(Me.log("ERROR","Mismatch channel in midrow parsing"),!1):(this.channels[r-1].ccMIDROW(t),Me.log("DEBUG","MIDROW ("+Pe([e,t])+")"),!0))},e.prototype.parsePAC=function(e,t){var r,i=null;if(!((17<=e&&e<=23||25<=e&&e<=31)&&64<=t&&t<=127)&&!((16===e||24===e)&&64<=t&&t<=95))return!1;if(e===this.lastCmdA&&t===this.lastCmdB)return this.lastCmdA=null,this.lastCmdB=null,!0;r=e<=23?1:2,i=64<=t&&t<=95?1===r?ke[e]:Ie[e]:1===r?De[e]:xe[e];var n=this.interpretPAC(i,t);return this.channels[r-1].setPAC(n),this.lastCmdA=e,this.lastCmdB=t,this.currChNr=r,!0},e.prototype.interpretPAC=function(e,t){var r=t,i={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,i.underline=1==(1&r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i},e.prototype.parseChars=function(e,t){var r=null,i=null,n=null;if(e>=25?(r=2,n=e-8):(r=1,n=e),17<=n&&n<=19){var o=t;o=17===n?t+80:18===n?t+112:t+144,Me.log("INFO","Special char '"+Oe(o)+"' in channel "+r),i=[o]}else 32<=e&&e<=127&&(i=0===t?[e]:[e,t]);if(i){var a=Pe(i);Me.log("DEBUG","Char codes = "+a.join(",")),this.lastCmdA=null,this.lastCmdB=null}return i},e.prototype.parseBackgroundAttributes=function(e,t){var r,i,n;return((16===e||24===e)&&32<=t&&t<=47||(23===e||31===e)&&45<=t&&t<=47)&&(r={},16===e||24===e?(i=Math.floor((t-32)/2),r.background=Ce[i],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0)),n=e<24?1:2,this.channels[n-1].setBkgData(r),this.lastCmdA=null,this.lastCmdB=null,!0)},e.prototype.reset=function(){for(var e=0;e<this.channels.length;e++)this.channels[e]&&this.channels[e].reset();this.lastCmdA=null,this.lastCmdB=null},e.prototype.cueSplitAtTime=function(e){for(var t=0;t<this.channels.length;t++)this.channels[t]&&this.channels[t].cueSplitAtTime(e)},e}();var Ue=function(){function e(t,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.timelineController=t,this.track=r,this.startTime=null,this.endTime=null,this.screen=null}return e.prototype.dispatchCue=function(){null!==this.startTime&&(this.timelineController.addCues("textTrack"+this.track,this.startTime,this.endTime,this.screen),this.startTime=null)},e.prototype.newCue=function(e,t,r){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.track)},e}(),ze=function(e,t,r){return e.substr(r||0,t.length)===t},Ge=function(e){for(var t=5381,r=e.length;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()},We={parse:function(e,t,r,i,n,o){var a=Object(Z.b)(new Uint8Array(e)).trim().replace(/\r\n|\n\r|\n|\r/g,"\n").split("\n"),s="00:00.000",u=0,c=0,l=0,d=[],f=void 0,h=!0,p=new we;p.oncue=function(e){var t=r[i],n=r.ccOffset;t&&t.new&&(void 0!==c?n=r.ccOffset=t.start:function(e,t,r){var i=e[t],n=e[i.prevCC];if(!n||!n.new&&i.new)return e.ccOffset=e.presentationOffset=i.start,void(i.new=!1);for(;n&&n.new;)e.ccOffset+=i.start-n.start,i.new=!1,n=e[(i=n).prevCC];e.presentationOffset=r}(r,i,l)),l&&(n=l+r.ccOffset-r.presentationOffset),e.startTime+=n-c,e.endTime+=n-c,e.id=Ge(e.startTime.toString())+Ge(e.endTime.toString())+Ge(e.text),e.text=decodeURIComponent(encodeURIComponent(e.text)),e.endTime>0&&d.push(e)},p.onparsingerror=function(e){f=e},p.onflush=function(){f&&o?o(f):n(d)},a.forEach(function(e){if(h){if(ze(e,"X-TIMESTAMP-MAP=")){h=!1,e.substr(16).split(",").forEach(function(e){ze(e,"LOCAL:")?s=e.substr(6):ze(e,"MPEGTS:")&&(u=parseInt(e.substr(7)))});try{u-=t=t<0?t+8589934592:t,r=s,i=parseInt(r.substr(-3)),n=parseInt(r.substr(-6,2)),o=parseInt(r.substr(-9,2)),a=r.length>9?parseInt(r.substr(0,r.indexOf(":"))):0,c=(isNaN(i)||isNaN(n)||isNaN(o)||isNaN(a)?-1:(i+=1e3*n,i+=6e4*o,i+=36e5*a))/1e3,l=u/9e4,-1===c&&(f=new Error("Malformed X-TIMESTAMP-MAP: "+e))}catch(t){f=new Error("Malformed X-TIMESTAMP-MAP: "+e)}return}""===e&&(h=!1)}var r,i,n,o,a;p.parse(e+"\n")}),p.flush()}};function He(e){if(e&&e.cues)for(;e.cues.length>0;)e.removeCue(e.cues[0])}var Ve=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r,a.a.MEDIA_ATTACHING,a.a.MEDIA_DETACHING,a.a.FRAG_PARSING_USERDATA,a.a.FRAG_DECRYPTED,a.a.MANIFEST_LOADING,a.a.MANIFEST_LOADED,a.a.FRAG_LOADED,a.a.LEVEL_SWITCHING,a.a.INIT_PTS_FOUND));if(i.hls=r,i.config=r.config,i.enabled=!0,i.Cues=r.config.cueHandler,i.textTracks=[],i.tracks=[],i.unparsedVttFrags=[],i.initPTS=void 0,i.cueRanges=[],i.config.enableCEA708Captions){var n=new Ue(i,1),o=new Ue(i,2);i.cea608Parser=new Be(0,n,o)}return i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.addCues=function(e,t,r,i){for(var n,o,a,s,u=this.cueRanges,c=!1,l=u.length;l--;){var d=u[l],f=(n=d[0],o=d[1],a=t,s=r,Math.min(o,s)-Math.max(n,a));if(f>=0&&(d[0]=Math.min(d[0],t),d[1]=Math.max(d[1],r),c=!0,f/(r-t)>.5))return}c||u.push([t,r]),this.Cues.newCue(this[e],t,r,i)},t.prototype.onInitPtsFound=function(e){var t=this;void 0===this.initPTS&&(this.initPTS=e.initPTS),this.unparsedVttFrags.length&&(this.unparsedVttFrags.forEach(function(e){t.onFragLoaded(e)}),this.unparsedVttFrags=[])},t.prototype.getExistingTrack=function(e){var t=this.media;if(t)for(var r=0;r<t.textTracks.length;r++){var i=t.textTracks[r];if(!0===i["textTrack"+e])return i}return null},t.prototype.sendAddTrackEvent=function(e,t){var r=null;try{r=new window.Event("addtrack")}catch(e){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)},t.prototype.createCaptionsTrack=function(e){var t="textTrack"+e;if(!this[t]){var r=this.getExistingTrack(e);if(r)this[t]=r,He(this[t]),this.sendAddTrackEvent(this[t],this.media);else{var i=this.createTextTrack("captions",this.config["captionsTextTrack"+e+"Label"],this.config.captionsTextTrack1LanguageCode);i&&(i[t]=!0,this[t]=i)}}},t.prototype.createTextTrack=function(e,t,r){var i=this.media;if(i)return i.addTextTrack(e,t,r)},t.prototype.destroy=function(){l.prototype.destroy.call(this)},t.prototype.onMediaAttaching=function(e){this.media=e.media,this._cleanTracks()},t.prototype.onMediaDetaching=function(){He(this.textTrack1),He(this.textTrack2)},t.prototype.onManifestLoading=function(){this.lastSn=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0},this._cleanTracks()},t.prototype._cleanTracks=function(){var e=this.media;if(e){var t=e.textTracks;if(t)for(var r=0;r<t.length;r++)He(t[r])}},t.prototype.onManifestLoaded=function(e){var t=this;if(this.textTracks=[],this.unparsedVttFrags=this.unparsedVttFrags||[],this.initPTS=void 0,this.cueRanges=[],this.config.enableWebVTT){this.tracks=e.subtitles||[];var r=this.media?this.media.textTracks:[];this.tracks.forEach(function(e,i){var n=void 0;if(i<r.length){var o=r[i];(function(e,t){return e&&e.label===t.name&&!(e.textTrack1||e.textTrack2)})(o,e)&&(n=o)}n||(n=t.createTextTrack("subtitles",e.name,e.lang)),n.mode=e.default?"showing":"hidden",t.textTracks.push(n)})}},t.prototype.onLevelSwitching=function(){this.enabled="NONE"!==this.hls.currentLevel.closedCaptions},t.prototype.onFragLoaded=function(e){var t=e.frag,r=e.payload;if("main"===t.type){var i=t.sn;if(i!==this.lastSn+1){var n=this.cea608Parser;n&&n.reset()}this.lastSn=i}else if("subtitle"===t.type)if(r.byteLength){if(void 0===this.initPTS)return void this.unparsedVttFrags.push(e);var o=t.decryptdata;null!=o&&null!=o.key&&"AES-128"===o.method||this._parseVTTs(t,r)}else this.hls.trigger(a.a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t})},t.prototype._parseVTTs=function(e,t){var r=this.vttCCs;r[e.cc]||(r[e.cc]={start:e.start,prevCC:this.prevCC,new:!0},this.prevCC=e.cc);var i=this.textTracks,n=this.hls;We.parse(t,this.initPTS,r,e.cc,function(t){var r=i[e.trackId];t.forEach(function(e){if(!r.cues.getCueById(e.id))try{r.addCue(e)}catch(i){var t=new window.TextTrackCue(e.startTime,e.endTime,e.text);t.id=e.id,r.addCue(t)}}),n.trigger(a.a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},function(t){u.b.log("Failed to parse VTT cue: "+t),n.trigger(a.a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e})})},t.prototype.onFragDecrypted=function(e){var t=e.payload,r=e.frag;if("subtitle"===r.type){if(void 0===this.initPTS)return void this.unparsedVttFrags.push(e);this._parseVTTs(r,t)}},t.prototype.onFragParsingUserdata=function(e){if(this.enabled&&this.config.enableCEA708Captions)for(var t=0;t<e.samples.length;t++){var r=this.extractCea608Data(e.samples[t].bytes);this.cea608Parser.addData(e.samples[t].pts,r)}},t.prototype.extractCea608Data=function(e){for(var t,r,i,n=31&e[0],o=2,a=[],s=0;s<n;s++)t=e[o++],r=127&e[o++],i=127&e[o++],0===r&&0===i||0!=(4&t)&&0===(3&t)&&(a.push(r),a.push(i));return a},t}(l),Ye=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}();function Ke(e){for(var t=[],r=0;r<e.length;r++)"subtitles"===e[r].kind&&t.push(e[r]);return t}var Ze=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r,a.a.MEDIA_ATTACHED,a.a.MEDIA_DETACHING,a.a.MANIFEST_LOADING,a.a.MANIFEST_LOADED,a.a.SUBTITLE_TRACK_LOADED));return i.tracks=[],i.trackId=-1,i.media=void 0,i.subtitleDisplay=!1,i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype._onTextTracksChanged=function(){if(this.media){for(var e=-1,t=Ke(this.media.textTracks),r=0;r<t.length;r++)"showing"===t[r].mode&&(e=r);this.subtitleTrack=e}},t.prototype.destroy=function(){l.prototype.destroy.call(this)},t.prototype.onMediaAttached=function(e){var t=this;this.media=e.media,this.media&&(void 0!==this.queuedDefaultTrack&&(this.subtitleTrack=this.queuedDefaultTrack,delete this.queuedDefaultTrack),this.trackChangeListener=this._onTextTracksChanged.bind(this),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.subtitlePollingInterval=setInterval(function(){t.trackChangeListener()},500):this.media.textTracks.addEventListener("change",this.trackChangeListener))},t.prototype.onMediaDetaching=function(){this.media&&(this.useTextTrackPolling?clearInterval(this.subtitlePollingInterval):this.media.textTracks.removeEventListener("change",this.trackChangeListener),this.media=void 0)},t.prototype.onManifestLoading=function(){this.tracks=[],this.trackId=-1},t.prototype.onManifestLoaded=function(e){var t=this,r=e.subtitles||[];this.tracks=r,this.trackId=-1,this.hls.trigger(a.a.SUBTITLE_TRACKS_UPDATED,{subtitleTracks:r}),r.forEach(function(e){e.default&&(t.media?t.subtitleTrack=e.id:t.queuedDefaultTrack=e.id)})},t.prototype.onTick=function(){var e=this.trackId,t=this.tracks[e];if(t){var r=t.details;void 0!==r&&!0!==r.live||(u.b.log("(re)loading playlist for subtitle track "+e),this.hls.trigger(a.a.SUBTITLE_TRACK_LOADING,{url:t.url,id:e}))}},t.prototype.onSubtitleTrackLoaded=function(e){var t=this;e.id<this.tracks.length&&(u.b.log("subtitle track "+e.id+" loaded"),this.tracks[e.id].details=e.details,e.details.live&&!this.timer&&(this.timer=setInterval(function(){t.onTick()},1e3*e.details.targetduration,this)),!e.details.live&&this.timer&&(clearInterval(this.timer),this.timer=null))},t.prototype.setSubtitleTrackInternal=function(e){if(!(e<-1||e>=this.tracks.length)){this.timer&&(clearInterval(this.timer),this.timer=null);var t=Ke(this.media.textTracks);if(-1!==this.trackId&&this.subtitleDisplay&&(t[this.trackId].mode="hidden"),this.trackId=e,u.b.log("switching to subtitle track "+e),this.hls.trigger(a.a.SUBTITLE_TRACK_SWITCH,{id:e}),-1!==e){var r=this.tracks[e];this.subtitleDisplay&&(t[e].mode="showing");var i=r.details;void 0!==i&&!0!==i.live||(u.b.log("(re)loading playlist for subtitle track "+e),this.hls.trigger(a.a.SUBTITLE_TRACK_LOADING,{url:r.url,id:e}))}}},Ye(t,[{key:"subtitleTracks",get:function(){return this.tracks}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(e){this.trackId!==e&&this.setSubtitleTrackInternal(e)}}]),t}(l),Qe=r(4);var Xe={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING"},qe=function(e){function t(r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r,a.a.MEDIA_ATTACHED,a.a.ERROR,a.a.KEY_LOADED,a.a.FRAG_LOADED,a.a.SUBTITLE_TRACKS_UPDATED,a.a.SUBTITLE_TRACK_SWITCH,a.a.SUBTITLE_TRACK_LOADED,a.a.SUBTITLE_FRAG_PROCESSED));return i.config=r.config,i.vttFragSNsProcessed={},i.vttFragQueues=void 0,i.currentlyProcessing=null,i.state=Xe.STOPPED,i.currentTrackId=-1,i.ticks=0,i.decrypter=new Qe.a(r.observer,r.config),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.destroy=function(){l.prototype.destroy.call(this),this.state=Xe.STOPPED},t.prototype.clearVttFragQueues=function(){var e=this;this.vttFragQueues={},this.tracks.forEach(function(t){e.vttFragQueues[t.id]=[]})},t.prototype.nextFrag=function(){if(null===this.currentlyProcessing&&this.currentTrackId>-1&&this.vttFragQueues[this.currentTrackId].length){var e=this.currentlyProcessing=this.vttFragQueues[this.currentTrackId].shift();this.fragCurrent=e,this.hls.trigger(a.a.FRAG_LOADING,{frag:e}),this.state=Xe.FRAG_LOADING}},t.prototype.onSubtitleFragProcessed=function(e){e.success&&this.vttFragSNsProcessed[e.frag.trackId].push(e.frag.sn),this.currentlyProcessing=null,this.state=Xe.IDLE,this.nextFrag()},t.prototype.onMediaAttached=function(){this.state=Xe.IDLE},t.prototype.onError=function(e){var t=e.frag;t&&"subtitle"!==t.type||this.currentlyProcessing&&(this.currentlyProcessing=null,this.nextFrag())},t.prototype.tick=function(){var e=this;this.ticks++,1===this.ticks&&(this.doTick(),this.ticks>1&&setTimeout(function(){e.tick()},1),this.ticks=0)},t.prototype.doTick=function(){var e=this;switch(this.state){case Xe.IDLE:var t,r=this.tracks,i=this.currentTrackId,n=this.vttFragSNsProcessed[i],o=this.vttFragQueues[i],s=this.currentlyProcessing?this.currentlyProcessing.sn:-1;if(!r)break;if(i<r.length&&(t=r[i].details),void 0===t)break;t.fragments.forEach(function(t){(function(e){return n.indexOf(e.sn)>-1})(t)||t.sn===s||function(e){return o.some(function(t){return t.sn===e.sn})}(t)||(t.decryptdata&&null!=t.decryptdata.uri&&null==t.decryptdata.key?(u.b.log("Loading key for "+t.sn),e.state=Xe.KEY_LOADING,e.hls.trigger(a.a.KEY_LOADING,{frag:t})):(t.trackId=i,o.push(t),e.nextFrag()))})}},t.prototype.onSubtitleTracksUpdated=function(e){var t=this;u.b.log("subtitle tracks updated"),this.tracks=e.subtitleTracks,this.clearVttFragQueues(),this.vttFragSNsProcessed={},this.tracks.forEach(function(e){t.vttFragSNsProcessed[e.id]=[]})},t.prototype.onSubtitleTrackSwitch=function(e){this.currentTrackId=e.id,this.clearVttFragQueues()},t.prototype.onSubtitleTrackLoaded=function(){this.tick()},t.prototype.onKeyLoaded=function(){this.state===Xe.KEY_LOADING&&(this.state=Xe.IDLE,this.tick())},t.prototype.onFragLoaded=function(e){var t=this.fragCurrent,r=e.frag.decryptdata,i=e.frag,n=this.hls;if(this.state===Xe.FRAG_LOADING&&t&&"subtitle"===e.frag.type&&t.sn===e.frag.sn&&e.payload.byteLength>0&&null!=r&&null!=r.key&&"AES-128"===r.method){var o;try{o=performance.now()}catch(e){o=Date.now()}this.decrypter.decrypt(e.payload,r.key.buffer,r.iv.buffer,function(e){var t;try{t=performance.now()}catch(e){t=Date.now()}n.trigger(a.a.FRAG_DECRYPTED,{frag:i,payload:e,stats:{tstart:o,tdecrypt:t}})})}},t}(l),Je={autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,initialLiveManifestSize:1,maxBufferLength:30,maxBufferSize:6e7,maxBufferHole:.5,maxSeekHole:2,lowBufferWatchdogPeriod:.5,highBufferWatchdogPeriod:3,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,liveDurationInfinity:!1,maxMaxBufferLength:600,enableWorker:!0,enableSoftwareAES:!0,manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,startLevel:void 0,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,fragLoadingLoopThreshold:3,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:ae,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,fetchSetup:void 0,abrController:ee,bufferController:re,capLevelController:ne,fpsController:oe,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0};Je.subtitleStreamController=qe,Je.subtitleTrackController=Ze,Je.timelineController=Ve,Je.cueHandler=i,Je.enableCEA708Captions=!0,Je.enableWebVTT=!0,Je.captionsTextTrack1Label="English",Je.captionsTextTrack1LanguageCode="en",Je.captionsTextTrack2Label="Spanish",Je.captionsTextTrack2LanguageCode="es",Je.audioStreamController=de,Je.audioTrackController=ue;var et=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}();var tt=function(){function e(){var t=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);var i=e.DefaultConfig;if((r.liveSyncDurationCount||r.liveMaxLatencyDurationCount)&&(r.liveSyncDuration||r.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");for(var n in i)n in r||(r[n]=i[n]);if(void 0!==r.liveMaxLatencyDurationCount&&r.liveMaxLatencyDurationCount<=r.liveSyncDurationCount)throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');if(void 0!==r.liveMaxLatencyDuration&&(r.liveMaxLatencyDuration<=r.liveSyncDuration||void 0===r.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');Object(u.a)(r.debug),this.config=r,this._autoLevelCapping=-1;var o=this.observer=new C.a;o.trigger=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];o.emit.apply(o,[e,e].concat(r))},o.off=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];o.removeListener.apply(o,[e].concat(r))},this.on=o.on.bind(o),this.off=o.off.bind(o),this.trigger=o.trigger.bind(o);var a=this.abrController=new r.abrController(this),s=new r.bufferController(this),c=new r.capLevelController(this),l=new r.fpsController(this),d=new O(this),f=new A(this),h=new $(this),p=new Q(this),m=[this.levelController=new K(this),this.streamController=new V(this)],v=r.audioStreamController;v&&m.push(new v(this)),this.networkControllers=m;var g=[d,f,h,a,s,c,l,p];if(v=r.audioTrackController){var y=new v(this);this.audioTrackController=y,g.push(y)}if(v=r.subtitleTrackController){var _=new v(this);this.subtitleTrackController=_,g.push(_)}[r.subtitleStreamController,r.timelineController].forEach(function(e){e&&g.push(new e(t))}),this.coreComponents=g}return e.isSupported=function(){return e=L(),t=window.SourceBuffer||window.WebKitSourceBuffer,r=e&&"function"==typeof e.isTypeSupported&&e.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),i=!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove,!!r&&!!i;var e,t,r,i},et(e,null,[{key:"version",get:function(){return"0.8.9"}},{key:"Events",get:function(){return a.a}},{key:"ErrorTypes",get:function(){return s.b}},{key:"ErrorDetails",get:function(){return s.a}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:Je},set:function(t){e.defaultConfig=t}}]),e.prototype.destroy=function(){u.b.log("destroy"),this.trigger(a.a.DESTROYING),this.detachMedia(),this.coreComponents.concat(this.networkControllers).forEach(function(e){e.destroy()}),this.url=null,this.observer.removeAllListeners(),this._autoLevelCapping=-1},e.prototype.attachMedia=function(e){u.b.log("attachMedia"),this.media=e,this.trigger(a.a.MEDIA_ATTACHING,{media:e})},e.prototype.detachMedia=function(){u.b.log("detachMedia"),this.trigger(a.a.MEDIA_DETACHING),this.media=null},e.prototype.loadSource=function(e){e=o.a.buildAbsoluteURL(window.location.href,e,{alwaysNormalize:!0}),u.b.log("loadSource:"+e),this.url=e,this.trigger(a.a.MANIFEST_LOADING,{url:e})},e.prototype.startLoad=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1;u.b.log("startLoad("+e+")"),this.networkControllers.forEach(function(t){t.startLoad(e)})},e.prototype.stopLoad=function(){u.b.log("stopLoad"),this.networkControllers.forEach(function(e){e.stopLoad()})},e.prototype.swapAudioCodec=function(){u.b.log("swapAudioCodec"),this.streamController.swapAudioCodec()},e.prototype.recoverMediaError=function(){u.b.log("recoverMediaError");var e=this.media;this.detachMedia(),this.attachMedia(e)},et(e,[{key:"levels",get:function(){return this.levelController.levels}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){u.b.log("set currentLevel:"+e),this.loadLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){u.b.log("set nextLevel:"+e),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){u.b.log("set loadLevel:"+e),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(e){u.b.log("set firstLevel:"+e),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){return this.levelController.startLevel},set:function(e){u.b.log("set startLevel:"+e);-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){u.b.log("set autoLevelCapping:"+e),this._autoLevelCapping=e}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){for(var e=this.levels,t=this.config.minAutoBitrate,r=e?e.length:0,i=0;i<r;i++){if((e[i].realBitrate?Math.max(e[i].realBitrate,e[i].bitrate):e[i].bitrate)>t)return i}return 0}},{key:"maxAutoLevel",get:function(){var e=this.levels,t=this.autoLevelCapping;return-1===t&&e&&e.length?e.length-1:t}},{key:"nextAutoLevel",get:function(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)},set:function(e){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,e)}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"liveSyncPosition",get:function(){return this.streamController.liveSyncPosition}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}}]),e}();t.default=tt},function(e,t,r){function i(e){var t=[],r=e.toString(),i=r.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/);if(!i)return t;for(var n,o=i[1],a=new RegExp("(\\\\n|\\W)"+(o+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")+"\\((/\\*.*?\\*/)?s?.*?([\\.|\\-|\\w|/|@]+).*?\\)","g");n=a.exec(r);)t.push(n[3]);return t}e.exports=function(e,t){t=t||{};var n=r.m,o=t.all?Object.keys(n):function(e,t){for(var r=[t],n=[],o={};r.length;){var a=r.pop();if(!o[a]&&e[a]){o[a]=!0,n.push(a);var s=i(e[a]);r=r.concat(s)}}return n}(n,e),a="("+function(e){var t={};function r(i){if(t[i])return t[i].exports;var n=t[i]={i:i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}r.m=e,r.c=t,r.i=function(e){return e},r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:i})},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="/",r.oe=function(e){throw console.error(e),e};var i=r(r.s=ENTRY_MODULE);return i.default||i}.toString().replace("ENTRY_MODULE",JSON.stringify(e))+")({"+o.map(function(e){return JSON.stringify(e)+": "+n[e].toString()}).join(",")+"})(self);",s=new window.Blob([a],{type:"text/javascript"});if(t.bare)return s;var u=(window.URL||window.webkitURL||window.mozURL||window.msURL).createObjectURL(s),c=new window.Worker(u);return c.objectURL=u,c}},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i=r(7),n=r(1),o=r(0),a=r(5),s=r.n(a);t.default=function(e){var t=new s.a;t.trigger=function(e){for(var r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];t.emit.apply(t,[e,e].concat(i))},t.off=function(e){for(var r=arguments.length,i=Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];t.removeListener.apply(t,[e].concat(i))};var r=function(t,r){e.postMessage({event:t,data:r})};e.addEventListener("message",function(n){var a=n.data;switch(a.cmd){case"init":var s=JSON.parse(a.config);e.demuxer=new i.a(t,a.typeSupported,s,a.vendor);try{Object(o.a)(!0===s.debug)}catch(e){console.warn("demuxerWorker: unable to enable logs")}r("init",null);break;case"demux":e.demuxer.push(a.data,a.decryptdata,a.initSegment,a.audioCodec,a.videoCodec,a.timeOffset,a.discontinuity,a.trackSwitch,a.contiguous,a.duration,a.accurateTimeOffset,a.defaultInitPTS)}}),t.on(n.a.FRAG_DECRYPTED,r),t.on(n.a.FRAG_PARSING_INIT_SEGMENT,r),t.on(n.a.FRAG_PARSED,r),t.on(n.a.ERROR,r),t.on(n.a.FRAG_PARSING_METADATA,r),t.on(n.a.FRAG_PARSING_USERDATA,r),t.on(n.a.INIT_PTS_FOUND,r),t.on(n.a.FRAG_PARSING_DATA,function(t,r){var i=[],n={event:t,data:r};r.data1&&(n.data1=r.data1.buffer,i.push(r.data1.buffer),delete r.data1),r.data2&&(n.data2=r.data2.buffer,i.push(r.data2.buffer),delete r.data2),e.postMessage(n,i)})}}]).default},e.exports=r()}),HlsCore=unwrapExports(hls),defaultCustomConfig={debug:!1,enableWorker:!0},_class$9;function _applyDecoratedDescriptor$8(e,t,r,i,n){var o={};return Object.keys(i).forEach(function(e){o[e]=i[e]}),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce(function(r,i){return i(e,t,r)||r},o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var LOG_TAG$1="chimee-kernel-hls",Hls=(_class$9=function(e){function t(e,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||_Object$getPrototypeOf(t)).call(this));if(n.version="1.3.0",!isElement(e))throw new Error("video element passed in "+LOG_TAG$1+" must be a HTMLVideoElement, but not "+(void 0===e?"undefined":_typeof(e)));if(!isObject(r))throw new Error("config of "+LOG_TAG$1+" must be an Object but not "+(void 0===r?"undefined":_typeof(r)));return n.video=e,n.config=r,n.customConfig=deepAssign({},defaultCustomConfig,i),n.hlsKernel=new HlsCore(n.customConfig),n.bindEvents(),n.attachMedia(),n}return _inherits(t,CustEvent),_createClass(t,null,[{key:"isSupport",value:function(){return HlsCore.isSupported()}}]),_createClass(t,[{key:"bindEvents",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.hlsKernel;t&&t[e?"off":"on"](HlsCore.Events.ERROR,this.hlsErrorHandler)}},{key:"load",value:function(){return this.hlsKernel.loadSource(this.config.src)}},{key:"startLoad",value:function(){return this.hlsKernel.startLoad()}},{key:"stopLoad",value:function(){return this.hlsKernel.stopLoad()}},{key:"attachMedia",value:function(){return this.hlsKernel.attachMedia(this.video)}},{key:"play",value:function(){return this.video.play()}},{key:"destroy",value:function(){return this.bindEvents(!0),this.hlsKernel.destroy()}},{key:"seek",value:function(e){this.video.currentTime=e}},{key:"pause",value:function(){return this.video.pause()}},{key:"refresh",value:function(){return this.hlsKernel.stopLoad(),this.hlsKernel.loadSource(this.config.src)}},{key:"hlsErrorHandler",value:function(e,t){this.emit("error",t),this.emit(e,t),Log$1.error(LOG_TAG$1+(e?" "+e:""),t.details)}}]),t}(),_applyDecoratedDescriptor$8(_class$9.prototype,"hlsErrorHandler",[autobind],_Object$getOwnPropertyDescriptor(_class$9.prototype,"hlsErrorHandler"),_class$9.prototype),_class$9),lib$2=createCommonjsModule(function(module,exports){var factory;factory=function(){return function(e){var t={};function r(i){if(t[i])return t[i].exports;var n=t[i]={i:i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=e,r.c=t,r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:i})},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=6)}([function(e,t,r){!function(e){function t(e){return e&&e.__esModule?e.default:e}function r(e,t){return e(t={exports:{}},t.exports),t.exports}var i=Math.ceil,n=Math.floor,o=function(e){return isNaN(e=+e)?0:(e>0?n:i)(e)},a=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e},s=r(function(e){var t=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=t)}),u=r(function(e){var t=e.exports={version:"2.4.0"};"number"==typeof __e&&(__e=t)}),c=function(e,t,r){if(function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!")}(e),void 0===t)return e;switch(r){case 1:return function(r){return e.call(t,r)};case 2:return function(r,i){return e.call(t,r,i)};case 3:return function(r,i,n){return e.call(t,r,i,n)}}return function(){return e.apply(t,arguments)}},l=function(e){return"object"==typeof e?null!==e:"function"==typeof e},d=function(e){if(!l(e))throw TypeError(e+" is not an object!");return e},f=function(e){try{return!!e()}catch(e){return!0}},h=!f(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),p=s.document,m=l(p)&&l(p.createElement),v=function(e){return m?p.createElement(e):{}},g=!h&&!f(function(){return 7!=Object.defineProperty(v("div"),"a",{get:function(){return 7}}).a}),y=function(e,t){if(!l(e))return e;var r,i;if(t&&"function"==typeof(r=e.toString)&&!l(i=r.call(e)))return i;if("function"==typeof(r=e.valueOf)&&!l(i=r.call(e)))return i;if(!t&&"function"==typeof(r=e.toString)&&!l(i=r.call(e)))return i;throw TypeError("Can't convert object to primitive value")},_=Object.defineProperty,b={f:h?Object.defineProperty:function(e,t,r){if(d(e),t=y(t,!0),d(r),g)try{return _(e,t,r)}catch(e){}if("get"in r||"set"in r)throw TypeError("Accessors not supported!");return"value"in r&&(e[t]=r.value),e}},w=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},E=h?function(e,t,r){return b.f(e,t,w(1,r))}:function(e,t,r){return e[t]=r,e},S=function(e,t,r){var i,n,o,a=e&S.F,l=e&S.G,d=e&S.S,f=e&S.P,h=e&S.B,p=e&S.W,m=l?u:u[t]||(u[t]={}),v=m.prototype,g=l?s:d?s[t]:(s[t]||{}).prototype;for(i in l&&(r=t),r)(n=!a&&g&&void 0!==g[i])&&i in m||(o=n?g[i]:r[i],m[i]=l&&"function"!=typeof g[i]?r[i]:h&&n?c(o,s):p&&g[i]==o?function(e){var t=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,r)}return new e(t,r,i)}return e.apply(this,arguments)};return t.prototype=e.prototype,t}(o):f&&"function"==typeof o?c(Function.call,o):o,f&&((m.virtual||(m.virtual={}))[i]=o,e&S.R&&v&&!v[i]&&E(v,i,o)))};S.F=1,S.G=2,S.S=4,S.P=8,S.B=16,S.W=32,S.U=64,S.R=128;var T,O=S,A=E,$={}.hasOwnProperty,k=function(e,t){return $.call(e,t)},D={}.toString,I=function(e){return D.call(e).slice(8,-1)},x=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==I(e)?e.split(""):Object(e)},C=function(e){return x(a(e))},M=Math.min,P=Math.max,L=Math.min,R=s["__core-js_shared__"]||(s["__core-js_shared__"]={}),N=function(e){return R[e]||(R[e]={})},j=0,F=Math.random(),B=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++j+F).toString(36))},U=N("keys"),z=function(e){return U[e]||(U[e]=B(e))},G=(T=!1,function(e,t,r){var i,n,a=C(e),s=(n=a.length)>0?M(o(n),9007199254740991):0,u=function(e,t){return(e=o(e))<0?P(e+t,0):L(e,t)}(r,s);if(T&&t!=t){for(;s>u;)if((i=a[u++])!=i)return!0}else for(;s>u;u++)if((T||u in a)&&a[u]===t)return T||u||0;return!T&&-1}),W=z("IE_PROTO"),H=function(e,t){var r,i=C(e),n=0,o=[];for(r in i)r!=W&&k(i,r)&&o.push(r);for(;t.length>n;)k(i,r=t[n++])&&(~G(o,r)||o.push(r));return o},V="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),Y=Object.keys||function(e){return H(e,V)},K=h?Object.defineProperties:function(e,t){d(e);for(var r,i=Y(t),n=i.length,o=0;n>o;)b.f(e,r=i[o++],t[r]);return e},Z=s.document&&document.documentElement,Q=z("IE_PROTO"),X=function(){},q=function(){var e,t=v("iframe"),r=V.length;for(t.style.display="none",Z.appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),q=e.F;r--;)delete q.prototype[V[r]];return q()},J=Object.create||function(e,t){var r;return null!==e?(X.prototype=d(e),r=new X,X.prototype=null,r[Q]=e):r=q(),void 0===t?r:K(r,t)},ee=r(function(e){var t=N("wks"),r=s.Symbol,i="function"==typeof r,n=e.exports=function(e){return t[e]||(t[e]=i&&r[e]||(i?r:B)("Symbol."+e))};n.store=t}),te=b.f,re=ee("toStringTag"),ie=function(e,t,r){e&&!k(e=r?e:e.prototype,re)&&te(e,re,{configurable:!0,value:t})},ne={};E(ne,ee("iterator"),function(){return this});var oe,ae=function(e,t,r){e.prototype=J(ne,{next:w(1,r)}),ie(e,t+" Iterator")},se=function(e){return Object(a(e))},ue=z("IE_PROTO"),ce=Object.prototype,le=Object.getPrototypeOf||function(e){return e=se(e),k(e,ue)?e[ue]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?ce:null},de=ee("iterator"),fe=!([].keys&&"next"in[].keys()),he=function(e,t,r,i,n,o,a){ae(r,t,i);var s,u,c,l=function(e){if(!fe&&e in p)return p[e];switch(e){case"keys":case"values":return function(){return new r(this,e)}}return function(){return new r(this,e)}},d=t+" Iterator",f="values"==n,h=!1,p=e.prototype,m=p[de]||p["@@iterator"]||n&&p[n],v=m||l(n),g=n?f?l("entries"):v:void 0,y="Array"==t&&p.entries||m;if(y&&(c=le(y.call(new e)))!==Object.prototype&&ie(c,d,!0),f&&m&&"values"!==m.name&&(h=!0,v=function(){return m.call(this)}),a&&(fe||h||!p[de])&&E(p,de,v),n)if(s={values:f?v:l("values"),keys:o?v:l("keys"),entries:g},a)for(u in s)u in p||A(p,u,s[u]);else O(O.P+O.F*(fe||h),t,s);return s},pe=(oe=!0,function(e,t){var r,i,n=String(a(e)),s=o(t),u=n.length;return s<0||s>=u?oe?"":void 0:(r=n.charCodeAt(s))<55296||r>56319||s+1===u||(i=n.charCodeAt(s+1))<56320||i>57343?oe?n.charAt(s):r:oe?n.slice(s,s+2):i-56320+(r-55296<<10)+65536});he(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,r=this._i;return r>=t.length?{value:void 0,done:!0}:(e=pe(t,r),this._i+=e.length,{value:e,done:!1})});for(var me=function(e,t){return{value:t,done:!!e}},ve=(he(Array,"Array",function(e,t){this._t=C(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,r=this._i++;return!e||r>=e.length?(this._t=void 0,me(1)):me(0,"keys"==t?r:"values"==t?e[r]:[r,e[r]])},"values"),ee("toStringTag")),ge=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],ye=0;ye<5;ye++){var _e=ge[ye],be=s[_e],we=be&&be.prototype;we&&!we[ve]&&E(we,ve,_e)}var Ee={f:ee},Se=Ee.f("iterator"),Te=r(function(e){e.exports={default:Se,__esModule:!0}}),Oe=r(function(e){var t=B("meta"),r=b.f,i=0,n=Object.isExtensible||function(){return!0},o=!f(function(){return n(Object.preventExtensions({}))}),a=function(e){r(e,t,{value:{i:"O"+ ++i,w:{}}})},s=e.exports={KEY:t,NEED:!1,fastKey:function(e,r){if(!l(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!k(e,t)){if(!n(e))return"F";if(!r)return"E";a(e)}return e[t].i},getWeak:function(e,r){if(!k(e,t)){if(!n(e))return!0;if(!r)return!1;a(e)}return e[t].w},onFreeze:function(e){return o&&s.NEED&&n(e)&&!k(e,t)&&a(e),e}}}),Ae=b.f,$e=function(e){var t=u.Symbol||(u.Symbol={});"_"==e.charAt(0)||e in t||Ae(t,e,{value:Ee.f(e)})},ke={f:Object.getOwnPropertySymbols},De={f:{}.propertyIsEnumerable},Ie=Array.isArray||function(e){return"Array"==I(e)},xe=V.concat("length","prototype"),Ce={f:Object.getOwnPropertyNames||function(e){return H(e,xe)}},Me=Ce.f,Pe={}.toString,Le="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],Re={f:function(e){return Le&&"[object Window]"==Pe.call(e)?function(e){try{return Me(e)}catch(e){return Le.slice()}}(e):Me(C(e))}},Ne=Object.getOwnPropertyDescriptor,je={f:h?Ne:function(e,t){if(e=C(e),t=y(t,!0),g)try{return Ne(e,t)}catch(e){}if(k(e,t))return w(!De.f.call(e,t),e[t])}},Fe=Oe.KEY,Be=je.f,Ue=b.f,ze=Re.f,Ge=s.Symbol,We=s.JSON,He=We&&We.stringify,Ve=ee("_hidden"),Ye=ee("toPrimitive"),Ke={}.propertyIsEnumerable,Ze=N("symbol-registry"),Qe=N("symbols"),Xe=N("op-symbols"),qe=Object.prototype,Je="function"==typeof Ge,et=s.QObject,tt=!et||!et.prototype||!et.prototype.findChild,rt=h&&f(function(){return 7!=J(Ue({},"a",{get:function(){return Ue(this,"a",{value:7}).a}})).a})?function(e,t,r){var i=Be(qe,t);i&&delete qe[t],Ue(e,t,r),i&&e!==qe&&Ue(qe,t,i)}:Ue,it=function(e){var t=Qe[e]=J(Ge.prototype);return t._k=e,t},nt=Je&&"symbol"==typeof Ge.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof Ge},ot=function(e,t,r){return e===qe&&ot(Xe,t,r),d(e),t=y(t,!0),d(r),k(Qe,t)?(r.enumerable?(k(e,Ve)&&e[Ve][t]&&(e[Ve][t]=!1),r=J(r,{enumerable:w(0,!1)})):(k(e,Ve)||Ue(e,Ve,w(1,{})),e[Ve][t]=!0),rt(e,t,r)):Ue(e,t,r)},at=function(e,t){d(e);for(var r,i=function(e){var t=Y(e),r=ke.f;if(r)for(var i,n=r(e),o=De.f,a=0;n.length>a;)o.call(e,i=n[a++])&&t.push(i);return t}(t=C(t)),n=0,o=i.length;o>n;)ot(e,r=i[n++],t[r]);return e},st=function(e){var t=Ke.call(this,e=y(e,!0));return!(this===qe&&k(Qe,e)&&!k(Xe,e))&&(!(t||!k(this,e)||!k(Qe,e)||k(this,Ve)&&this[Ve][e])||t)},ut=function(e,t){if(e=C(e),t=y(t,!0),e!==qe||!k(Qe,t)||k(Xe,t)){var r=Be(e,t);return!r||!k(Qe,t)||k(e,Ve)&&e[Ve][t]||(r.enumerable=!0),r}},ct=function(e){for(var t,r=ze(C(e)),i=[],n=0;r.length>n;)k(Qe,t=r[n++])||t==Ve||t==Fe||i.push(t);return i},lt=function(e){for(var t,r=e===qe,i=ze(r?Xe:C(e)),n=[],o=0;i.length>o;)!k(Qe,t=i[o++])||r&&!k(qe,t)||n.push(Qe[t]);return n};Je||(A((Ge=function(){if(this instanceof Ge)throw TypeError("Symbol is not a constructor!");var e=B(arguments.length>0?arguments[0]:void 0),t=function(r){this===qe&&t.call(Xe,r),k(this,Ve)&&k(this[Ve],e)&&(this[Ve][e]=!1),rt(this,e,w(1,r))};return h&&tt&&rt(qe,e,{configurable:!0,set:t}),it(e)}).prototype,"toString",function(){return this._k}),je.f=ut,b.f=ot,Ce.f=Re.f=ct,De.f=st,ke.f=lt,Ee.f=function(e){return it(ee(e))}),O(O.G+O.W+O.F*!Je,{Symbol:Ge});for(var dt="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),ft=0;dt.length>ft;)ee(dt[ft++]);for(var dt=Y(ee.store),ft=0;dt.length>ft;)$e(dt[ft++]);O(O.S+O.F*!Je,"Symbol",{for:function(e){return k(Ze,e+="")?Ze[e]:Ze[e]=Ge(e)},keyFor:function(e){if(nt(e))return function(e,t){for(var r,i=C(e),n=Y(i),o=n.length,a=0;o>a;)if(i[r=n[a++]]===t)return r}(Ze,e);throw TypeError(e+" is not a symbol!")},useSetter:function(){tt=!0},useSimple:function(){tt=!1}}),O(O.S+O.F*!Je,"Object",{create:function(e,t){return void 0===t?J(e):at(J(e),t)},defineProperty:ot,defineProperties:at,getOwnPropertyDescriptor:ut,getOwnPropertyNames:ct,getOwnPropertySymbols:lt}),We&&O(O.S+O.F*(!Je||f(function(){var e=Ge();return"[null]"!=He([e])||"{}"!=He({a:e})||"{}"!=He(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!nt(e)){for(var t,r,i=[e],n=1;arguments.length>n;)i.push(arguments[n++]);return"function"==typeof(t=i[1])&&(r=t),!r&&Ie(t)||(t=function(e,t){if(r&&(t=r.call(this,e,t)),!nt(t))return t}),i[1]=t,He.apply(We,i)}}}),Ge.prototype[Ye]||E(Ge.prototype,Ye,Ge.prototype.valueOf),ie(Ge,"Symbol"),ie(Math,"Math",!0),ie(s.JSON,"JSON",!0),$e("asyncIterator"),$e("observable");var ht=u.Symbol,pt=r(function(e){e.exports={default:ht,__esModule:!0}}),mt=t(r(function(e,t){t.__esModule=!0;var r=o(Te),i=o(pt),n="function"==typeof i.default&&"symbol"==typeof r.default?function(e){return typeof e}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":typeof e};function o(e){return e&&e.__esModule?e:{default:e}}t.default="function"==typeof i.default&&"symbol"===n(r.default)?function(e){return void 0===e?"undefined":n(e)}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":void 0===e?"undefined":n(e)}})),vt=t(r(function(e,t){t.__esModule=!0,t.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}}));O(O.S+O.F*!h,"Object",{defineProperty:b.f});var gt=u.Object,yt=function(e,t,r){return gt.defineProperty(e,t,r)},_t=r(function(e){e.exports={default:yt,__esModule:!0}}),bt=t(r(function(e,t){t.__esModule=!0;var r,i=(r=_t)&&r.__esModule?r:{default:r};t.default=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),(0,i.default)(e,n.key,n)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}()})),wt=Object.assign,Et=!wt||f(function(){var e={},t={},r=Symbol(),i="abcdefghijklmnopqrst";return e[r]=7,i.split("").forEach(function(e){t[e]=e}),7!=wt({},e)[r]||Object.keys(wt({},t)).join("")!=i})?function(e,t){for(var r=se(e),i=arguments.length,n=1,o=ke.f,a=De.f;i>n;)for(var s,u=x(arguments[n++]),c=o?Y(u).concat(o(u)):Y(u),l=c.length,d=0;l>d;)a.call(u,s=c[d++])&&(r[s]=u[s]);return r}:wt;O(O.S+O.F,"Object",{assign:Et});var St=u.Object.assign,Tt=t(r(function(e){e.exports={default:St,__esModule:!0}}));O(O.S,"Object",{create:J});var Ot,At,$t,kt,Dt=u.Object,It=function(e,t){return Dt.create(e,t)},xt=t(r(function(e){e.exports={default:It,__esModule:!0}}));Ot="keys",At=function(){return function(e){return Y(se(e))}},$t=(u.Object||{})[Ot]||Object[Ot],(kt={})[Ot]=At($t),O(O.S+O.F*f(function(){$t(1)}),"Object",kt);var Ct=u.Object.keys,Mt=(r(function(e){e.exports={default:Ct,__esModule:!0}}),Math.floor);O(O.S,"Number",{isInteger:function(e){return!l(e)&&isFinite(e)&&Mt(e)===e}});var Pt=u.Number.isInteger,Lt=(r(function(e){e.exports={default:Pt,__esModule:!0}}),"\t\n\v\f\r \u2028\u2029\ufeff"),Rt="["+Lt+"]",Nt=RegExp("^"+Rt+Rt+"*"),jt=RegExp(Rt+Rt+"*$"),Ft=function(e,t,r){var i={},n=f(function(){return!!Lt[e]()||"
"!="
"[e]()}),o=i[e]=n?t(Bt):Lt[e];r&&(i[r]=o),O(O.P+O.F*n,"String",i)},Bt=Ft.trim=function(e,t){return e=String(a(e)),1&t&&(e=e.replace(Nt,"")),2&t&&(e=e.replace(jt,"")),e},Ut=Ft,zt=s.parseFloat,Gt=Ut.trim,Wt=1/zt(Lt+"-0")!=-1/0?function(e){var t=Gt(String(e),3),r=zt(t);return 0===r&&"-"==t.charAt(0)?-0:r}:zt;O(O.S+O.F*(Number.parseFloat!=Wt),"Number",{parseFloat:Wt});var Ht=parseFloat;function Vt(e){return"function"==typeof e}function Yt(e){return Object(e)===e&&"[object Object]"===String(e)&&!Vt(e)&&(t=e,!Array.isArray(t));var t}r(function(e){e.exports={default:Ht,__esModule:!0}});var Kt=xt(null);function Zt(e,t){var r=e.__evt_id;r||(Object.defineProperty(e,"__evt_id",{writable:!0,enumerable:!1,configurable:!0}),r=e.__evt_id=++Kt.count);var i=r+"_"+t,n=Kt[i];return n||(n=Kt[i]=[]),n}function Qt(e,t,r){var i=xt(null);i.type=t,i.target=e,r&&Tt(i,Yt(r)?r:{data:r}),Zt(e,t).forEach(function(t){(t[1]||t[0]).apply(e,[i])})}function Xt(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments[4];Vt(i)&&!n&&(n=i,i=void 0);var o=[r,void 0,i];i&&!n&&(n=function(){qt(e,t,r,i);for(var n=arguments.length,o=Array(n),a=0;a<n;a++)o[a]=arguments[a];r.apply(e,o)}),n&&(o[1]=n),Zt(e,t).push(o)}function qt(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=Zt(e,t);if(r||i){var o=-1,a=void 0;return n.find(function(e,t){if((!r||e[0]===r)&&(!i||e[2]))return o=t,a=e[1],!0}),-1!==o&&n.splice(o,1),a}n.length=0}Kt.count=0;var Jt=function(){function e(t,r){var i=this;if(vt(this,e),Object.defineProperty(this,"__target",{writable:!0,enumerable:!1,configurable:!0}),this.__target=this,t){if("object"!==(void 0===t?"undefined":mt(t)))throw new Error("CusEvent target are not object");this.__target=t,r&&["on","once","off","emit"].forEach(function(e){t[e]=i[e]})}}return bt(e,[{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return Xt(this.__target,e,t,r),this}},{key:"once",value:function(e,t){return this.on(e,t,!0)}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return qt(this.__target,e,t,r),this}},{key:"emit",value:function(e,t){return Qt(this.__target,e,{data:t}),this}}]),e}();e.emitEventCache=Qt,e.addEventCache=Xt,e.removeEventCache=qt,e.CustEvent=Jt,Object.defineProperty(e,"__esModule",{value:!0})}(t)},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});t.ERRORNO={NET_ERROR:100,CODEC_ERROR:101,CANNOT_SEEK:102,ENDOFSTREAM_ERROR:103,MEDIASOURCE_ERROR:104,SOURCEBUFFER_ERROR:105,SBABORT_ERROR:106,APPENDBUFFER_ERROR:107}},function(e,t,r){e.exports=function(){function e(e){return e&&e.__esModule?e.default:e}function t(e,t){return e(t={exports:{}},t.exports),t.exports}var r=e(t(function(e,t){t.__esModule=!0,t.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}})),i=t(function(e){var t=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=t)}),n=t(function(e){var t=e.exports={version:"2.5.0"};"number"==typeof __e&&(__e=t)}),o=function(e,t,r){if(function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!")}(e),void 0===t)return e;switch(r){case 1:return function(r){return e.call(t,r)};case 2:return function(r,i){return e.call(t,r,i)};case 3:return function(r,i,n){return e.call(t,r,i,n)}}return function(){return e.apply(t,arguments)}},a=function(e){return"object"==typeof e?null!==e:"function"==typeof e},s=function(e){if(!a(e))throw TypeError(e+" is not an object!");return e},u=function(e){try{return!!e()}catch(e){return!0}},c=!u(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),l=i.document,d=a(l)&&a(l.createElement),f=function(e){return d?l.createElement(e):{}},h=!c&&!u(function(){return 7!=Object.defineProperty(f("div"),"a",{get:function(){return 7}}).a}),p=function(e,t){if(!a(e))return e;var r,i;if(t&&"function"==typeof(r=e.toString)&&!a(i=r.call(e)))return i;if("function"==typeof(r=e.valueOf)&&!a(i=r.call(e)))return i;if(!t&&"function"==typeof(r=e.toString)&&!a(i=r.call(e)))return i;throw TypeError("Can't convert object to primitive value")},m=Object.defineProperty,v={f:c?Object.defineProperty:function(e,t,r){if(s(e),t=p(t,!0),s(r),h)try{return m(e,t,r)}catch(e){}if("get"in r||"set"in r)throw TypeError("Accessors not supported!");return"value"in r&&(e[t]=r.value),e}},g=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},y=c?function(e,t,r){return v.f(e,t,g(1,r))}:function(e,t,r){return e[t]=r,e},_=function(e,t,r){var a,s,u,c=e&_.F,l=e&_.G,d=e&_.S,f=e&_.P,h=e&_.B,p=e&_.W,m=l?n:n[t]||(n[t]={}),v=m.prototype,g=l?i:d?i[t]:(i[t]||{}).prototype;for(a in l&&(r=t),r)(s=!c&&g&&void 0!==g[a])&&a in m||(u=s?g[a]:r[a],m[a]=l&&"function"!=typeof g[a]?r[a]:h&&s?o(u,i):p&&g[a]==u?function(e){var t=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,r)}return new e(t,r,i)}return e.apply(this,arguments)};return t.prototype=e.prototype,t}(u):f&&"function"==typeof u?o(Function.call,u):u,f&&((m.virtual||(m.virtual={}))[a]=u,e&_.R&&v&&!v[a]&&y(v,a,u)))};_.F=1,_.G=2,_.S=4,_.P=8,_.B=16,_.W=32,_.U=64,_.R=128;var b=_;b(b.S+b.F*!c,"Object",{defineProperty:v.f});var w,E=n.Object,S=function(e,t,r){return E.defineProperty(e,t,r)},T=t(function(e){e.exports={default:S,__esModule:!0}}),O=e(t(function(e,t){t.__esModule=!0;var r,i=(r=T)&&r.__esModule?r:{default:r};t.default=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),(0,i.default)(e,n.key,n)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}()})),A=Math.ceil,$=Math.floor,k=function(e){return isNaN(e=+e)?0:(e>0?$:A)(e)},D=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e},I=y,x={}.hasOwnProperty,C=function(e,t){return x.call(e,t)},M={}.toString,P=function(e){return M.call(e).slice(8,-1)},L=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==P(e)?e.split(""):Object(e)},R=function(e){return L(D(e))},N=Math.min,j=Math.max,F=Math.min,B=i["__core-js_shared__"]||(i["__core-js_shared__"]={}),U=function(e){return B[e]||(B[e]={})},z=0,G=Math.random(),W=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++z+G).toString(36))},H=U("keys"),V=function(e){return H[e]||(H[e]=W(e))},Y=(w=!1,function(e,t,r){var i,n,o=R(e),a=(i=o.length)>0?N(k(i),9007199254740991):0,s=function(e,t){return(e=k(e))<0?j(e+t,0):F(e,t)}(r,a);if(w&&t!=t){for(;a>s;)if((n=o[s++])!=n)return!0}else for(;a>s;s++)if((w||s in o)&&o[s]===t)return w||s||0;return!w&&-1}),K=V("IE_PROTO"),Z=function(e,t){var r,i=R(e),n=0,o=[];for(r in i)r!=K&&C(i,r)&&o.push(r);for(;t.length>n;)C(i,r=t[n++])&&(~Y(o,r)||o.push(r));return o},Q="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),X=Object.keys||function(e){return Z(e,Q)},q=c?Object.defineProperties:function(e,t){s(e);for(var r,i=X(t),n=i.length,o=0;n>o;)v.f(e,r=i[o++],t[r]);return e},J=i.document,ee=J&&J.documentElement,te=V("IE_PROTO"),re=function(){},ie=function(){var e,t=f("iframe"),r=Q.length;for(t.style.display="none",ee.appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),ie=e.F;r--;)delete ie.prototype[Q[r]];return ie()},ne=Object.create||function(e,t){var r;return null!==e?(re.prototype=s(e),r=new re,re.prototype=null,r[te]=e):r=ie(),void 0===t?r:q(r,t)},oe=t(function(e){var t=U("wks"),r=i.Symbol,n="function"==typeof r,o=e.exports=function(e){return t[e]||(t[e]=n&&r[e]||(n?r:W)("Symbol."+e))};o.store=t}),ae=v.f,se=oe("toStringTag"),ue=function(e,t,r){e&&!C(e=r?e:e.prototype,se)&&ae(e,se,{configurable:!0,value:t})},ce={};y(ce,oe("iterator"),function(){return this});var le,de=function(e,t,r){e.prototype=ne(ce,{next:g(1,r)}),ue(e,t+" Iterator")},fe=function(e){return Object(D(e))},he=V("IE_PROTO"),pe=Object.prototype,me=Object.getPrototypeOf||function(e){return e=fe(e),C(e,he)?e[he]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?pe:null},ve=oe("iterator"),ge=!([].keys&&"next"in[].keys()),ye=function(e,t,r,i,n,o,a){de(r,t,i);var s,u,c,l=function(e){if(!ge&&e in p)return p[e];switch(e){case"keys":case"values":return function(){return new r(this,e)}}return function(){return new r(this,e)}},d=t+" Iterator",f="values"==n,h=!1,p=e.prototype,m=p[ve]||p["@@iterator"]||n&&p[n],v=m||l(n),g=n?f?l("entries"):v:void 0,_="Array"==t&&p.entries||m;if(_&&(c=me(_.call(new e)))!==Object.prototype&&c.next&&ue(c,d,!0),f&&m&&"values"!==m.name&&(h=!0,v=function(){return m.call(this)}),a&&(ge||h||!p[ve])&&y(p,ve,v),n)if(s={values:f?v:l("values"),keys:o?v:l("keys"),entries:g},a)for(u in s)u in p||I(p,u,s[u]);else b(b.P+b.F*(ge||h),t,s);return s},_e=(le=!0,function(e,t){var r,i,n=String(D(e)),o=k(t),a=n.length;return o<0||o>=a?le?"":void 0:(r=n.charCodeAt(o))<55296||r>56319||o+1===a||(i=n.charCodeAt(o+1))<56320||i>57343?le?n.charAt(o):r:le?n.slice(o,o+2):i-56320+(r-55296<<10)+65536});ye(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,r=this._i;return r>=t.length?{value:void 0,done:!0}:(e=_e(t,r),this._i+=e.length,{value:e,done:!1})});for(var be=function(e,t){return{value:t,done:!!e}},we=(ye(Array,"Array",function(e,t){this._t=R(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,r=this._i++;return!e||r>=e.length?(this._t=void 0,be(1)):be(0,"keys"==t?r:"values"==t?e[r]:[r,e[r]])},"values"),oe("toStringTag")),Ee="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),Se=0;Se<Ee.length;Se++){var Te=Ee[Se],Oe=i[Te],Ae=Oe&&Oe.prototype;Ae&&!Ae[we]&&y(Ae,we,Te)}var $e={f:oe},ke=$e.f("iterator"),De=t(function(e){e.exports={default:ke,__esModule:!0}}),Ie=t(function(e){var t=W("meta"),r=v.f,i=0,n=Object.isExtensible||function(){return!0},o=!u(function(){return n(Object.preventExtensions({}))}),s=function(e){r(e,t,{value:{i:"O"+ ++i,w:{}}})},c=e.exports={KEY:t,NEED:!1,fastKey:function(e,r){if(!a(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!C(e,t)){if(!n(e))return"F";if(!r)return"E";s(e)}return e[t].i},getWeak:function(e,r){if(!C(e,t)){if(!n(e))return!0;if(!r)return!1;s(e)}return e[t].w},onFreeze:function(e){return o&&c.NEED&&n(e)&&!C(e,t)&&s(e),e}}}),xe=v.f,Ce=function(e){var t=n.Symbol||(n.Symbol={});"_"==e.charAt(0)||e in t||xe(t,e,{value:$e.f(e)})},Me={f:Object.getOwnPropertySymbols},Pe={f:{}.propertyIsEnumerable},Le=Array.isArray||function(e){return"Array"==P(e)},Re=Q.concat("length","prototype"),Ne={f:Object.getOwnPropertyNames||function(e){return Z(e,Re)}},je=Ne.f,Fe={}.toString,Be="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],Ue={f:function(e){return Be&&"[object Window]"==Fe.call(e)?function(e){try{return je(e)}catch(e){return Be.slice()}}(e):je(R(e))}},ze=Object.getOwnPropertyDescriptor,Ge={f:c?ze:function(e,t){if(e=R(e),t=p(t,!0),h)try{return ze(e,t)}catch(e){}if(C(e,t))return g(!Pe.f.call(e,t),e[t])}},We=Ie.KEY,He=Ge.f,Ve=v.f,Ye=Ue.f,Ke=i.Symbol,Ze=i.JSON,Qe=Ze&&Ze.stringify,Xe=oe("_hidden"),qe=oe("toPrimitive"),Je={}.propertyIsEnumerable,et=U("symbol-registry"),tt=U("symbols"),rt=U("op-symbols"),it=Object.prototype,nt="function"==typeof Ke,ot=i.QObject,at=!ot||!ot.prototype||!ot.prototype.findChild,st=c&&u(function(){return 7!=ne(Ve({},"a",{get:function(){return Ve(this,"a",{value:7}).a}})).a})?function(e,t,r){var i=He(it,t);i&&delete it[t],Ve(e,t,r),i&&e!==it&&Ve(it,t,i)}:Ve,ut=function(e){var t=tt[e]=ne(Ke.prototype);return t._k=e,t},ct=nt&&"symbol"==typeof Ke.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof Ke},lt=function(e,t,r){return e===it&<(rt,t,r),s(e),t=p(t,!0),s(r),C(tt,t)?(r.enumerable?(C(e,Xe)&&e[Xe][t]&&(e[Xe][t]=!1),r=ne(r,{enumerable:g(0,!1)})):(C(e,Xe)||Ve(e,Xe,g(1,{})),e[Xe][t]=!0),st(e,t,r)):Ve(e,t,r)},dt=function(e,t){s(e);for(var r,i=function(e){var t=X(e),r=Me.f;if(r)for(var i,n=r(e),o=Pe.f,a=0;n.length>a;)o.call(e,i=n[a++])&&t.push(i);return t}(t=R(t)),n=0,o=i.length;o>n;)lt(e,r=i[n++],t[r]);return e},ft=function(e){var t=Je.call(this,e=p(e,!0));return!(this===it&&C(tt,e)&&!C(rt,e))&&(!(t||!C(this,e)||!C(tt,e)||C(this,Xe)&&this[Xe][e])||t)},ht=function(e,t){if(e=R(e),t=p(t,!0),e!==it||!C(tt,t)||C(rt,t)){var r=He(e,t);return!r||!C(tt,t)||C(e,Xe)&&e[Xe][t]||(r.enumerable=!0),r}},pt=function(e){for(var t,r=Ye(R(e)),i=[],n=0;r.length>n;)C(tt,t=r[n++])||t==Xe||t==We||i.push(t);return i},mt=function(e){for(var t,r=e===it,i=Ye(r?rt:R(e)),n=[],o=0;i.length>o;)!C(tt,t=i[o++])||r&&!C(it,t)||n.push(tt[t]);return n};nt||(I((Ke=function(){if(this instanceof Ke)throw TypeError("Symbol is not a constructor!");var e=W(arguments.length>0?arguments[0]:void 0),t=function(r){this===it&&t.call(rt,r),C(this,Xe)&&C(this[Xe],e)&&(this[Xe][e]=!1),st(this,e,g(1,r))};return c&&at&&st(it,e,{configurable:!0,set:t}),ut(e)}).prototype,"toString",function(){return this._k}),Ge.f=ht,v.f=lt,Ne.f=Ue.f=pt,Pe.f=ft,Me.f=mt,$e.f=function(e){return ut(oe(e))}),b(b.G+b.W+b.F*!nt,{Symbol:Ke});for(var vt="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),gt=0;vt.length>gt;)oe(vt[gt++]);for(var yt=X(oe.store),_t=0;yt.length>_t;)Ce(yt[_t++]);b(b.S+b.F*!nt,"Symbol",{for:function(e){return C(et,e+="")?et[e]:et[e]=Ke(e)},keyFor:function(e){if(ct(e))return function(e,t){for(var r,i=R(e),n=X(i),o=n.length,a=0;o>a;)if(i[r=n[a++]]===t)return r}(et,e);throw TypeError(e+" is not a symbol!")},useSetter:function(){at=!0},useSimple:function(){at=!1}}),b(b.S+b.F*!nt,"Object",{create:function(e,t){return void 0===t?ne(e):dt(ne(e),t)},defineProperty:lt,defineProperties:dt,getOwnPropertyDescriptor:ht,getOwnPropertyNames:pt,getOwnPropertySymbols:mt}),Ze&&b(b.S+b.F*(!nt||u(function(){var e=Ke();return"[null]"!=Qe([e])||"{}"!=Qe({a:e})||"{}"!=Qe(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!ct(e)){for(var t,r,i=[e],n=1;arguments.length>n;)i.push(arguments[n++]);return"function"==typeof(t=i[1])&&(r=t),!r&&Le(t)||(t=function(e,t){if(r&&(t=r.call(this,e,t)),!ct(t))return t}),i[1]=t,Qe.apply(Ze,i)}}}),Ke.prototype[qe]||y(Ke.prototype,qe,Ke.prototype.valueOf),ue(Ke,"Symbol"),ue(Math,"Math",!0),ue(i.JSON,"JSON",!0),Ce("asyncIterator"),Ce("observable");var bt,wt,Et,St,Tt=n.Symbol,Ot=t(function(e){e.exports={default:Tt,__esModule:!0}}),At=e(t(function(e,t){t.__esModule=!0;var r=o(De),i=o(Ot),n="function"==typeof i.default&&"symbol"==typeof r.default?function(e){return typeof e}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":typeof e};function o(e){return e&&e.__esModule?e:{default:e}}t.default="function"==typeof i.default&&"symbol"===n(r.default)?function(e){return void 0===e?"undefined":n(e)}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":void 0===e?"undefined":n(e)}}));bt="keys",wt=function(){return function(e){return X(fe(e))}},Et=(n.Object||{})[bt]||Object[bt],(St={})[bt]=wt(Et),b(b.S+b.F*u(function(){Et(1)}),"Object",St);var $t=n.Object.keys,kt=(t(function(e){e.exports={default:$t,__esModule:!0}}),Math.floor);b(b.S,"Number",{isInteger:function(e){return!a(e)&&isFinite(e)&&kt(e)===e}});var Dt=n.Number.isInteger,It=(t(function(e){e.exports={default:Dt,__esModule:!0}}),"\t\n\v\f\r \u2028\u2029\ufeff"),xt="["+It+"]",Ct=RegExp("^"+xt+xt+"*"),Mt=RegExp(xt+xt+"*$"),Pt=function(e,t,r){var i={},n=u(function(){return!!It[e]()||"
"!="
"[e]()}),o=i[e]=n?t(Lt):It[e];r&&(i[r]=o),b(b.P+b.F*n,"String",i)},Lt=Pt.trim=function(e,t){return e=String(D(e)),1&t&&(e=e.replace(Ct,"")),2&t&&(e=e.replace(Mt,"")),e},Rt=Pt,Nt=i.parseFloat,jt=Rt.trim,Ft=1/Nt(It+"-0")!=-1/0?function(e){var t=jt(String(e),3),r=Nt(t);return 0===r&&"-"==t.charAt(0)?-0:r}:Nt;b(b.S+b.F*(Number.parseFloat!=Ft),"Number",{parseFloat:Ft});var Bt=parseFloat;function Ut(e){return"string"==typeof e||e instanceof String}function zt(e,t){if(!Ut(e))throw new TypeError("Log's method only acccept string as argument, but not "+e+" in "+(void 0===e?"undefined":At(e)));return Ut(t)?"["+(e=Gt.FORCE_GLOBAL_TAG?Gt.GLOBAL_TAG:e||Gt.GLOBAL_TAG)+"] > "+t:"["+Gt.GLOBAL_TAG+"] > "+e}t(function(e){e.exports={default:Bt,__esModule:!0}});var Gt=function(){function e(){r(this,e)}return O(e,null,[{key:"error",value:function(t,r){e.ENABLE_ERROR&&(console.error||console.warn||console.log)(zt(t,r))}},{key:"info",value:function(t,r){e.ENABLE_INFO&&(console.info||console.log)(zt(t,r))}},{key:"warn",value:function(t,r){e.ENABLE_WARN&&(console.warn||console.log)(zt(t,r))}},{key:"debug",value:function(t,r){e.ENABLE_DEBUG&&(console.debug||console.log)(zt(t,r))}},{key:"verbose",value:function(t,r){e.ENABLE_VERBOSE&&console.log(zt(t,r))}}]),e}();return Gt.GLOBAL_TAG="chimee",Gt.FORCE_GLOBAL_TAG=!1,Gt.ENABLE_ERROR=!0,Gt.ENABLE_INFO=!0,Gt.ENABLE_WARN=!0,Gt.ENABLE_DEBUG=!0,Gt.ENABLE_VERBOSE=!0,Gt}()},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),n=c(r(10)),o=c(r(12)),a=c(r(13)),s=c(r(14)),u=r(0);function c(e){return e&&e.__esModule?e:{default:e}}var l=function(e){function t(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var r=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return r.loader=null,r.config={},r.config=e||{},r.bufferSize=3145728,r.cacheBuffer=new ArrayBuffer(r.bufferSize),r.cacheRemain=0,r.stashByteStart=0,r.enableStash=!0,r.stashSize=r.config.stashSize||393216,r.resumeFrom=0,r.currentRange={},r.totalReceive=0,r.seekPonit=void 0,r.timer=null,r.heartBeatInterval=null,r.preTotalReceive=0,r.seekLock=!1,r.webSocketURLReg=/wss?:\/\/(.+?)/,r.selectLoader(),r.bindEvent(),r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,u.CustEvent),i(t,[{key:"selectLoader",value:function(){var e=this.config,t=this.config.src;this.webSocketURLReg.test(t)?this.loader=new a.default(t,e,this.queryHandle):n.default.isSupport()?this.loader=new n.default(t,e,this.queryHandle):s.default.isSupport()?this.loader=new s.default(t,e,this.queryHandle):o.default.isSupport()&&(this.loader=new o.default(t,e,this.queryHandle)),this.loader.arrivalDataCallback=this.onLoaderChunkArrival.bind(this)}},{key:"bindEvent",value:function(){var e=this;this.loader.on("end",function(){var t=e.cacheBuffer.slice(0,e.cacheRemain);e.arrivalDataCallback(t,e.stashByteStart),e.emit("end")}),this.loader.on("error",function(t){e.emit("error",t.data)})}},{key:"onLoaderChunkArrival",value:function(e,t,r){if((!this.seekLock||void 0!==r)&&(void 0!==r&&(this.seekPonit=r,this.seekLock=!1),this.arrivalDataCallback))if(this.totalReceive+=e.byteLength,0===this.cacheRemain&&0===this.stashByteStart&&(this.stashByteStart=t),this.cacheRemain+e.byteLength<=this.stashSize){new Uint8Array(this.cacheBuffer,0,this.stashSize).set(new Uint8Array(e),this.cacheRemain),this.cacheRemain+=e.byteLength}else{var i=new Uint8Array(this.cacheBuffer,0,this.bufferSize);if(this.cacheRemain>0){var n=this.cacheBuffer.slice(0,this.cacheRemain),o=0;if(void 0!==this.seekPonit?(o=this.arrivalDataCallback(n,this.stashByteStart,this.seekPonit),this.seekPonit=void 0):o=this.arrivalDataCallback(n,this.stashByteStart),o<n.byteLength){if(o>0){var a=new Uint8Array(n,o);i.set(a,0),this.cacheRemain=a.byteLength,this.stashByteStart+=o}}else this.cacheRemain=0,this.stashByteStart+=o;this.cacheRemain+e.byteLength>this.bufferSize&&(this.expandBuffer(this.cacheRemain+e.byteLength),i=new Uint8Array(this.cacheBuffer,0,this.bufferSize)),i.set(new Uint8Array(e),this.cacheRemain),this.cacheRemain+=e.byteLength}else{var s=0;if(void 0!==this.seekPonit?(s=this.arrivalDataCallback(e,t,this.seekPonit),this.seekPonit=void 0):s=this.arrivalDataCallback(e,t),s<e.byteLength){var u=e.byteLength-s;u>this.bufferSize&&(this.expandBuffer(u),i=new Uint8Array(this.cacheBuffer,0,this.bufferSize)),i.set(new Uint8Array(e,s),0),this.cacheRemain+=u,this.stashByteStart=t+s}}}}},{key:"initCacheBuffer",value:function(){this.cacheRemain=0,this.totalReceive=0,this.cacheBuffer=new ArrayBuffer(this.bufferSize)}},{key:"expandBuffer",value:function(e){var t=this.bufferSize;t<e&&(t=e),this.cacheBuffer=new ArrayBuffer(t),this.bufferSize=t}},{key:"pause",value:function(){this.loader.pause()}},{key:"open",value:function(e,t){this.loader.open({from:e||0,to:-1},t),this.heartbeat()}},{key:"heartbeat",value:function(){var e=this;window.clearInterval(this.heartBeatInterval),this.heartBeatInterval=setInterval(function(){e.emit("heartbeat",{speed:e.totalReceive-e.preTotalReceive,totalReceive:e.totalReceive}),e.preTotalReceive=e.totalReceive},1e3)}},{key:"resume",value:function(){this.paused=!1;var e=this.totalReceive;this.open(e)}},{key:"seek",value:function(e,t,r){this.seekLock=!0,this.totalReceive=e,this.preTotalReceive=e,this.initCacheBuffer(),this.cacheRemain=0,this.stashByteStart=0,this.open(e,r)}},{key:"destroy",value:function(){this.pause(),this.initCacheBuffer(),window.clearInterval(this.heartBeatInterval),this.heartBeatInterval=null}}]),t}();t.default=l},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t={},r=void 0;return r=-1!==e.to?"bytes="+e.from.toString()+"-"+e.to.toString():"bytes="+e.from.toString()+"-",t.Range=r,{headers:t}}},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i=r(0);r.n(i);function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function o(e,t){return e(t={exports:{}},t.exports),t.exports}var a=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e},s=function(e){return Object(a(e))},u={}.hasOwnProperty,c=function(e,t){return u.call(e,t)},l=o(function(e){var t=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=t)}),d=l["__core-js_shared__"]||(l["__core-js_shared__"]={}),f=function(e){return d[e]||(d[e]={})},h=0,p=Math.random(),m=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++h+p).toString(36))},g=f("keys"),y=function(e){return g[e]||(g[e]=m(e))},_=y("IE_PROTO"),b=Object.prototype,w=Object.getPrototypeOf||function(e){return e=s(e),c(e,_)?e[_]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?b:null},E=o(function(e){var t=e.exports={version:"2.5.1"};"number"==typeof __e&&(__e=t)}),S=function(e,t,r){if(function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!")}(e),void 0===t)return e;switch(r){case 1:return function(r){return e.call(t,r)};case 2:return function(r,i){return e.call(t,r,i)};case 3:return function(r,i,n){return e.call(t,r,i,n)}}return function(){return e.apply(t,arguments)}},T=function(e){return"object"==typeof e?null!==e:"function"==typeof e},O=function(e){if(!T(e))throw TypeError(e+" is not an object!");return e},A=function(e){try{return!!e()}catch(e){return!0}},$=!A(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),k=l.document,D=T(k)&&T(k.createElement),I=function(e){return D?k.createElement(e):{}},x=!$&&!A(function(){return 7!=Object.defineProperty(I("div"),"a",{get:function(){return 7}}).a}),C=function(e,t){if(!T(e))return e;var r,i;if(t&&"function"==typeof(r=e.toString)&&!T(i=r.call(e)))return i;if("function"==typeof(r=e.valueOf)&&!T(i=r.call(e)))return i;if(!t&&"function"==typeof(r=e.toString)&&!T(i=r.call(e)))return i;throw TypeError("Can't convert object to primitive value")},M=Object.defineProperty,P={f:$?Object.defineProperty:function(e,t,r){if(O(e),t=C(t,!0),O(r),x)try{return M(e,t,r)}catch(e){}if("get"in r||"set"in r)throw TypeError("Accessors not supported!");return"value"in r&&(e[t]=r.value),e}},L=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},R=$?function(e,t,r){return P.f(e,t,L(1,r))}:function(e,t,r){return e[t]=r,e},N=function(e,t,r){var i,n,o,a=e&N.F,s=e&N.G,u=e&N.S,c=e&N.P,d=e&N.B,f=e&N.W,h=s?E:E[t]||(E[t]={}),p=h.prototype,m=s?l:u?l[t]:(l[t]||{}).prototype;for(i in s&&(r=t),r)(n=!a&&m&&void 0!==m[i])&&i in h||(o=n?m[i]:r[i],h[i]=s&&"function"!=typeof m[i]?r[i]:d&&n?S(o,l):f&&m[i]==o?function(e){var t=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,r)}return new e(t,r,i)}return e.apply(this,arguments)};return t.prototype=e.prototype,t}(o):c&&"function"==typeof o?S(Function.call,o):o,c&&((h.virtual||(h.virtual={}))[i]=o,e&N.R&&p&&!p[i]&&R(p,i,o)))};N.F=1,N.G=2,N.S=4,N.P=8,N.B=16,N.W=32,N.U=64,N.R=128;var j,F,B,U,z=N;j="getPrototypeOf",F=function(){return function(e){return w(s(e))}},B=(E.Object||{})[j]||Object[j],(U={})[j]=F(B),z(z.S+z.F*A(function(){B(1)}),"Object",U);var G,W=E.Object.getPrototypeOf,H=n(o(function(e){e.exports={default:W,__esModule:!0}})),V=Math.ceil,Y=Math.floor,K=function(e){return isNaN(e=+e)?0:(e>0?Y:V)(e)},Z=R,Q={}.toString,X=function(e){return Q.call(e).slice(8,-1)},q=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==X(e)?e.split(""):Object(e)},J=function(e){return q(a(e))},ee=Math.min,te=Math.max,re=Math.min,ie=(G=!1,function(e,t,r){var i,n,o=J(e),a=(i=o.length)>0?ee(K(i),9007199254740991):0,s=function(e,t){return(e=K(e))<0?te(e+t,0):re(e,t)}(r,a);if(G&&t!=t){for(;a>s;)if((n=o[s++])!=n)return!0}else for(;a>s;s++)if((G||s in o)&&o[s]===t)return G||s||0;return!G&&-1}),ne=y("IE_PROTO"),oe=function(e,t){var r,i=J(e),n=0,o=[];for(r in i)r!=ne&&c(i,r)&&o.push(r);for(;t.length>n;)c(i,r=t[n++])&&(~ie(o,r)||o.push(r));return o},ae="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),se=Object.keys||function(e){return oe(e,ae)},ue=$?Object.defineProperties:function(e,t){O(e);for(var r,i=se(t),n=i.length,o=0;n>o;)P.f(e,r=i[o++],t[r]);return e},ce=l.document,le=ce&&ce.documentElement,de=y("IE_PROTO"),fe=function(){},he=function(){var e,t=I("iframe"),r=ae.length;for(t.style.display="none",le.appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),he=e.F;r--;)delete he.prototype[ae[r]];return he()},pe=Object.create||function(e,t){var r;return null!==e?(fe.prototype=O(e),r=new fe,fe.prototype=null,r[de]=e):r=he(),void 0===t?r:ue(r,t)},me=o(function(e){var t=f("wks"),r=l.Symbol,i="function"==typeof r;(e.exports=function(e){return t[e]||(t[e]=i&&r[e]||(i?r:m)("Symbol."+e))}).store=t}),ve=P.f,ge=me("toStringTag"),ye=function(e,t,r){e&&!c(e=r?e:e.prototype,ge)&&ve(e,ge,{configurable:!0,value:t})},_e={};R(_e,me("iterator"),function(){return this});var be,we=function(e,t,r){e.prototype=pe(_e,{next:L(1,r)}),ye(e,t+" Iterator")},Ee=me("iterator"),Se=!([].keys&&"next"in[].keys()),Te=function(e,t,r,i,n,o,a){we(r,t,i);var s,u,c,l=function(e){if(!Se&&e in p)return p[e];switch(e){case"keys":case"values":return function(){return new r(this,e)}}return function(){return new r(this,e)}},d=t+" Iterator",f="values"==n,h=!1,p=e.prototype,m=p[Ee]||p["@@iterator"]||n&&p[n],v=m||l(n),g=n?f?l("entries"):v:void 0,y="Array"==t&&p.entries||m;if(y&&(c=w(y.call(new e)))!==Object.prototype&&c.next&&ye(c,d,!0),f&&m&&"values"!==m.name&&(h=!0,v=function(){return m.call(this)}),a&&(Se||h||!p[Ee])&&R(p,Ee,v),n)if(s={values:f?v:l("values"),keys:o?v:l("keys"),entries:g},a)for(u in s)u in p||Z(p,u,s[u]);else z(z.P+z.F*(Se||h),t,s);return s},Oe=(be=!0,function(e,t){var r,i,n=String(a(e)),o=K(t),s=n.length;return o<0||o>=s?be?"":void 0:(r=n.charCodeAt(o))<55296||r>56319||o+1===s||(i=n.charCodeAt(o+1))<56320||i>57343?be?n.charAt(o):r:be?n.slice(o,o+2):i-56320+(r-55296<<10)+65536});Te(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,r=this._i;return r>=t.length?{value:void 0,done:!0}:(e=Oe(t,r),this._i+=e.length,{value:e,done:!1})});for(var Ae=function(e,t){return{value:t,done:!!e}},$e=(Te(Array,"Array",function(e,t){this._t=J(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,r=this._i++;return!e||r>=e.length?(this._t=void 0,Ae(1)):Ae(0,"keys"==t?r:"values"==t?e[r]:[r,e[r]])},"values"),me("toStringTag")),ke="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),De=0;De<ke.length;De++){var Ie=ke[De],xe=l[Ie],Ce=xe&&xe.prototype;Ce&&!Ce[$e]&&R(Ce,$e,Ie)}var Me={f:me},Pe=Me.f("iterator"),Le=o(function(e){e.exports={default:Pe,__esModule:!0}});n(Le);var Re=o(function(e){var t=m("meta"),r=P.f,i=0,n=Object.isExtensible||function(){return!0},o=!A(function(){return n(Object.preventExtensions({}))}),a=function(e){r(e,t,{value:{i:"O"+ ++i,w:{}}})},s=e.exports={KEY:t,NEED:!1,fastKey:function(e,r){if(!T(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!c(e,t)){if(!n(e))return"F";if(!r)return"E";a(e)}return e[t].i},getWeak:function(e,r){if(!c(e,t)){if(!n(e))return!0;if(!r)return!1;a(e)}return e[t].w},onFreeze:function(e){return o&&s.NEED&&n(e)&&!c(e,t)&&a(e),e}}}),Ne=P.f,je=function(e){var t=E.Symbol||(E.Symbol={});"_"==e.charAt(0)||e in t||Ne(t,e,{value:Me.f(e)})},Fe={f:Object.getOwnPropertySymbols},Be={f:{}.propertyIsEnumerable},Ue=Array.isArray||function(e){return"Array"==X(e)},ze=ae.concat("length","prototype"),Ge={f:Object.getOwnPropertyNames||function(e){return oe(e,ze)}},We=Ge.f,He={}.toString,Ve="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],Ye={f:function(e){return Ve&&"[object Window]"==He.call(e)?function(e){try{return We(e)}catch(e){return Ve.slice()}}(e):We(J(e))}},Ke=Object.getOwnPropertyDescriptor,Ze={f:$?Ke:function(e,t){if(e=J(e),t=C(t,!0),x)try{return Ke(e,t)}catch(e){}if(c(e,t))return L(!Be.f.call(e,t),e[t])}},Qe=Re.KEY,Xe=Ze.f,qe=P.f,Je=Ye.f,et=l.Symbol,tt=l.JSON,rt=tt&&tt.stringify,it=me("_hidden"),nt=me("toPrimitive"),ot={}.propertyIsEnumerable,at=f("symbol-registry"),st=f("symbols"),ut=f("op-symbols"),ct=Object.prototype,lt="function"==typeof et,dt=l.QObject,ft=!dt||!dt.prototype||!dt.prototype.findChild,ht=$&&A(function(){return 7!=pe(qe({},"a",{get:function(){return qe(this,"a",{value:7}).a}})).a})?function(e,t,r){var i=Xe(ct,t);i&&delete ct[t],qe(e,t,r),i&&e!==ct&&qe(ct,t,i)}:qe,pt=function(e){var t=st[e]=pe(et.prototype);return t._k=e,t},mt=lt&&"symbol"==typeof et.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof et},vt=function(e,t,r){return e===ct&&vt(ut,t,r),O(e),t=C(t,!0),O(r),c(st,t)?(r.enumerable?(c(e,it)&&e[it][t]&&(e[it][t]=!1),r=pe(r,{enumerable:L(0,!1)})):(c(e,it)||qe(e,it,L(1,{})),e[it][t]=!0),ht(e,t,r)):qe(e,t,r)},gt=function(e,t){O(e);for(var r,i=function(e){var t=se(e),r=Fe.f;if(r)for(var i,n=r(e),o=Be.f,a=0;n.length>a;)o.call(e,i=n[a++])&&t.push(i);return t}(t=J(t)),n=0,o=i.length;o>n;)vt(e,r=i[n++],t[r]);return e},yt=function(e){var t=ot.call(this,e=C(e,!0));return!(this===ct&&c(st,e)&&!c(ut,e))&&(!(t||!c(this,e)||!c(st,e)||c(this,it)&&this[it][e])||t)},_t=function(e,t){if(e=J(e),t=C(t,!0),e!==ct||!c(st,t)||c(ut,t)){var r=Xe(e,t);return!r||!c(st,t)||c(e,it)&&e[it][t]||(r.enumerable=!0),r}},bt=function(e){for(var t,r=Je(J(e)),i=[],n=0;r.length>n;)c(st,t=r[n++])||t==it||t==Qe||i.push(t);return i},wt=function(e){for(var t,r=e===ct,i=Je(r?ut:J(e)),n=[],o=0;i.length>o;)!c(st,t=i[o++])||r&&!c(ct,t)||n.push(st[t]);return n};lt||(Z((et=function(){if(this instanceof et)throw TypeError("Symbol is not a constructor!");var e=m(arguments.length>0?arguments[0]:void 0),t=function(r){this===ct&&t.call(ut,r),c(this,it)&&c(this[it],e)&&(this[it][e]=!1),ht(this,e,L(1,r))};return $&&ft&&ht(ct,e,{configurable:!0,set:t}),pt(e)}).prototype,"toString",function(){return this._k}),Ze.f=_t,P.f=vt,Ge.f=Ye.f=bt,Be.f=yt,Fe.f=wt,Me.f=function(e){return pt(me(e))}),z(z.G+z.W+z.F*!lt,{Symbol:et});for(var Et="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),St=0;Et.length>St;)me(Et[St++]);for(var Tt=se(me.store),Ot=0;Tt.length>Ot;)je(Tt[Ot++]);z(z.S+z.F*!lt,"Symbol",{for:function(e){return c(at,e+="")?at[e]:at[e]=et(e)},keyFor:function(e){if(!mt(e))throw TypeError(e+" is not a symbol!");for(var t in at)if(at[t]===e)return t},useSetter:function(){ft=!0},useSimple:function(){ft=!1}}),z(z.S+z.F*!lt,"Object",{create:function(e,t){return void 0===t?pe(e):gt(pe(e),t)},defineProperty:vt,defineProperties:gt,getOwnPropertyDescriptor:_t,getOwnPropertyNames:bt,getOwnPropertySymbols:wt}),tt&&z(z.S+z.F*(!lt||A(function(){var e=et();return"[null]"!=rt([e])||"{}"!=rt({a:e})||"{}"!=rt(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!mt(e)){for(var t,r,i=[e],n=1;arguments.length>n;)i.push(arguments[n++]);return"function"==typeof(t=i[1])&&(r=t),!r&&Ue(t)||(t=function(e,t){if(r&&(t=r.call(this,e,t)),!mt(t))return t}),i[1]=t,rt.apply(tt,i)}}}),et.prototype[nt]||R(et.prototype,nt,et.prototype.valueOf),ye(et,"Symbol"),ye(Math,"Math",!0),ye(l.JSON,"JSON",!0),je("asyncIterator"),je("observable");var At=E.Symbol,$t=o(function(e){e.exports={default:At,__esModule:!0}});n($t);var kt=o(function(e,t){t.__esModule=!0;var r=o(Le),i=o($t),n="function"==typeof i.default&&"symbol"==typeof r.default?function(e){return typeof e}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":typeof e};function o(e){return e&&e.__esModule?e:{default:e}}t.default="function"==typeof i.default&&"symbol"===n(r.default)?function(e){return void 0===e?"undefined":n(e)}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":void 0===e?"undefined":n(e)}}),Dt=n(kt),It=n(o(function(e,t){t.__esModule=!0;var r,i=(r=kt)&&r.__esModule?r:{default:r};t.default=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==(void 0===t?"undefined":(0,i.default)(t))&&"function"!=typeof t?e:t}})),xt=function(e,t){if(O(e),!T(t)&&null!==t)throw TypeError(t+": can't set as prototype!")},Ct={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,r){try{(r=S(Function.call,Ze.f(Object.prototype,"__proto__").set,2))(e,[]),t=!(e instanceof Array)}catch(e){t=!0}return function(e,i){return xt(e,i),t?e.__proto__=i:r(e,i),e}}({},!1):void 0),check:xt};z(z.S,"Object",{setPrototypeOf:Ct.set});var Mt=E.Object.setPrototypeOf,Pt=o(function(e){e.exports={default:Mt,__esModule:!0}});n(Pt),z(z.S,"Object",{create:pe});var Lt=E.Object,Rt=function(e,t){return Lt.create(e,t)},Nt=o(function(e){e.exports={default:Rt,__esModule:!0}});n(Nt);var jt=n(o(function(e,t){t.__esModule=!0;var r=o(Pt),i=o(Nt),n=o(kt);function o(e){return e&&e.__esModule?e:{default:e}}t.default=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":(0,n.default)(t)));e.prototype=(0,i.default)(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(r.default?(0,r.default)(e,t):e.__proto__=t)}})),Ft=Object.assign,Bt=!Ft||A(function(){var e={},t={},r=Symbol(),i="abcdefghijklmnopqrst";return e[r]=7,i.split("").forEach(function(e){t[e]=e}),7!=Ft({},e)[r]||Object.keys(Ft({},t)).join("")!=i})?function(e,t){for(var r=s(e),i=arguments.length,n=1,o=Fe.f,a=Be.f;i>n;)for(var u,c=q(arguments[n++]),l=o?se(c).concat(o(c)):se(c),d=l.length,f=0;d>f;)a.call(c,u=l[f++])&&(r[u]=c[u]);return r}:Ft;z(z.S+z.F,"Object",{assign:Bt});var Ut=E.Object.assign,zt=n(o(function(e){e.exports={default:Ut,__esModule:!0}})),Gt=n(o(function(e,t){t.__esModule=!0,t.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}}));z(z.S+z.F*!$,"Object",{defineProperty:P.f});var Wt=E.Object,Ht=function(e,t,r){return Wt.defineProperty(e,t,r)},Vt=o(function(e){e.exports={default:Ht,__esModule:!0}});n(Vt);var Yt=n(o(function(e,t){t.__esModule=!0;var r,i=(r=Vt)&&r.__esModule?r:{default:r};t.default=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),(0,i.default)(e,n.key,n)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}()})),Kt=function(){function e(){Gt(this,e),this.tagType=-1,this.dataSize=-1,this.Timestamp=-1,this.StreamID=-1,this.body=-1,this.time=-1,this.arr=[],this.size=-1}return Yt(e,[{key:"getTime",value:function(){this.arr=[];for(var e=0;e<this.Timestamp.length;e++)this.arr.push(1==this.Timestamp[e].toString(16).length?"0"+this.Timestamp[e].toString(16):this.Timestamp[e].toString(16));this.arr.pop();var t=this.arr.join("");return this.time=parseInt(t,16),parseInt(t,16)}}]),e}();function Zt(e){for(var t=[],r=e,i=0,n=e.length;i<n;)if(r[i]<128)t.push(String.fromCharCode(r[i])),++i;else{if(r[i]<192);else if(r[i]<224){if(Qt(r,i,1)){var o=(31&r[i])<<6|63&r[i+1];if(o>=128){t.push(String.fromCharCode(65535&o)),i+=2;continue}}}else if(r[i]<240){if(Qt(r,i,2)){var a=(15&r[i])<<12|(63&r[i+1])<<6|63&r[i+2];if(a>=2048&&55296!=(63488&a)){t.push(String.fromCharCode(65535&a)),i+=3;continue}}}else if(r[i]<248&&Qt(r,i,3)){var s=(7&r[i])<<18|(63&r[i+1])<<12|(63&r[i+2])<<6|63&r[i+3];if(s>65536&&s<1114112){s-=65536,t.push(String.fromCharCode(s>>>10|55296)),t.push(String.fromCharCode(1023&s|56320)),i+=4;continue}}t.push(String.fromCharCode(65533)),++i}return t.join("")}function Qt(e,t,r){var i=e;if(t+r<i.length){for(;r--;)if(128!=(192&i[++t]))return!1;return!0}return!1}var Xt=function(){function e(t){Gt(this,e),this.TAG=this.constructor.name,this._buffer=t,this._buffer_index=0,this._total_bytes=t.byteLength,this._total_bits=8*t.byteLength,this._current_word=0,this._current_word_bits_left=0}return Yt(e,[{key:"destroy",value:function(){this._buffer=null}},{key:"_fillCurrentWord",value:function(){var e=this._total_bytes-this._buffer_index;if(e<=0)throw new IllegalStateException("ExpGolomb: _fillCurrentWord() but no bytes available");var t=Math.min(4,e),r=new Uint8Array(4);r.set(this._buffer.subarray(this._buffer_index,this._buffer_index+t)),this._current_word=new DataView(r.buffer).getUint32(0,!1),this._buffer_index+=t,this._current_word_bits_left=8*t}},{key:"readBits",value:function(e){if(e>32)throw new InvalidArgumentException("ExpGolomb: readBits() bits exceeded max 32bits!");if(e<=this._current_word_bits_left){var t=this._current_word>>>32-e;return this._current_word<<=e,this._current_word_bits_left-=e,t}var r=this._current_word_bits_left?this._current_word:0;r>>>=32-this._current_word_bits_left;var i=e-this._current_word_bits_left;this._fillCurrentWord();var n=Math.min(i,this._current_word_bits_left),o=this._current_word>>>32-n;return this._current_word<<=n,this._current_word_bits_left-=n,r=r<<n|o}},{key:"readBool",value:function(){return 1===this.readBits(1)}},{key:"readByte",value:function(){return this.readBits(8)}},{key:"_skipLeadingZero",value:function(){var e=void 0;for(e=0;e<this._current_word_bits_left;e++)if(0!=(this._current_word&2147483648>>>e))return this._current_word<<=e,this._current_word_bits_left-=e,e;return this._fillCurrentWord(),e+this._skipLeadingZero()}},{key:"readUEG",value:function(){var e=this._skipLeadingZero();return this.readBits(e+1)-1}},{key:"readSEG",value:function(){var e=this.readUEG();return 1&e?e+1>>>1:-1*(e>>>1)}}]),e}(),qt=function(){function e(){Gt(this,e)}return Yt(e,null,[{key:"_ebsp2rbsp",value:function(e){for(var t=e,r=t.byteLength,i=new Uint8Array(r),n=0,o=0;o<r;o++)o>=2&&3===t[o]&&0===t[o-1]&&0===t[o-2]||(i[n]=t[o],n++);return new Uint8Array(i.buffer,0,n)}},{key:"parseSPS",value:function(t){var r=e._ebsp2rbsp(t),i=new Xt(r);i.readByte();var n=i.readByte();i.readByte();var o=i.readByte();i.readUEG();var a=e.getProfileString(n),s=e.getLevelString(o),u=1,c=420,l=8;if((100===n||110===n||122===n||244===n||44===n||83===n||86===n||118===n||128===n||138===n||144===n)&&(3===(u=i.readUEG())&&i.readBits(1),u<=3&&(c=[0,420,422,444][u]),l=i.readUEG()+8,i.readUEG(),i.readBits(1),i.readBool()))for(var d=3!==u?8:12,f=0;f<d;f++)i.readBool()&&(f<6?e._skipScalingList(i,16):e._skipScalingList(i,64));i.readUEG();var h=i.readUEG();if(0===h)i.readUEG();else if(1===h){i.readBits(1),i.readSEG(),i.readSEG();for(var p=i.readUEG(),m=0;m<p;m++)i.readSEG()}i.readUEG(),i.readBits(1);var v=i.readUEG(),g=i.readUEG(),y=i.readBits(1);0===y&&i.readBits(1),i.readBits(1);var _=0,b=0,w=0,E=0;i.readBool()&&(_=i.readUEG(),b=i.readUEG(),w=i.readUEG(),E=i.readUEG());var S=1,T=1,O=0,A=!0,$=0,k=0;if(i.readBool()){if(i.readBool()){var D=i.readByte();D>0&&D<16?(S=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][D-1],T=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][D-1]):255===D&&(S=i.readByte()<<8|i.readByte(),T=i.readByte()<<8|i.readByte())}if(i.readBool()&&i.readBool(),i.readBool()&&(i.readBits(4),i.readBool()&&i.readBits(24)),i.readBool()&&(i.readUEG(),i.readUEG()),i.readBool()){var I=i.readBits(32),x=i.readBits(32);A=i.readBool(),O=($=x)/(k=2*I)}}var C=1;1===S&&1===T||(C=S/T);var M=0,P=0;0===u?(M=1,P=2-y):(M=3===u?1:2,P=(1===u?2:1)*(2-y));var L=16*(v+1),R=16*(g+1)*(2-y);L-=(_+b)*M,R-=(w+E)*P;var N=Math.ceil(L*C);return i.destroy(),i=null,{profile_string:a,level_string:s,bit_depth:l,chroma_format:c,chroma_format_string:e.getChromaFormatString(c),frame_rate:{fixed:A,fps:O,fps_den:k,fps_num:$},sar_ratio:{width:S,height:T},codec_size:{width:L,height:R},present_size:{width:N,height:R}}}},{key:"_skipScalingList",value:function(e,t){for(var r=8,i=8,n=0;n<t;n++)0!==i&&(i=(r+e.readSEG()+256)%256),r=0===i?r:i}},{key:"getProfileString",value:function(e){switch(e){case 66:return"Baseline";case 77:return"Main";case 88:return"Extended";case 100:return"High";case 110:return"High10";case 122:return"High422";case 244:return"High444";default:return"Unknown"}}},{key:"getLevelString",value:function(e){return(e/10).toFixed(1)}},{key:"getChromaFormatString",value:function(e){switch(e){case 420:return"4:2:0";case 422:return"4:2:2";case 444:return"4:4:4";default:return"Unknown"}}}]),e}(),Jt=null,er=function(){function e(){Gt(this,e)}return Yt(e,null,[{key:"parseObject",value:function(t,r,i){var n=e.parseString(t,r,i),o=e.parseScript(t,r+n.size),a=o.objectEnd;return{data:{name:n.data,value:o.data},size:o.size,objectEnd:a}}},{key:"parseVariable",value:function(t,r,i){return e.parseObject(t,r,i)}},{key:"parseLongString",value:function(e,t,r){var i=new DataView(e,t).getUint32(0,!Jt);return{data:i>0?Zt(new Uint8Array(e,t+4,i)):"",size:4+i}}},{key:"parseDate",value:function(e,t,r){var i=new DataView(e,t),n=i.getFloat64(0,!Jt),o=i.getInt16(8,!Jt);return{data:new Date(n+=60*o*1e3),size:10}}},{key:"parseString",value:function(e,t,r){var i=new DataView(e,t).getUint16(0,!Jt);return{data:i>0?Zt(new Uint8Array(e,t+2,i)):"",size:2+i}}},{key:"parseMetadata",value:function(t){var r;r=new ArrayBuffer(2),new DataView(r).setInt16(0,256,!0),Jt=256===new Int16Array(r)[0];var i=e.parseScript(t,0),n=e.parseScript(t,i.size,t.length-i.size),o={};return o[i.data]=n.data,o}},{key:"parseScript",value:function(t,r,i){var n=r,o=new Uint8Array(t).buffer,a=new DataView(o,0,i),s=null,u=a.getUint8(n);switch(n+=1,u){case 0:s=a.getFloat64(n,!Jt),n+=8;break;case 1:s=!!a.getUint8(n),n+=1;break;case 2:var c=e.parseString(o,n);s=c.data,n+=c.size;break;case 3:s={};var l=0;for(9==(16777215&a.getUint32(i-4,!Jt))&&(l=3);n<i-4;){var d=e.parseObject(o,n,i-r-l);if(d.objectEnd)break;s[d.data.name]=d.data.value,n=d.size}if(n<=i-3)9===(16777215&v.getUint32(n-1,!Jt))&&(n+=3);break;case 8:for(s={},n+=4,a.getUint32(i-4,!Jt);n<i-8;){var f=e.parseVariable(o,n);if(f.objectEnd)break;s[f.data.name]=f.data.value,n=f.size}if(n<=i-3)9===(16777215&a.getUint32(n-1,!Jt))&&(n+=3);break;case 9:s=void 0,n=1;break;case 10:s=[];var h=a.getUint32(n,!Jt);n+=4;for(var p=0;p<h;p++){var m=e.parseScript(o,n);s.push(m.data),n=m.size}break;case 11:var g=e.parseDate(o,n+1,i-1);s=g.data,n+=g.size;break;case 12:var y=e.parseString(o,n+1,i-1);s=y.data,n+=y.size;break;default:n=i,console.log("AMF","Unsupported AMF value type "+u)}return{data:s,size:n}}}]),e}(),tr=function(){function e(){Gt(this,e),this.mimeType=null,this.duration=null,this.hasAudio=null,this.hasVideo=null,this.audioCodec=null,this.videoCodec=null,this.audioDataRate=null,this.videoDataRate=null,this.audioSampleRate=null,this.audioChannelCount=null,this.width=null,this.height=null,this.fps=null,this.profile=null,this.level=null,this.chromaFormat=null,this.sarNum=null,this.sarDen=null,this.metadata=null,this.segments=null,this.segmentCount=null,this.hasKeyframesIndex=null,this.keyframesIndex=null}return Yt(e,[{key:"isComplete",value:function(){var e=!1===this.hasAudio||!0===this.hasAudio&&null!=this.audioCodec&&null!=this.audioSampleRate&&null!=this.audioChannelCount,t=!1===this.hasVideo||!0===this.hasVideo&&null!=this.videoCodec&&null!=this.width&&null!=this.height&&null!=this.fps&&null!=this.profile&&null!=this.level&&null!=this.chromaFormat&&null!=this.sarNum&&null!=this.sarDen;return null!=this.mimeType&&null!=this.duration&&null!=this.metadata&&null!=this.hasKeyframesIndex&&e&&t}},{key:"isSeekable",value:function(){return!0===this.hasKeyframesIndex}}]),e}(),rr=function e(t){Gt(this,e),this.type=t},ir=function(){function e(){var t;Gt(this,e),this.TAG=this.constructor.name,this._config={},this._onError=null,this._onMediaInfo=null,this._onTrackMetadata=null,this._onDataAvailable=null,this._dataOffset=0,this._firstParse=!0,this._dispatch=!1,this._hasAudio=!1,this._hasVideo=!1,this._audioInitialMetadataDispatched=!1,this._videoInitialMetadataDispatched=!1,this._mediaInfo=new tr,this._mediaInfo.hasAudio=this._hasAudio,this._mediaInfo.hasVideo=this._hasVideo,this._metadata=null,this._audioMetadata=null,this._videoMetadata=null,this._naluLengthSize=4,this._timestampBase=0,this._timescale=1e3,this._duration=0,this._durationOverrided=!1,this._referenceFrameRate={fixed:!0,fps:23.976,fps_num:23976,fps_den:1e3},this._videoTrack={type:"video",id:1,sequenceNumber:0,addcoefficient:2,samples:[],length:0},this._audioTrack={type:"audio",id:2,sequenceNumber:0,addcoefficient:2,samples:[],length:0},this._littleEndian=(t=new ArrayBuffer(2),new DataView(t).setInt16(0,256,!0),256===new Int16Array(t)[0])}return Yt(e,[{key:"onMediaInfo",value:function(e){this._onMediaInfo=e}},{key:"parseMetadata",value:function(e){var t=er.parseMetadata(e);this._parseScriptData(t)}},{key:"_parseScriptData",value:function(e){var t=e;if(t.hasOwnProperty("onMetaData")){this._metadata=t;var r=this._metadata.onMetaData;if("boolean"==typeof r.hasAudio&&(this._hasAudio=r.hasAudio,this._mediaInfo.hasAudio=this._hasAudio),"boolean"==typeof r.hasVideo&&(this._hasVideo=r.hasVideo,this._mediaInfo.hasVideo=this._hasVideo),"number"==typeof r.audiodatarate&&(this._mediaInfo.audioDataRate=r.audiodatarate),"number"==typeof r.videodatarate&&(this._mediaInfo.videoDataRate=r.videodatarate),"number"==typeof r.width&&(this._mediaInfo.width=r.width),"number"==typeof r.height&&(this._mediaInfo.height=r.height),"number"==typeof r.duration){if(!this._durationOverrided){var i=Math.floor(r.duration*this._timescale);this._duration=i,this._mediaInfo.duration=i}}else this._mediaInfo.duration=0;if("number"==typeof r.framerate){var n=Math.floor(1e3*r.framerate);if(n>0){var o=n/1e3;this._referenceFrameRate.fixed=!0,this._referenceFrameRate.fps=o,this._referenceFrameRate.fps_num=n,this._referenceFrameRate.fps_den=1e3,this._mediaInfo.fps=o}}if("object"===Dt(r.keyframes)){this._mediaInfo.hasKeyframesIndex=!0;var a=r.keyframes;a.times=r.times,a.filepositions=r.filepositions,this._mediaInfo.keyframesIndex=this._parseKeyframesIndex(a),r.keyframes=null}else this._mediaInfo.hasKeyframesIndex=!1;return this._dispatch=!1,this._mediaInfo.metadata=r,console.log(this.TAG,"Parsed onMetaData"),this._mediaInfo}}},{key:"_parseKeyframesIndex",value:function(e){for(var t=[],r=[],i=1;i<e.times.length;i++){var n=this._timestampBase+Math.floor(1e3*e.times[i]);t.push(n),r.push(e.filepositions[i])}return{times:t,filepositions:r}}},{key:"moofTag",value:function(e){for(var t=0;t<e.length;t++)this._dispatch=!0,this.parseChunks(e[t]);this._isInitialMetadataDispatched()&&this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack)}},{key:"parseChunks",value:function(e){switch(e.tagType){case 8:this._parseAudioData(e.body.buffer,0,e.body.length,e.getTime());break;case 9:this._parseVideoData(e.body.buffer,0,e.body.length,e.getTime(),0);break;case 18:this.parseMetadata(e.body)}}},{key:"_parseVideoData",value:function(e,t,r,i,n){if(i==this._timestampBase&&0!=this._timestampBase)throw new rr(i,this._timestampBase,"夭寿啦这个视频不是从0开始");if(r<=1)console.log(this.TAG,"Flv: Invalid video packet, missing VideoData payload!");else{var o=new Uint8Array(e,t,r)[0],a=(240&o)>>>4,s=15&o;7===s?this._parseAVCVideoPacket(e,t+1,r-1,i,n,a):this._onError&&this._onError("Flv: Unsupported codec in video frame: "+s)}}},{key:"_parseAVCVideoPacket",value:function(e,t,r,i,n,o){if(r<4)console.log(this.TAG,"Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime");else{var a=this._littleEndian,s=new DataView(e,t,r),u=s.getUint8(0),c=16777215&s.getUint32(0,!a);if(0===u)this._parseAVCDecoderConfigurationRecord(e,t+4,r-4);else if(1===u)this._parseAVCVideoData(e,t+4,r-4,i,n,o,c);else if(2!==u)return void this._onError("Flv: Invalid video packet type "+u)}}},{key:"_parseAVCDecoderConfigurationRecord",value:function(e,t,r){if(r<7)console.log(this.TAG,"Flv: Invalid AVCDecoderConfigurationRecord, lack of data!");else{var i=this._videoMetadata,n=this._videoTrack,o=this._littleEndian,a=new DataView(e,t,r);i?void 0!==i.avcc&&console.log(this.TAG,"Found another AVCDecoderConfigurationRecord!"):((i=this._videoMetadata={}).type="video",i.id=n.id,i.timescale=this._timescale,i.duration=this._duration);var s=a.getUint8(0),u=a.getUint8(1);a.getUint8(2),a.getUint8(3);if(1===s&&0!==u)if(this._naluLengthSize=1+(3&a.getUint8(4)),3===this._naluLengthSize||4===this._naluLengthSize){var c=31&a.getUint8(5);if(0===c||c>1)this._onError(DemuxErrors.FORMAT_ERROR,"Flv: Invalid H264 SPS count: "+c);else{for(var l=6,d=0;d<c;d++){var f=a.getUint16(l,!o);if(l+=2,0!==f){var h=new Uint8Array(e,t+l,f);l+=f;var p=qt.parseSPS(h);i.codecWidth=p.codec_size.width,i.codecHeight=p.codec_size.height,i.presentWidth=p.present_size.width,i.presentHeight=p.present_size.height,i.config=p,i.profile=p.profile_string,i.level=p.level_string,i.bitDepth=p.bit_depth,i.chromaFormat=p.chroma_format,i.sarRatio=p.sar_ratio,i.frameRate=p.frame_rate,!1!==p.frame_rate.fixed&&0!==p.frame_rate.fps_num&&0!==p.frame_rate.fps_den||(i.frameRate=this._referenceFrameRate);var m=i.frameRate.fps_den,v=i.frameRate.fps_num;i.refSampleDuration=Math.floor(i.timescale*(m/v));for(var g=h.subarray(1,4),y="avc1.",_=0;_<3;_++){var b=g[_].toString(16);b.length<2&&(b="0"+b),y+=b}i.codec=y;var w=this._mediaInfo;w.width=i.codecWidth,w.height=i.codecHeight,w.fps=i.frameRate.fps,w.profile=i.profile,w.level=i.level,w.chromaFormat=p.chroma_format_string,w.sarNum=i.sarRatio.width,w.sarDen=i.sarRatio.height,w.videoCodec=y,w.meta=i,w.hasAudio?null!=w.audioCodec&&(w.mimeType='video/x-flv; codecs="'+w.videoCodec+","+w.audioCodec+'"'):w.mimeType='video/x-flv; codecs="'+w.videoCodec+'"',w.isComplete()&&this._onMediaInfo(w)}}var E=a.getUint8(l);if(0===E||E>1)this._onError(DemuxErrors.FORMAT_ERROR,"Flv: Invalid H264 PPS count: "+E);else{l++;for(var S=0;S<E;S++){var T=a.getUint16(l,!o);l+=2,0!==T&&(l+=T)}i.avcc=new Uint8Array(r),i.avcc.set(new Uint8Array(e,t,r),0),console.log(this.TAG,"Parsed AVCDecoderConfigurationRecord"),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._videoInitialMetadataDispatched=!0,this._dispatch=!1,this._onTrackMetadata("video",i)}}}else this._onError(DemuxErrors.FORMAT_ERROR,"Flv: Strange NaluLengthSizeMinusOne: "+(this._naluLengthSize-1));else this._onError(DemuxErrors.FORMAT_ERROR,"Flv: Invalid AVCDecoderConfigurationRecord")}}},{key:"timestampBase",value:function(e){this._timestampBase=e}},{key:"_parseAVCVideoData",value:function(e,t,r,i,n,o,a){for(var s=this._littleEndian,u=new DataView(e,t,r),c=[],l=0,d=0,f=this._naluLengthSize,h=this._timestampBase+i,p=1===o;d<r;){if(d+4>=r){console.log(this.TAG,"Malformed Nalu near timestamp "+h+", offset = "+d+", dataSize = "+r);break}var m=u.getUint32(d,!s);if(3===f&&(m>>>=8),m>r-f)return void console.log(this.TAG,"Malformed Nalus near timestamp "+h+", NaluSize > DataSize!");var v=31&u.getUint8(d+f);5===v&&(p=!0);var g=new Uint8Array(e,t+d,f+m),y={type:v,data:g};c.push(y),l+=g.byteLength,d+=f+m}if(c.length){var _=this._videoTrack,b={units:c,length:l,isKeyframe:p,dts:h,cts:a,pts:h+a};p&&(b.fileposition=n),_.samples.push(b),_.length+=l}}},{key:"_parseAudioData",value:function(e,t,r,i){if(i==this._timestampBase&&0!=this._timestampBase&&console.log(i,this._timestampBase,"夭寿啦这个视频不是从0开始"),r<=1)console.log(this.TAG,"Flv: Invalid audio packet, missing SoundData payload!");else{var n=this._audioMetadata,o=this._audioTrack;if(!n||!n.codec){(n=this._audioMetadata={}).type="audio",n.id=o.id,n.timescale=this._timescale,n.duration=this._duration;var a=new DataView(e,t,r).getUint8(0),s=a>>>4;if(10!==s)return void this._onError(DemuxErrors.CODEC_UNSUPPORTED,"Flv: Unsupported audio codec idx: "+s);var u=0,c=(12&a)>>>2,l=[5500,11025,22050,44100,48e3];if(!(c<l.length))return void this._onError(DemuxErrors.FORMAT_ERROR,"Flv: Invalid audio sample rate idx: "+c);u=l[c];var d=1&a;n.audioSampleRate=u,n.channelCount=0===d?1:2,n.refSampleDuration=Math.floor(1024/n.audioSampleRate*n.timescale),n.codec="mp4a.40.5"}var f=this._parseAACAudioData(e,t+1,r-1);if(void 0!=f){if(0===f.packetType){n.config&&console.log(this.TAG,"Found another AudioSpecificConfig!");var h=f.data;n.audioSampleRate=h.samplingRate,n.channelCount=h.channelCount,n.codec=h.codec,n.config=h.config,n.refSampleDuration=Math.floor(1024/n.audioSampleRate*n.timescale),console.log(this.TAG,"Parsed AudioSpecificConfig"),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._audioInitialMetadataDispatched=!0,this._dispatch=!1;var p=this._mediaInfo;return p.audioCodec="mp4a.40."+h.originalAudioObjectType,p.audioSampleRate=n.audioSampleRate,p.audioChannelCount=n.channelCount,p.hasVideo?null!=p.videoCodec&&(p.mimeType='video/x-flv; codecs="'+p.videoCodec+","+p.audioCodec+'"'):p.mimeType='video/x-flv; codecs="'+p.audioCodec+'"',this._onTrackMetadata("audio",n),void(p.isComplete()&&this._onMediaInfo(p))}if(1===f.packetType){var m=this._timestampBase+i,v={unit:f.data,dts:m,pts:m};o.samples.push(v),o.length+=f.data.length}else console.log(this.TAG,"Flv: Unsupported AAC data type "+f.packetType)}}}},{key:"_parseAACAudioData",value:function(e,t,r){if(!(r<=1)){var i={},n=new Uint8Array(e,t,r);return i.packetType=n[0],0===n[0]?i.data=this._parseAACAudioSpecificConfig(e,t+1,r-1):i.data=n.subarray(1),i}console.log(this.TAG,"Flv: Invalid AAC packet, missing AACPacketType or/and Data!")}},{key:"_parseAACAudioSpecificConfig",value:function(e,t,r){var i,n,o=new Uint8Array(e,t,r),a=null,s=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],u=0,c=null;if(u=i=o[0]>>>3,(n=(7&o[0])<<1|o[1]>>>7)<0||n>=s.length)this._onError(DemuxErrors.FORMAT_ERROR,"Flv: AAC invalid sampling frequency index!");else{var l=s[n],d=(120&o[1])>>>3;if(!(d<0||d>=8)){5===u&&(c=(7&o[1])<<1|o[2]>>>7);var f=self.navigator.userAgent.toLowerCase();return-1!==f.indexOf("firefox")?n>=6?(u=5,a=new Array(4),c=n-3):(u=2,a=new Array(2),c=n):-1!==f.indexOf("android")?(u=2,a=new Array(2),c=n):(u=5,c=n,a=new Array(4),n>=6?c=n-3:1===d&&(u=2,a=new Array(2),c=n)),a[0]=u<<3,a[0]|=(15&n)>>>1,a[1]=(15&n)<<7,a[1]|=(15&d)<<3,5===u&&(a[1]|=(15&c)>>>1,a[2]=(1&c)<<7,a[2]|=8,a[3]=0),{config:a,samplingRate:l,channelCount:d,codec:"mp4a.40."+u,originalAudioObjectType:i}}this._onError(DemuxErrors.FORMAT_ERROR,"Flv: AAC invalid channel configuration")}}},{key:"_isInitialMetadataDispatched",value:function(){return this._hasAudio&&this._hasVideo?this._audioInitialMetadataDispatched&&this._videoInitialMetadataDispatched:this._hasAudio&&!this._hasVideo?this._audioInitialMetadataDispatched:!this._hasAudio&&this._hasVideo?this._videoInitialMetadataDispatched:void 0}},{key:"hasAudio",set:function(e){this._mediaInfo.hasAudio=this._hasAudio=e}},{key:"hasVideo",set:function(e){this._mediaInfo.hasVideo=this._hasVideo=e}}]),e}(),nr=function(){function e(){Gt(this,e),this.tempUint8=new Uint8Array,this.arrTag=[],this.index=0,this.tempArr=[],this.stop=!1,this.offset=0,this.frist=!0,this._hasAudio=!1,this._hasVideo=!1,this._dispose=!1,this.busy=!1,this.busyArr=[]}return Yt(e,[{key:"setFlv",value:function(e){return this.busy=!0,this._dispose=!1,this.stop=!1,this.arrTag=[],this.index=0,this.tempUint8=e,this.tempUint8.length>13&&70==this.tempUint8[0]&&76==this.tempUint8[1]&&86==this.tempUint8[2]?(this.probe(this.tempUint8.buffer),this.read(9),this.read(4),this.parse(),this.frist=!1,this.busy=!1,this.offset):this.frist?this.offset:(this.parse(),this.offset)}},{key:"probe",value:function(e){var t=new Uint8Array(e),r={match:!1};if(70!==t[0]||76!==t[1]||86!==t[2]||1!==t[3])return r;var i=(4&t[4])>>>2!=0,n=0!=(1&t[4]);return i||n?(this._hasAudio=ir._hasAudio=i,this._hasVideo=ir._hasVideo=n,{match:!0,hasAudioTrack:i,hasVideoTrack:n}):r}},{key:"dispose",value:function(){}},{key:"parse",value:function(){for(;this.index<this.tempUint8.length&&!this.stop;){this.offset=this.index;var e=new Kt;if(this.tempUint8.length-this.index>=11){if(e.tagType=this.read(1)[0],e.dataSize=this.read(3),e.Timestamp=this.read(4),e.StreamID=this.read(3),18!=e.tagType&&8!=e.tagType&&9!=e.tagType)throw new rr("wrong tagType"+e.tagType);this.tempUint8.length-this.index>=this.getBodySum(e.dataSize)+4?(e.body=this.read(this.getBodySum(e.dataSize)),9==e.tagType&&this._hasVideo&&this.arrTag.push(e),8==e.tagType&&this._hasAudio&&this.arrTag.push(e),18==e.tagType&&0==this.arrTag.length&&this.arrTag.push(e),e.size=this.read(4),this.offset=this.index):this.stop=!0}else this.stop=!0}return this.offset}},{key:"read",value:function(e){var t=this.tempUint8.slice(this.index,this.index+e);return this.index+=e,t}},{key:"getBodySum",value:function(e){var t="";return t+=1==e[0].toString(16).length?"0"+e[0].toString(16):e[0].toString(16),t+=1==e[1].toString(16).length?"0"+e[1].toString(16):e[1].toString(16),t+=1==e[2].toString(16).length?"0"+e[2].toString(16):e[2].toString(16),parseInt(t,16)}}]),e}(),or=function(){function e(){Gt(this,e)}return Yt(e,null,[{key:"init",value:function(){for(var t in e.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],mvex:[],mvhd:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);var r=e.constants={};r.FTYP=new Uint8Array([105,115,111,109,0,0,0,1,105,115,111,109,97,118,99,49]),r.STSD_PREFIX=new Uint8Array([0,0,0,0,0,0,0,1]),r.STTS=new Uint8Array([0,0,0,0,0,0,0,0]),r.STSC=r.STCO=r.STTS,r.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),r.HDLR_VIDEO=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r.HDLR_AUDIO=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]),r.DREF=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),r.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])}},{key:"box",value:function(e){for(var t=8,r=null,i=Array.prototype.slice.call(arguments,1),n=i.length,o=0;o<n;o++)t+=i[o].byteLength;(r=new Uint8Array(t))[0]=t>>>24&255,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r.set(e,4);for(var a=8,s=0;s<n;s++)r.set(i[s],a),a+=i[s].byteLength;return r}},{key:"generateInitSegment",value:function(t){t.constructor!=Array&&(t=[t]);var r=e.box(e.types.ftyp,e.constants.FTYP),i=e.moov(t),n=new Uint8Array(r.byteLength+i.byteLength);return n.set(r,0),n.set(i,r.byteLength),n}},{key:"moov",value:function(t){var r=e.mvhd(t[0].timescale,t[0].duration),i=e.trak(t[0]),n=void 0;t.length>1&&(n=e.trak(t[1]));var o=e.mvex(t);return t.length>1?e.box(e.types.moov,r,i,n,o):e.box(e.types.moov,r,i,o)}},{key:"mvhd",value:function(t,r){return e.box(e.types.mvhd,new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,t>>>24&255,t>>>16&255,t>>>8&255,255&t,r>>>24&255,r>>>16&255,r>>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]))}},{key:"trak",value:function(t){return e.box(e.types.trak,e.tkhd(t),e.mdia(t))}},{key:"tkhd",value:function(t){var r=t.id,i=t.duration,n=t.presentWidth,o=t.presentHeight;return e.box(e.types.tkhd,new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,0,0,0,0,i>>>24&255,i>>>16&255,i>>>8&255,255&i,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>>8&255,255&n,0,0,o>>>8&255,255&o,0,0]))}},{key:"mdia",value:function(t){return e.box(e.types.mdia,e.mdhd(t),e.hdlr(t),e.minf(t))}},{key:"mdhd",value:function(t){var r=t.timescale,i=t.duration;return e.box(e.types.mdhd,new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,i>>>24&255,i>>>16&255,i>>>8&255,255&i,85,196,0,0]))}},{key:"hdlr",value:function(t){var r=null;return r="audio"===t.type?e.constants.HDLR_AUDIO:e.constants.HDLR_VIDEO,e.box(e.types.hdlr,r)}},{key:"minf",value:function(t){var r=null;return r="audio"===t.type?e.box(e.types.smhd,e.constants.SMHD):e.box(e.types.vmhd,e.constants.VMHD),e.box(e.types.minf,r,e.dinf(),e.stbl(t))}},{key:"dinf",value:function(){return e.box(e.types.dinf,e.box(e.types.dref,e.constants.DREF))}},{key:"stbl",value:function(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.constants.STTS),e.box(e.types.stsc,e.constants.STSC),e.box(e.types.stsz,e.constants.STSZ),e.box(e.types.stco,e.constants.STCO))}},{key:"stsd",value:function(t){return"audio"===t.type?e.box(e.types.stsd,e.constants.STSD_PREFIX,e.mp4a(t)):e.box(e.types.stsd,e.constants.STSD_PREFIX,e.avc1(t))}},{key:"mp4a",value:function(t){var r=t.channelCount,i=t.audioSampleRate,n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,r,0,16,0,0,0,0,i>>>8&255,255&i,0,0]);return e.box(e.types.mp4a,n,e.esds(t))}},{key:"esds",value:function(t){var r=t.config,i=r.length,n=new Uint8Array([0,0,0,0,3,23+i,0,1,0,4,15+i,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([i]).concat(r).concat([6,1,2]));return e.box(e.types.esds,n)}},{key:"avc1",value:function(t){var r=t.avcc,i=t.codecWidth,n=t.codecHeight,o=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,i>>>8&255,255&i,n>>>8&255,255&n,0,72,0,0,0,72,0,0,0,0,0,0,0,1,4,103,49,49,49,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,255,255]);return e.box(e.types.avc1,o,e.box(e.types.avcC,r))}},{key:"mvex",value:function(t){return t.length>1?e.box(e.types.mvex,e.trex(t[0]),e.trex(t[1])):e.box(e.types.mvex,e.trex(t[0]))}},{key:"trex",value:function(t){var r=t.id,i=new Uint8Array([0,0,0,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return e.box(e.types.trex,i)}},{key:"moof",value:function(t,r){return e.box(e.types.moof,e.mfhd(t.sequenceNumber),e.traf(t,r))}},{key:"mfhd",value:function(t){var r=new Uint8Array([0,0,0,0,t>>>24&255,t>>>16&255,t>>>8&255,255&t]);return e.box(e.types.mfhd,r)}},{key:"traf",value:function(t,r){var i=t.id,n=e.box(e.types.tfhd,new Uint8Array([0,0,0,0,i>>>24&255,i>>>16&255,i>>>8&255,255&i])),o=e.box(e.types.tfdt,new Uint8Array([0,0,0,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r])),a=e.sdtp(t),s=e.trun(t,a.byteLength+16+16+8+16+8+8);return e.box(e.types.traf,n,o,s,a)}},{key:"sdtp",value:function(t){for(var r=t.samples||[],i=r.length,n=new Uint8Array(4+i),o=0;o<i;o++){var a=r[o].flags;n[o+4]=a.isLeading<<6|a.dependsOn<<4|a.isDependedOn<<2|a.hasRedundancy}return e.box(e.types.sdtp,n)}},{key:"trun",value:function(t,r){var i=t.samples||[],n=i.length,o=12+16*n,a=new Uint8Array(o);r+=8+o,a.set([0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,255&n,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0);for(var s=0;s<n;s++){var u=i[s].duration,c=i[s].size,l=i[s].flags,d=i[s].cts;a.set([u>>>24&255,u>>>16&255,u>>>8&255,255&u,c>>>24&255,c>>>16&255,c>>>8&255,255&c,l.isLeading<<2|l.dependsOn,l.isDependedOn<<6|l.hasRedundancy<<4|l.isNonSync,0,0,d>>>24&255,d>>>16&255,d>>>8&255,255&d],12+16*s)}return e.box(e.types.trun,a)}},{key:"mdat",value:function(t){return e.box(e.types.mdat,t)}}]),e}(),ar=function(){function e(){Gt(this,e)}return Yt(e,null,[{key:"getSilentFrame",value:function(e){return 1===e?new Uint8Array([0,200,0,128,35,128]):2===e?new Uint8Array([33,0,73,144,2,25,0,35,128]):3===e?new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]):4===e?new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]):5===e?new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]):6===e?new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]):null}}]),e}(),sr={};!function(){var e=self.navigator.userAgent.toLowerCase(),t=/(edge)\/([\w.]+)/.exec(e)||/(opr)[\/]([\w.]+)/.exec(e)||/(chrome)[ \/]([\w.]+)/.exec(e)||/(iemobile)[\/]([\w.]+)/.exec(e)||/(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("trident")>=0&&/(rv)(?::| )([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[],r=/(ipad)/.exec(e)||/(ipod)/.exec(e)||/(windows phone)/.exec(e)||/(iphone)/.exec(e)||/(kindle)/.exec(e)||/(android)/.exec(e)||/(windows)/.exec(e)||/(mac)/.exec(e)||/(linux)/.exec(e)||/(cros)/.exec(e)||[],i={browser:t[5]||t[3]||t[1]||"",version:t[2]||t[4]||"0",majorVersion:t[4]||t[2]||"0",platform:r[0]||""},n={};if(i.browser){n[i.browser]=!0;var o=i.majorVersion.split(".");n.version={major:parseInt(i.majorVersion,10),string:i.version},o.length>1&&(n.version.minor=parseInt(o[1],10)),o.length>2&&(n.version.build=parseInt(o[2],10))}i.platform&&(n[i.platform]=!0),(n.chrome||n.opr||n.safari)&&(n.webkit=!0),(n.rv||n.iemobile)&&(n.rv&&delete n.rv,i.browser="msie",n.msie=!0);n.edge&&(delete n.edge,i.browser="msedge",n.msedge=!0);n.opr&&(i.browser="opera",n.opera=!0);n.safari&&n.android&&(i.browser="android",n.android=!0);for(var a in n.name=i.browser,n.platform=i.platform,sr)sr.hasOwnProperty(a)&&delete sr[a];sr=n}();var ur=sr,cr=function e(t,r,i,n,o){Gt(this,e),this.dts=t,this.pts=r,this.duration=i,this.originalDts=n,this.isSyncPoint=o,this.fileposition=null},lr=function(){function e(){Gt(this,e),this.beginDts=0,this.endDts=0,this.beginPts=0,this.endPts=0,this.originalBeginDts=0,this.originalEndDts=0,this.syncPoints=[],this.firstSample=null,this.lastSample=null}return Yt(e,[{key:"appendSyncPoint",value:function(e){e.isSyncPoint=!0,this.syncPoints.push(e)}}]),e}(),dr=(function(){function e(){Gt(this,e),this._list=[]}Yt(e,[{key:"clear",value:function(){this._list=[]}},{key:"appendArray",value:function(e){var t=this._list;0!==e.length&&(t.length>0&&e[0].originalDts<t[t.length-1].originalDts&&this.clear(),Array.prototype.push.apply(t,e))}},{key:"getLastSyncPointBeforeDts",value:function(e){if(0==this._list.length)return null;var t=this._list,r=0,i=t.length-1,n=0,o=0,a=i;for(e<t[0].dts&&(r=0,o=a+1);o<=a;){if((n=o+Math.floor((a-o)/2))===i||e>=t[n].dts&&e<t[n+1].dts){r=n;break}t[n].dts<e?o=n+1:a=n-1}return this._list[r]}}])}(),function(){function e(t){Gt(this,e),this._type=t,this._list=[],this._lastAppendLocation=-1}return Yt(e,[{key:"isEmpty",value:function(){return 0===this._list.length}},{key:"clear",value:function(){this._list=[],this._lastAppendLocation=-1}},{key:"_searchNearestSegmentBefore",value:function(e){var t=this._list;if(0===t.length)return-2;var r=t.length-1,i=0,n=0,o=r,a=0;if(e<t[0].originalBeginDts)return a=-1;for(;n<=o;){if((i=n+Math.floor((o-n)/2))===r||e>t[i].lastSample.originalDts&&e<t[i+1].originalBeginDts){a=i;break}t[i].originalBeginDts<e?n=i+1:o=i-1}return a}},{key:"_searchNearestSegmentAfter",value:function(e){return this._searchNearestSegmentBefore(e)+1}},{key:"append",value:function(e){var t=this._list,r=e,i=this._lastAppendLocation,n=0;-1!==i&&i<t.length&&r.originalBeginDts>=t[i].lastSample.originalDts&&(i===t.length-1||i<t.length-1&&r.originalBeginDts<t[i+1].originalBeginDts)?n=i+1:t.length>0&&(n=this._searchNearestSegmentBefore(r.originalBeginDts)+1),this._lastAppendLocation=n,this._list.splice(n,0,r)}},{key:"getLastSegmentBefore",value:function(e){var t=this._searchNearestSegmentBefore(e);return t>=0?this._list[t]:null}},{key:"getLastSampleBefore",value:function(e){var t=this.getLastSegmentBefore(e);return null!=t?t.lastSample:null}},{key:"getLastSyncPointBefore",value:function(e){for(var t=this._searchNearestSegmentBefore(e),r=this._list[t].syncPoints;0===r.length&&t>0;)t--,r=this._list[t].syncPoints;return r.length>0?r[r.length-1]:null}},{key:"type",get:function(){return this._type}},{key:"length",get:function(){return this._list.length}}]),e}()),fr=function(){function e(t){Gt(this,e),this.TAG="MP4Remuxer",this._config=t,this._isLive=!0===t.isLive,this._dtsBase=-1,this._dtsBaseInited=!1,this._audioDtsBase=1/0,this._videoDtsBase=1/0,this._audioNextDts=void 0,this._videoNextDts=void 0,this._audioMeta=null,this._videoMeta=null,this._audioSegmentInfoList=new dr("audio"),this._videoSegmentInfoList=new dr("video"),this._onInitSegment=null,this._onMediaSegment=null,this._forceFirstIDR=!(!ur.chrome||!(ur.version.major<50||50===ur.version.major&&ur.version.build<2661)),this._fillSilentAfterSeek=ur.msedge||ur.msie,this._mp3UseMpegAudio=!ur.firefox}return Yt(e,[{key:"destroy",value:function(){this._dtsBase=-1,this._dtsBaseInited=!1,this._audioMeta=null,this._videoMeta=null,this._audioSegmentInfoList.clear(),this._audioSegmentInfoList=null,this._videoSegmentInfoList.clear(),this._videoSegmentInfoList=null,this._onInitSegment=null,this._onMediaSegment=null}},{key:"bindDataSource",value:function(e){return e.onDataAvailable=this.remux.bind(this),e.onTrackMetadata=this._onTrackMetadataReceived.bind(this),this}},{key:"insertDiscontinuity",value:function(){this._audioNextDts=this._videoNextDts=void 0}},{key:"seek",value:function(e){this._videoSegmentInfoList.clear(),this._audioSegmentInfoList.clear()}},{key:"remux",value:function(e,t){if(!this._onMediaSegment)throw new IllegalStateException("MP4Remuxer: onMediaSegment callback must be specificed!");this._dtsBaseInited||this._calculateDtsBase(e,t),this._remuxVideo(t),this._remuxAudio(e)}},{key:"_onTrackMetadataReceived",value:function(e,t){var r=null,i="mp4",n=t.codec;if("audio"===e)this._audioMeta=t,"mp3"===t.codec&&this._mp3UseMpegAudio?(i="mpeg",n="",r=new Uint8Array):r=or.generateInitSegment(t);else{if("video"!==e)return;this._videoMeta=t,r=or.generateInitSegment(t)}if(!this._onInitSegment)throw new IllegalStateException("MP4Remuxer: onInitSegment callback must be specified!");this._onInitSegment(e,{type:e,data:r.buffer,codec:n,container:e+"/"+i,mediaDuration:t.duration})}},{key:"_calculateDtsBase",value:function(e,t){this._dtsBaseInited||(e.samples&&e.samples.length&&(this._audioDtsBase=e.samples[0].dts),t.samples&&t.samples.length&&(this._videoDtsBase=t.samples[0].dts),this._dtsBase=Math.min(this._audioDtsBase,this._videoDtsBase),this._dtsBaseInited=!0)}},{key:"_remuxAudio",value:function(e){if(null!=this._audioMeta){var t,r=e,i=r.samples,n=void 0,o=-1,a=this._audioMeta.refSampleDuration,s="mp3"===this._audioMeta.codec&&this._mp3UseMpegAudio,u=this._dtsBaseInited&&void 0===this._audioNextDts,c=!1;if(i&&!(i.length<=1)){var l=0,d=null,f=0;s?(l=0,f=r.length):(l=8,f=8+r.length);var h=i[0].dts-this._dtsBase;if(this._audioNextDts)n=h-this._audioNextDts;else if(this._audioSegmentInfoList.isEmpty())n=0,this._fillSilentAfterSeek&&!this._videoSegmentInfoList.isEmpty()&&"mp3"!==this._audioMeta.originalCodec&&(c=!0);else{var p=this._audioSegmentInfoList.getLastSampleBefore(h);if(null!=p){var m=h-(p.originalDts+p.duration);m<=3&&(m=0),n=h-(p.dts+p.duration+m)}else n=0}if(c){var v=h-n,g=this._videoSegmentInfoList.getLastSegmentBefore(h);if(null!=g&&g.beginDts<v){var y=ar.getSilentFrame(this._audioMeta.originalCodec,this._audioMeta.channelCount);if(y){var _=g.beginDts,b=v-g.beginDts;Log.v(this.TAG,"InsertPrefixSilentAudio: dts: "+_+", duration: "+b),i.unshift({unit:y,dts:_,pts:_}),f+=y.byteLength}}else c=!1}var w=[];n=0;for(var E=0;E+1<i.length;E++){var S=i[E],T=S.dts-this._dtsBase,O=T-n;-1===o&&(o=O);var A=0;if(E!==i.length-1)A=i[E+1].dts-this._dtsBase-n-O;else A=w.length>=1?w[w.length-1].duration:Math.floor(a);w.push({dts:O,pts:O,cts:0,unit:S.unit,size:S.unit.byteLength,duration:A,originalDts:T,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0}})}if(s)d=new Uint8Array(f);else{for(var $=8,k=0;k<w.length;++k)$+=w[k].size;(d=new Uint8Array($))[0]=$>>>24&255,d[1]=$>>>16&255,d[2]=$>>>8&255,d[3]=255&$,d.set(or.types.mdat,4)}for(var D=0;D<w.length;D++){var I=w[D].unit;d.set(I,l),l+=I.byteLength}var x=w[w.length-1];t=x.dts+x.duration,this._audioNextDts=t;var C=new lr;C.beginDts=o,C.endDts=t,C.beginPts=o,C.endPts=t,C.originalBeginDts=w[0].originalDts,C.originalEndDts=x.originalDts+x.duration,C.firstSample=new cr(w[0].dts,w[0].pts,w[0].duration,w[0].originalDts,!1),C.lastSample=new cr(x.dts,x.pts,x.duration,x.originalDts,!1),this._isLive||this._audioSegmentInfoList.append(C),r.samples=w,r.sequenceNumber++;var M=null;M=s?new Uint8Array:or.moof(r,o),r.samples=[i[i.length-1]],r.length=0;var P={type:"audio",data:this._mergeBoxes(M,d).buffer,sampleCount:w.length,info:C};s&&u&&(P.timestampOffset=o),this._onMediaSegment("audio",P)}}}},{key:"_remuxVideo",value:function(e){if(null!=this._videoMeta){var t,r,i=e,n=i.samples,o=void 0,a=-1,s=-1;if(n&&!(n.length<=1)){var u=n[0].dts-this._dtsBase;if(this._videoNextDts)o=Math.max(u-this._videoNextDts,0);else if(this._videoSegmentInfoList.isEmpty())o=0;else{var c=this._videoSegmentInfoList.getLastSampleBefore(u);if(null!=c){var l=u-(c.originalDts+c.duration);l<=3&&(l=0),o=u-(c.dts+c.duration+l)}else o=0}var d=new lr,f=[],h=o;o=0;for(var p=0;p+1<n.length;p++){var m=n[p],v=m.dts-this._dtsBase-(0==p?h:0),g=m.isKeyframe,y=v-o,_=m.cts,b=y+_;-1===a&&(a=y,s=b);var w=0;if(p!==n.length-1)w=n[p+1].dts-this._dtsBase-o-y;else w=f.length>=1?f[f.length-1].duration:Math.floor(this._videoMeta.refSampleDuration);if(g){var E=new cr(y,b,w,m.dts,!0);E.fileposition=m.fileposition,d.appendSyncPoint(E)}f.push({dts:y,pts:b,cts:_,units:m.units,size:m.length,isKeyframe:g,duration:w,originalDts:v,flags:{isLeading:0,dependsOn:g?2:1,isDependedOn:g?1:0,hasRedundancy:0,isNonSync:g?0:1}})}for(var S=8,T=8,O=0;O<f.length;++O)T+=f[O].size;var A=new Uint8Array(T);A[0]=T>>>24&255,A[1]=T>>>16&255,A[2]=T>>>8&255,A[3]=255&T,A.set(or.types.mdat,4);for(var $=0;$<f.length;$++)for(var k=f[$].units;k.length;){var D=k.shift().data;A.set(D,S),S+=D.byteLength}var I=f[f.length-1];if(t=I.dts+I.duration,r=I.pts+I.duration,this._videoNextDts=t,d.beginDts=a,d.endDts=t,d.beginPts=s,d.endPts=r,d.originalBeginDts=f[0].originalDts,d.originalEndDts=I.originalDts+I.duration,d.firstSample=new cr(f[0].dts,f[0].pts,f[0].duration,f[0].originalDts,f[0].isKeyframe),d.lastSample=new cr(I.dts,I.pts,I.duration,I.originalDts,I.isKeyframe),this._isLive||this._videoSegmentInfoList.append(d),i.samples=f,i.sequenceNumber++,this._forceFirstIDR){var x=f[0].flags;x.dependsOn=2,x.isNonSync=0}var C=or.moof(i,a);i.samples=[n[n.length-1]],i.length=0,this._onMediaSegment("video",{type:"video",data:this._mergeBoxes(C,A).buffer,sampleCount:f.length,info:d})}}}},{key:"_mergeBoxes",value:function(e,t){var r=new Uint8Array(e.byteLength+t.byteLength);return r.set(e,0),r.set(t,e.byteLength),r}},{key:"onInitSegment",get:function(){return this._onInitSegment},set:function(e){this._onInitSegment=e}},{key:"onMediaSegment",get:function(){return this._onMediaSegment},set:function(e){this._onMediaSegment=e}}]),e}(),hr=function(){function e(t){Gt(this,e),or.init(),this._config={_isLive:!1},zt(this._config,t),this.onInitSegment=null,this.onMediaSegment=null,this.onMediaInfo=null,this.seekCallBack=null,this.loadmetadata=!1,this.ftyp_moov=null,this._tagdemux=new ir,this._flvparse=new nr,this.ftyp_moov_v=null,this.ftyp_moov_a=null,this.metaSuccRun=!1,this.metas=[],this.parseChunk=null,this.hasVideo=!1,this.hasAudio=!1,this._error=null,this._pendingResolveSeekPoint=-1,this._tempBaseTime=0,this.setflvBase=this.setflvBasefrist,this._tagdemux._onTrackMetadata=this.Metadata.bind(this),this._tagdemux._onMediaInfo=this.metaSucc.bind(this),this._tagdemux._onDataAvailable=this.onDataAvailable.bind(this),this._tagdemux._onError=this.error.bind(this),this.m4mof=new fr(this._config),this.m4mof.onMediaSegment=this.onMdiaSegment.bind(this)}return Yt(e,[{key:"seek",value:function(e){this._flvparse.dispose(),this.setflvBase=this.setflvBasefrist,void 0!=e&&0!=e||(e=0,this._pendingResolveSeekPoint=-1),this._tempBaseTime!=e&&(this._tempBaseTime=e,this._tagdemux._timestampBase=e,this.m4mof.seek(e),this.m4mof.insertDiscontinuity(),this._pendingResolveSeekPoint=e)}},{key:"setflvBasefrist",value:function(e,t){var r=0;try{r=this._flvparse.setFlv(new Uint8Array(e))}catch(e){this.error(e)}if(0==this._flvparse.arrTag.length)return r;if(this._flvparse.arrTag.length>0){this._tagdemux.hasAudio=this.hasAudio=this._flvparse._hasAudio,this._tagdemux.hasVideo=this.hasVideo=this._flvparse._hasVideo,0!=this._tempBaseTime&&this._tempBaseTime==this._flvparse.arrTag[0].getTime()&&(this._tagdemux._timestampBase=0);try{this._tagdemux.moofTag(this._flvparse.arrTag)}catch(e){this.error(e)}this.setflvBase=this.setflvBaseUsually}return r}},{key:"setflvBaseUsually",value:function(e,t){var r=0;try{r=this._flvparse.setFlv(new Uint8Array(e))}catch(e){this.error(e)}if(this._flvparse.arrTag.length>0)try{this._tagdemux.moofTag(this._flvparse.arrTag)}catch(e){this.error(e)}return r}},{key:"onMdiaSegment",value:function(e,t){if(this.onMediaSegment&&this.onMediaSegment(e,new Uint8Array(t.data)),-1!=this._pendingResolveSeekPoint&&"video"==e){var r=this._pendingResolveSeekPoint;this._pendingResolveSeekPoint=-1,this.seekCallBack&&this.seekCallBack(r)}}},{key:"Metadata",value:function(e,t){switch(e){case"video":if(this.metas.push(["video",t]),this.m4mof._videoMeta=t,this.hasVideo&&!this.hasAudio)return void this.metaSucc();break;case"audio":if(this.metas.push(["audio",t]),this.m4mof._audioMeta=t,!this.hasVideo&&this.hasAudio)return void this.metaSucc()}this.hasVideo&&this.hasAudio&&this.m4mof._videoMeta&&this.m4mof._audioMeta&&this.metaSucc()}},{key:"metaSucc",value:function(e){var t=this;this.onMediaInfo&&e&&this.onMediaInfo(e||this._tagdemux._mediaInfo,{hasAudio:this.hasAudio,hasVideo:this.hasVideo}),0!=this.metas.length?e||(this.metas.length>1?this.metas.map(function(e){"video"==e[0]?t.ftyp_moov_v=or.generateInitSegment([e[1]]):t.ftyp_moov_a=or.generateInitSegment([e[1]])}):this.ftyp_moov=or.generateInitSegment([this.metas[0][1]]),this.onInitSegment&&0==this.loadmetadata&&(this.ftyp_moov?this.onInitSegment(this.ftyp_moov):this.onInitSegment(this.ftyp_moov_v,this.ftyp_moov_a),this.loadmetadata=!0)):this.metaSuccRun=!0}},{key:"onDataAvailable",value:function(e,t){try{this.m4mof.remux(e,t)}catch(e){this.error(e)}}},{key:"setflv",value:function(e,t){return this.setflvBase(e,t)}},{key:"setflvloc",value:function(e){nr.setFlv(new Uint8Array(e));if(nr.arrTag.length>0)return nr.arrTag}},{key:"error",value:function(e){this._error&&this._error(e)}}]),e}(),pr=function(e){function t(e){Gt(this,t);var r=It(this,(t.__proto__||H(t)).call(this));return r.f2m=new hr(e),r.f2m._error=r.error.bind(r),r._onInitSegment=null,r._onMediaSegment=null,r._onMediaInfo=null,r._seekCallBack=null,r}return jt(t,e),Yt(t,[{key:"error",value:function(e){this.emit("error",e.type)}},{key:"seek",value:function(e){this.f2m.seek(e)}},{key:"setflv",value:function(e){return this.f2m.setflv(e,0)}},{key:"setflvloc",value:function(e){return this.f2m.setflvloc(e)}},{key:"onInitSegment",set:function(e){this._onInitSegment=e,this.f2m.onInitSegment=e}},{key:"onMediaSegment",set:function(e){this._onMediaSegment=e,this.f2m.onMediaSegment=e}},{key:"onMediaInfo",set:function(e){this._onMediaInfo=e,this.f2m.onMediaInfo=e}},{key:"seekCallBack",set:function(e){this._seekCallBack=e,this.f2m.seekCallBack=e}}]),t}(i.CustEvent);t.default=pr},function(e,t,r){e.exports=r(7)},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),n=u(r(8)),o=u(r(9)),a=u(r(17)),s=r(18);function u(e){return e&&e.__esModule?e:{default:e}}var c=function(e){function t(e,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return i.tag="flv-player",i.video=e,i.box="flv",i.timer=null,i.seekTimer=null,i.config=(0,s.deepAssign)({},a.default,r),i.requestSetTime=!1,i.throttle=null,i.bindEvents(),i.attachMedia(),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,s.CustEvent),i(t,null,[{key:"isSupport",value:function(){var e=(new s.UAParser).getBrowser();return!("Safari"===e.name&&parseInt(e.major)<10)&&!(!window.MediaSource||!window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.640020,mp4a.40.2"'))}},{key:"version",get:function(){return"1.4.9"}}]),i(t,[{key:"internalPropertyHandle",value:function(){if(Object.getOwnPropertyDescriptor){var e=this,t=Object.getOwnPropertyDescriptor(HTMLMediaElement.prototype,"currentTime");Object.defineProperty(this.video,"currentTime",{get:function(){return t.get.call(e.video)},set:function(r){if(e.currentTimeLock)return t.set.call(e.video,r);throw new Error("can not set currentTime by youself")}})}}},{key:"bindEvents",value:function(){var e=this;this.video&&this.video.addEventListener("canplay",function(){e.config.isLive&&e.video.play(),e.config.lockInternalProperty&&e.internalPropertyHandle()})}},{key:"attachMedia",value:function(){var e=this;this.mediaSource=new n.default(this.video,this.config),this.mediaSource.on("error",function(t){e.emit("error",t.data),e.transmuxer&&e.transmuxer.pause()}),this.mediaSource.on("bufferFull",function(){e.pauseTransmuxer()}),this.mediaSource.on("updateend",function(){e.onmseUpdateEnd()})}},{key:"load",value:function(e){e&&(this.config.src=e),this.transmuxer=new o.default(this.mediaSource,this.config,this.globalEvent),this.transmuxerEvent(this.transmuxer),this.transmuxer.loadSource()}},{key:"transmuxerEvent",value:function(e){var t=this,r=this.mediaSource;e.on("mediaSegment",function(e){r.emit("mediaSegment",e.data)}),e.on("mediaSegmentInit",function(e){r.emit("mediaSegmentInit",e.data)}),e.on("error",function(i){t.emit("error",i.data),e.pause(),r.pause()}),e.on("end",function(e){r.endOfStream()}),e.on("heartbeat",function(e){t.emit("heartbeat",e.data)}),e.on("mediaInfo",function(e){t.mediaInfo||(t.mediaInfo=e,t.emit("mediaInfo",e.data),r.init(e.data),t.video.src=URL.createObjectURL(r.mediaSource),t.video.addEventListener("seeking",t._throttle.call(t)))})}},{key:"_throttle",value:function(){return this.throttle=(0,s.throttle)(this._seek.bind(this),200,{leading:!1}),this.throttle}},{key:"isTimeinBuffered",value:function(e){for(var t=this.video.buffered,r=0;r<t.length;r++){var i=t.start(r),n=t.end(r);if(e>=i&&e<n)return!0}return!1}},{key:"getCurrentBufferEnd",value:function(){for(var e=this.video.buffered,t=this.video.currentTime,r=0;r<e.length;r++){var i=e.start(r),n=e.end(r);if(i<=t&&t<n)return n}}},{key:"_seek",value:function(e){var t=this;this.currentTimeLock=!0;var r=(0,s.isNumber)(e)&&!isNaN(e)?e:this.video.currentTime;if(this.requestSetTime)return this.requestSetTime=!1,void(this.currentTimeLock=!1);if(this.isTimeinBuffered(r)){if(this.config.alwaysSeekKeyframe){var i=this.transmuxer.getNearestKeyframe(Math.floor(1e3*r));i&&(this.requestSetTime=!0,this.video.currentTime=i.keyframetime/1e3)}}else{s.Log.verbose(this.tag,"do seek"),this.transmuxer.pause();var n=this.transmuxer.getNearestKeyframe(Math.floor(1e3*r));r=n.keyframetime/1e3,this.seekTimer=setTimeout(function(){t.mediaSource.seek(r),t.transmuxer.seek(n)},100),this.requestSetTime=!0,this.video.currentTime=r,window.clearInterval(this.timer),this.timer=null}return this.currentTimeLock=!1,r}},{key:"onmseUpdateEnd",value:function(){this.config.isLive||this.getCurrentBufferEnd()>=this.video.currentTime+this.config.lazyLoadMaxDuration&&null===this.timer&&(s.Log.verbose(this.tag,"Maximum buffering duration exceeded, suspend transmuxing task"),this.pauseTransmuxer())}},{key:"heartbeat",value:function(){for(var e=this.video.currentTime,t=this.video.buffered,r=!1,i=0;i<t.length;i++){var n=t.start(i),o=t.end(i);if(e>=n&&e<o){e>=o-this.config.lazyLoadRecoverDuration&&(r=!0);break}}r&&(window.clearInterval(this.timer),this.timer=null,s.Log.verbose(this.tag,"Continue loading from paused position"),this.transmuxer.resume(),this.mediaSource.resume())}},{key:"pauseTransmuxer",value:function(){this.transmuxer.pause(),this.mediaSource.pause(),this.timer||(this.timer=setInterval(this.heartbeat.bind(this),1e3))}},{key:"resume",value:function(){this._seek(0)}},{key:"destroy",value:function(){window.clearInterval(this.timer),window.clearInterval(this.seekTimer),this.video.removeEventListener("seeking",this.throttle),this.video&&(URL.revokeObjectURL(this.video.src),this.video.src="",this.video.removeAttribute("src"),this.transmuxer&&(this.transmuxer.pause(),this.transmuxer.destroy(),this.transmuxer=null),this.mediaSource&&(this.mediaSource.destroy(),this.mediaSource=null))}},{key:"seek",value:function(e){return this._seek(e)}},{key:"play",value:function(){return this.video.play()}},{key:"pause",value:function(){return this.video.pause()}},{key:"refresh",value:function(){this.transmuxer&&this.mediaSource?this._seek(0):s.Log.verbose(this.tag,"transmuxer & mediaSource not ready")}},{key:"stopLoad",value:function(){this.transmuxer&&this.transmuxer.pause(),this.mediaSource&&this.mediaSource.pause()}}]),t}();t.default=c},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i,n=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),o=r(0),a=r(2),s=(i=a)&&i.__esModule?i:{default:i},u=r(1);var c=function(e){function t(e,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return i.video=e,i.config=r,i.tag="mse-controller",i.e={onSourceOpen:i.onSourceOpen.bind(i),onSourceEnded:i.onSourceEnded.bind(i),onSourceClose:i.onSourceClose.bind(i),onSourceBufferError:i.onSourceBufferError.bind(i)},i.hasVideo=!0,i.hasAudio=!0,i.removeRangesList={video:[],audio:[]},i.removeBucketing=!1,i.timer={video:null,audio:null},i.queue={video:[],audio:[]},i.sourceBuffer={video:null,audio:null},i.mimeCodec={video:null,audio:null},i.sourceBufferEvent(),i.complete=!1,i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,o.CustEvent),n(t,[{key:"init",value:function(e){if(this.mediaSource)return s.default.Error(this.tag,"MediaSource has been attached to an HTMLMediaElement!"),void this.emit("error",{errno:u.ERRORNO.MEDIASOURCE_ERROR,errmsg:"MediaSource has been attached to an HTMLMediaElement!"});e.hasAudio?this.mimeCodec.audio='audio/mp4; codecs="'+e.audioCodec+'"':this.hasAudio=!1,e.hasVideo?this.mimeCodec.video='video/mp4; codecs="'+e.videoCodec+'"':this.hasVideo=!1;var t=this.mediaSource=new window.MediaSource;t.addEventListener("sourceopen",this.e.onSourceOpen),t.addEventListener("sourceended",this.e.onSourceEnded),t.addEventListener("sourceclose",this.e.onSourceClose)}},{key:"onSourceOpen",value:function(){s.default.verbose(this.tag,"MediaSource onSourceOpen"),this.mediaSource.removeEventListener("sourceopen",this.e.onSourceOpen),this.hasAudio&&this.addSourceBuffer("audio"),this.hasVideo&&this.addSourceBuffer("video"),this.hasQueueList()&&this.doUpdate(),this.emit("source_open")}},{key:"addSourceBuffer",value:function(e){var t=this;this.sourceBuffer[e]=this.mediaSource.addSourceBuffer(this.mimeCodec[e]),s.default.verbose(this.tag,"add sourcebuffer "+e);var r=this.sourceBuffer[e];r.addEventListener("error",this.e.onSourceBufferError),r.addEventListener("abort",function(){return s.default.verbose(t.tag,"sourceBuffer: abort")}),r.addEventListener("updateend",function(){t.sourceBuffer&&(t.hasRemoveList()?(t.removeRangesList.video.length&&t.cleanRangesList("video"),t.removeRangesList.audio.length&&t.cleanRangesList("audio")):t.hasQueueList()?t.doUpdate():t.complete&&!t.sourceBuffer[e].updating&&t.endOfStream(),t.emit("updateend"))})}},{key:"hasRemoveList",value:function(){return this.removeRangesList.video.length||this.removeRangesList.audio.length}},{key:"hasQueueList",value:function(){return this.queue.video.length||this.queue.audio.length}},{key:"doUpdate",value:function(){for(var e in this.queue)if(this.queue[e].length>0&&!this.sourceBuffer[e].updating){var t=this.queue[e].shift();this.appendBuffer(t,e)}}},{key:"sourceBufferEvent",value:function(){var e=this;this.on("mediaSegment",function(t){var r=t.data,i=r.type;e.needCleanupSourceBuffer(i)&&e.doCleanupSourceBuffer(i),e.queue[i].push(r.data),e.sourceBuffer[i]&&!e.hasRemoveList()&&e.doUpdate()}),this.on("mediaSegmentInit",function(t){var r=t.data,i=r.type;e.queue[i].push(r.data)})}},{key:"needCleanupSourceBuffer",value:function(e){var t=this.video.currentTime,r=this.video.buffered;return r.length>=1&&t-r.start(0)>=this.config.autoCleanupMaxBackwardDuration}},{key:"doCleanupSourceBuffer",value:function(e){for(var t=this.video.currentTime,r=this.sourceBuffer[e].buffered,i=!1,n=0;n<r.length;n++){var o=r.start(n),a=r.end(n);if(o<=t&&t<a+3&&t-o>=this.config.autoCleanupMaxBackwardDuration){i=!0;var s=t-this.config.autoCleanupMinBackwardDuration;this.removeRangesList[e].push({start:o,end:s})}}i&&!this.sourceBuffer[e].updating&&this.cleanRangesList(e)}},{key:"cleanRangesList",value:function(e){if(!this.sourceBuffer[e].updating)for(var t=this.sourceBuffer[e];this.removeRangesList[e].length&&!t.updating;){var r=this.removeRangesList[e].shift();t.remove(r.start,r.end)}}},{key:"appendBuffer",value:function(e,t){if(this.sourceBuffer[t])try{this.sourceBuffer[t].appendBuffer(e.buffer)}catch(r){this.queue[t].unshift(e),22===r.code&&(s.default.verbose(this.tag,"MediaSource bufferFull"),this.emit("bufferFull"))}}},{key:"onSourceEnded",value:function(){s.default.verbose(this.tag,"MediaSource onSourceEnded")}},{key:"onSourceClose",value:function(){s.default.verbose(this.tag,"MediaSource onSourceClose"),this.mediaSource&&null!==this.e&&(this.mediaSource.removeEventListener("sourceopen",this.e.onSourceOpen),this.mediaSource.removeEventListener("sourceended",this.e.onSourceEnded),this.mediaSource.removeEventListener("sourceclose",this.e.onSourceClose))}},{key:"onSourceBufferError",value:function(e){this.emit("error",{errnono:u.ERRORNO.SOURCEBUFFER_ERROR,errmsg:e}),s.default.error(this.tag,"SourceBuffer Error: "+e)}},{key:"seek",value:function(){for(var e in this.sourceBuffer){var t=this.sourceBuffer[e];if(t){if("open"===this.mediaSource.readyState)try{t.abort()}catch(e){this.emit("error",{errno:u.ERRORNO.SBABORT_ERROR,errmsg:e}),s.default.error(this.tag,e.message)}this.queue[e]=[];for(var r=0;r<t.buffered.length;r++){var i=t.buffered.start(r),n=t.buffered.end(r);this.removeRangesList[e].push({start:i,end:n})}t.updating||this.cleanRangesList(e)}}}},{key:"resume",value:function(){this.doUpdate()}},{key:"pause",value:function(){}},{key:"endOfStream",value:function(){if(this.mediaSource){var e=this.mediaSource;this.complete=!0;var t=this.sourceBuffer;if(t.video&&t.video.updating||t.audio&&t.audio.updating)return;if("open"===e.readyState)try{e.endOfStream(),this.complete=!1}catch(e){s.default.verbose(this.tag,e),this.emit("error",{errno:u.ERRORNO.ENDOFSTREAM_ERROR,errmsg:e})}}}},{key:"destroy",value:function(){if(this.mediaSource){var e=this.mediaSource;this.queue={video:[],audio:[]},this.sourceBuffer={video:null,audio:null},this.mimeCodec={video:null,audio:null};var t=this.sourceBuffer;this.complete=!1,this.endOfStream(),t&&("closed"!==e.readyState&&(e.removeSourceBuffer(t),t.removeEventListener("error",this.e.onSourceBufferError),t.removeEventListener("updateend",this.e.onSourceBufferUpdateEnd)),this.sourceBuffer=null),e.removeEventListener("sourceopen",this.e.onSourceOpen),e.removeEventListener("sourceended",this.e.onSourceEnded),e.removeEventListener("sourceclose",this.e.onSourceClose),this.mediaSource=null}}}]),t}();t.default=c},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),n=c(r(3)),o=r(0),a=c(r(15)),s=c(r(5)),u=r(1);function c(e){return e&&e.__esModule?e:{default:e}}var l=function(e){function t(e,r,i){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var n=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return n.config=r||{},n.tag="transmuxer",n.loader=null,n.CPU=null,n.keyframePoint=!1,n.w=null,n.config.webWorker&&(n.w=(0,a.default)(16),n.w.addEventListener("message",function(e){n.parseCallback.call(n,e.data)}),n.w.postMessage({cmd:"init",data:r})),n.lock=0,n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,o.CustEvent),i(t,[{key:"loadSource",value:function(){this.config.webWorker?this.w.postMessage({cmd:"loadSource"}):(this.loader=new n.default(this.config),this.loader.arrivalDataCallback=this.arrivalDataCallback.bind(this),this.loader.open(),this.loaderBindEvent(this.loader))}},{key:"loaderBindEvent",value:function(e){var t=this;e.on("end",function(){t.emit("end")}),e.on("error",function(e){t.emit("error",e.data)}),e.on("heartbeat",function(e){t.emit("heartbeat",e.data)})}},{key:"arrivalDataCallback",value:function(e,t,r){var i=this;return this.CPU||(this.config.isLive?this.config._isLive=!0:this.config._isLive=!1,this.CPU=new s.default(this.config),this.CPU.onInitSegment=this.onRemuxerInitSegmentArrival.bind(this),this.CPU.onMediaSegment=this.onRemuxerMediaSegmentArrival.bind(this),this.CPU.onMediaInfo=this.onMediaInfo.bind(this),this.CPU.on("error",function(e){i.emit("error",{errno:u.ERRORNO.CODEC_ERROR,errmsg:e.data})})),void 0!==r&&this.CPU.seek(r),this.CPU.setflv(e)}},{key:"parseCallback",value:function(e){switch(e.cmd){case"mediaSegmentInit":this.emit("mediaSegmentInit",e.source);break;case"mediaSegment":this.emit("mediaSegment",e.source);break;case"mediainfo":this.mediaInfo=e.source,this.emit("mediaInfo",e.source);break;case"error":this.emit("error",e.source)}}},{key:"onMediaInfo",value:function(e){this.mediaInfo=e,this.emit("mediaInfo",e)}},{key:"onRemuxerInitSegmentArrival",value:function(e,t){this.emit("mediaSegmentInit",{type:"video",data:e}),t&&this.emit("mediaSegmentInit",{type:"audio",data:t})}},{key:"onRemuxerMediaSegmentArrival",value:function(e,t){this.emit("mediaSegment",{type:e,data:t})}},{key:"getMediaInfo",value:function(){return this.mediaInfo}},{key:"pause",value:function(){this.config.webWorker?this.w.postMessage({cmd:"pause"}):this.loader.pause()}},{key:"resume",value:function(){this.config.webWorker?this.w.postMessage({cmd:"resume"}):this.loader.resume()}},{key:"isSeekable",value:function(){return this.mediaInfo.hasKeyframesIndex}},{key:"seek",value:function(e){if(!this.isSeekable())return this.emit("error",{errno:u.ERRORNO.CANNOT_SEEK,errmsg:"这个flv视频不支持seek"}),!1;this.config.webWorker?this.w.postMessage({cmd:"seek",keyframe:e}):this.loader.seek(e.keyframePoint,!1,e.keyframetime)}},{key:"destroy",value:function(){this.config.webWorker?this.w.postMessage({cmd:"destroy"}):(this.loader.destroy(),this.loader=null,this.CPU=null)}},{key:"getNearestKeyframe",value:function(e){if(this.mediaInfo&&this.mediaInfo.keyframesIndex){var t=this.mediaInfo.keyframesIndex.times,r=this.mediaInfo.keyframesIndex.filepositions;return function e(i,n){var o=i.length,a=Math.floor(o/2);if(1===o){var s=t.indexOf(i[0]);return{keyframetime:i[0],keyframePoint:r[s]}}if(i[a]>n)return e(i.slice(0,a),n);if(i[a]<n)return e(i.slice(a),n);var u=t.indexOf(i[0]);return{keyframetime:i[0],keyframePoint:r[u]}}(t,e)}return 0}}]),t}();t.default=l},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),n=u(r(11)),o=r(0),a=u(r(2)),s=r(1);function u(e){return e&&e.__esModule?e:{default:e}}var c=function(e){function t(e,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return i.tag="fetch",i.fetching=!1,i.config=r,i.range={from:0,to:524288},i.src=e,i.totalRange=null,i.block=524288,i.reader=null,i.requestAbort=!1,i.arrivalDataCallback=null,i.bytesStart=0,i.heartbeat=null,i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,o.CustEvent),i(t,null,[{key:"isSupport",value:function(){return!(!self.fetch||!self.ReadableStream)}}]),i(t,[{key:"open",value:function(e,t){var r=this;this.requestAbort=!1;var i=new Headers,o=e||{from:0,to:-1};if(!this.config.isLive){this.range.from=o.from,this.range.to=o.to;var a=(0,n.default)(o,this.config);if("string"==typeof a)this.src=this.config.src+a;else for(var u in a)i.append(u,a[u])}t&&(this.bytesStart=0),this.bytesStart=e.from;var c={method:"GET",headers:i,mode:"cors",cache:"default",referrerPolicy:"no-referrer-when-downgrade"};fetch(this.src,c).then(function(e){if(e.ok){var i=e.body.getReader();return r.pump(i,t)}}).catch(function(e){r.emit("error",{errno:s.ERRORNO.NET_ERROR,errmsg:e})})}},{key:"pause",value:function(){this.requestAbort=!0}},{key:"pump",value:function(e,t){var r=this;return e.read().then(function(i){if(!i.done){if(!0===r.requestAbort)return r.requestAbort=!1,e.cancel();var n=i.value.buffer;return r.arrivalDataCallback&&(r.arrivalDataCallback(n,r.bytesStart,t),r.bytesStart+=n.byteLength),r.pump(e)}r.emit("end"),a.default.verbose(r.tag,"load end")}).catch(function(e){r.emit("error",{errno:s.ERRORNO.NET_ERROR,errmsg:e.message})})}}]),t}();t.default=c},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){if("range"===t.seekType){var r={},i=void 0;return i=-1!==e.to?"bytes="+e.from.toString()+"-"+e.to.toString():"bytes="+e.from.toString()+"-",r.Range=i,r}return-1!==e.to?"?start="+e.from.toString()+"&end="+e.to.toString():"?start="+e.from.toString()}},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i,n=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),o=r(4),a=(i=o)&&i.__esModule?i:{default:i},s=r(0),u=r(1);var c=function(e){function t(e,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return i.tag="RangeLoader",i.xhr=null,i.src=e,i.totalLength=null,i.chunkSizeKB=524288,i.range={},i.bytesStart=0,i.needSeek=!1,i.keyframePoint=null,i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,s.CustEvent),n(t,null,[{key:"isSupport",value:function(){try{var e=new XMLHttpRequest;return e.open("GET","https://example.com",!0),e.responseType="arraybuffer","arraybuffer"===e.responseType}catch(e){return!1}}}]),n(t,[{key:"open",value:function(e,t){var r=this.xhr=new XMLHttpRequest;r.open("GET",this.src,!0),r.responseType="arraybuffer",r.onreadystatechange=this.onReadyStateChange.bind(this),r.onprogress=this.onProgress.bind(this),r.onload=this.onLoad.bind(this),r.onerror=this.onXhrError.bind(this);var i=e||{from:0,to:-1};this.range.from=i.from,-1===i.to&&(i.to=i.from+this.chunkSizeKB),t&&(this.bytesStart=e.from,this.needSeek=!0,this.keyframePoint=t),this.range.to=i.to;var n=(0,a.default)(i).headers;for(var o in n)r.setRequestHeader(o,n[o]);r.send()}},{key:"pause",value:function(){this.abort()}},{key:"abort",value:function(){this.xhr&&(this.xhr.onreadystatechange=null,this.xhr.onprogress=null,this.xhr.onload=null,this.xhr.onerror=null,this.xhr.abort(),this.xhr=null)}},{key:"destroy",value:function(){this.xhr&&(this.abort(),this.xhr.onreadystatechange=null,this.xhr.onprogress=null,this.xhr.onload=null,this.xhr.onerror=null,this.xhr=null),this.totalLength=null,this.bytesStart=null,this.range={}}},{key:"onReadyStateChange",value:function(e){var t=this.xhr;if(2===t.readyState&&t.status<200&&t.status>299){var r={from:this.range.from,to:this.range.to,url:this.src,msg:"http Error: http code "+t.status};this.emit("error",{errno:u.ERRORNO.NET_ERROR,errmsg:r})}}},{key:"onProgress",value:function(e){this.totalLength||(this.totalLength=e.total,this.abort(),this.open())}},{key:"onLoad",value:function(e){if(this.totalLength&&this.arrivalDataCallback){var t=e.target.response;this.needSeek?(this.needSeek=!1,this.arrivalDataCallback(t,this.bytesStart,this.keyframePoint)):this.arrivalDataCallback(t,this.bytesStart),this.bytesStart+=t.byteLength,this.open({from:this.bytesStart,to:-1})}}},{key:"onXhrError",value:function(e){var t={from:this.range.from,to:this.range.to,url:this.src,msg:e.constructor.name+" "+e.type};this.emit("error",{errno:u.ERRORNO.NET_ERROR,errmsg:t})}}]),t}();t.default=c},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),n=r(0),o=r(1);var a=function(e){function t(e,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return i.tag="WebSocket",i.src=e,i._ws=null,i._requestAbort=!1,i._receivedLength=0,i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,n.CustEvent),i(t,null,[{key:"isSupported",value:function(){try{return void 0!==window.WebSocket}catch(e){return!1}}}]),i(t,[{key:"destroy",value:function(){this._ws&&this.abort()}},{key:"open",value:function(e,t){try{var r=this._ws=new self.WebSocket(this.src);r.binaryType="arraybuffer",r.onopen=this.onWebSocketOpen.bind(this),r.onclose=this.onWebSocketClose.bind(this),r.onmessage=this.onWebSocketMessage.bind(this),r.onerror=this.onWebSocketError.bind(this)}catch(e){var i={code:e.code,msg:e.message};this.emit("error",{errno:o.ERRORNO.NET_ERROR,errmsg:i})}}},{key:"abort",value:function(){var e=this._ws;!e||0!==e.readyState&&1!==e.readyState||(this._requestAbort=!0,e.close()),this._ws=null}},{key:"onWebSocketClose",value:function(e){!0!==this._requestAbort?this.emit("end"):this._requestAbort=!1}},{key:"onWebSocketOpen",value:function(){}},{key:"onWebSocketMessage",value:function(e){var t=this;if(e.data instanceof ArrayBuffer)this.dispatchArrayBuffer(e.data);else if(e.data instanceof Blob){var r=new FileReader;r.onload=function(){t.dispatchArrayBuffer(r.result)},r.readAsArrayBuffer(e.data)}else{var i={code:-1,msg:"Unsupported WebSocket message type: "+e.data.constructor.name};this.emit("error",{errno:o.ERRORNO.NET_ERROR,errmsg:i})}}},{key:"dispatchArrayBuffer",value:function(e){var t=e,r=this.receivedLength;this.receivedLength+=t.byteLength,this.arrivalDataCallback&&this.arrivalDataCallback(t,r)}},{key:"onWebSocketError",value:function(e){var t={code:e.code,msg:e.message};this.emit("error",{errno:o.ERRORNO.NET_ERROR,errmsg:t})}}]),t}();t.default=a},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});var i,n=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),o=r(4),a=(i=o)&&i.__esModule?i:{default:i},s=r(0),u=r(1);var c=function(e){function t(e,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return i.tag="mozChunkLoader",i.xhr=null,i.src=e,i.config=r,i.totalLength=null,i.chunkSizeKB=393216,i.range={},i.bytesStart=0,i.keyframePoint=null,i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,s.CustEvent),n(t,null,[{key:"isSupport",value:function(){try{var e=new XMLHttpRequest;return e.open("GET","https://example.com",!0),e.responseType="moz-chunked-arraybuffer","moz-chunked-arraybuffer"===e.responseType}catch(e){return!1}}}]),n(t,[{key:"open",value:function(e,t){var r=this.xhr=new XMLHttpRequest;if(r.open("GET",this.src,!0),r.responseType="moz-chunked-arraybuffer",r.onreadystatechange=this.onReadyStateChange.bind(this),r.onprogress=this.onProgress.bind(this),r.onload=this.onLoadEnd.bind(this),r.onerror=this.onXhrError.bind(this),!this.config.isLive){var i=e||{from:0,to:-1};this.range.from=i.from,this.range.to=i.to,t&&(this.needSeek=!0,this.keyframePoint=t);var n=(0,a.default)(i).headers;for(var o in n)r.setRequestHeader(o,n[o])}r.send()}},{key:"pause",value:function(){this.abort()}},{key:"abort",value:function(){this.xhr&&(this.xhr.onreadystatechange=null,this.xhr.onprogress=null,this.xhr.onload=null,this.xhr.onerror=null,this.xhr.abort(),this.xhr=null)}},{key:"destroy",value:function(){this.xhr&&(this.abort(),this.xhr.onreadystatechange=null,this.xhr.onprogress=null,this.xhr.onload=null,this.xhr.onerror=null,this.xhr=null),this.totalLength=null,this.bytesStart=null,this.range={}}},{key:"onReadyStateChange",value:function(e){var t=this.xhr;if(2===t.readyState&&t.status<200&&t.status>299){var r={from:this.range.from,to:this.range.to,url:this.src,msg:"http Error: http code "+t.status};this.emit("error",{errno:u.ERRORNO.NET_ERROR,errmsg:r})}}},{key:"onProgress",value:function(e){this.totalLength||(this.totalLength=e.total,null!==e.total&&0!==e.total&&(this.totalLength=e.total));var t=e.target.response;this.needSeek?(this.needSeek=!1,this.arrivalDataCallback(t,this.bytesStart,this.keyframePoint)):this.arrivalDataCallback(t,this.bytesStart),this.bytesStart+=t.byteLength}},{key:"onLoadEnd",value:function(e){this.emit(this.tag,"video load end")}},{key:"onXhrError",value:function(e){var t={from:this.range.from,to:this.range.to,url:this.src,msg:e.constructor.name+" "+e.type};this.emit("error",{errno:u.ERRORNO.NET_ERROR,errmsg:t})}}]),t}();t.default=c},function(e,t,r){function i(e){var t={};function r(i){if(t[i])return t[i].exports;var n=t[i]={i:i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}r.m=e,r.c=t,r.i=function(e){return e},r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:i})},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="/",r.oe=function(e){throw console.error(e),e};var i=r(r.s=ENTRY_MODULE);return i.default||i}var n="[\\.|\\-|\\+|\\w|/|@]+",o="\\((/\\*.*?\\*/)?s?.*?("+n+").*?\\)";function a(e){return(e+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function s(e,t,i){var s={};s[i]=[];var u=t.toString(),c=u.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/);if(!c)return s;for(var l,d=c[1],f=new RegExp("(\\\\n|\\W)"+a(d)+o,"g");l=f.exec(u);)"dll-reference"!==l[3]&&s[i].push(l[3]);for(f=new RegExp("\\("+a(d)+'\\("(dll-reference\\s('+n+'))"\\)\\)'+o,"g");l=f.exec(u);)e[l[2]]||(s[i].push(l[1]),e[l[2]]=r(l[1]).m),s[l[2]]=s[l[2]]||[],s[l[2]].push(l[4]);return s}function u(e){return Object.keys(e).reduce(function(t,r){return t||e[r].length>0},!1)}e.exports=function(e,t){t=t||{};var n={main:r.m},o=t.all?{main:Object.keys(n)}:function(e,t){for(var r={main:[t]},i={main:[]},n={main:{}};u(r);)for(var o=Object.keys(r),a=0;a<o.length;a++){var c=o[a],l=r[c].pop();if(n[c]=n[c]||{},!n[c][l]&&e[c][l]){n[c][l]=!0,i[c]=i[c]||[],i[c].push(l);for(var d=s(e,e[c][l],c),f=Object.keys(d),h=0;h<f.length;h++)r[f[h]]=r[f[h]]||[],r[f[h]]=r[f[h]].concat(d[f[h]])}}return i}(n,e),a="";Object.keys(o).filter(function(e){return"main"!==e}).forEach(function(e){for(var t=0;o[e][t];)t++;o[e].push(t),n[e][t]="(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })",a=a+"var "+e+" = ("+i.toString().replace("ENTRY_MODULE",JSON.stringify(t))+")({"+o[e].map(function(t){return JSON.stringify(t)+": "+n[e][t].toString()}).join(",")+"});\n"}),a=a+"("+i.toString().replace("ENTRY_MODULE",JSON.stringify(e))+")({"+o.main.map(function(e){return JSON.stringify(e)+": "+n.main[e].toString()}).join(",")+"})(self);";var c=new window.Blob([a],{type:"text/javascript"});if(t.bare)return c;var l=(window.URL||window.webkitURL||window.mozURL||window.msURL).createObjectURL(c),d=new window.Worker(l);return d.objectURL=l,d}},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=null,r=null,o={};function a(e,t){self.postMessage({cmd:"mediaSegmentInit",source:{type:"video",data:e}}),t&&self.postMessage({cmd:"mediaSegmentInit",source:{type:"audio",data:t}})}function s(e,t){self.postMessage({cmd:"mediaSegment",source:{type:e,data:t}})}function u(e){self.postMessage({cmd:"error",source:e})}function c(e){self.postMessage({cmd:"mediainfo",source:e})}function l(e,r,n){return t||((t=new i.default).onInitSegment=a,t.onMediaSegment=s,t.onError=u,t.onMediaInfo=c,t.on("error",function(e){self.postMessage({cmd:"error",source:e.data})})),n&&t.seek(n),t.setflv(e)}e.addEventListener("message",function(e){switch(e.data.cmd){case"init":o=e.data.data;break;case"loadSource":(r=new n.default(o)).arrivalDataCallback=l,r.open();break;case"pause":r.pause();break;case"seek":i=e.data.keyframe,r.pause(),(r=new n.default(o)).arrivalDataCallback=l,r.seek(i.keyframePoint,!1,i.keyframetime);break;case"resume":r.resume();break;case"destroy":r.destroy(),r=null,t=null}var i})};var i=o(r(5)),n=o(r(3));function o(e){return e&&e.__esModule?e:{default:e}}},function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.default={isLive:!1,box:"flv",seekInKeyframe:!0,alwaysSeekKeyframe:!0,lazyLoadMaxDuration:120,lazyLoadRecoverDuration:30,lockInternalProperty:!1,debug:!0,webWorker:!1,autoCleanupSourceBuffer:!0,autoCleanupMaxBackwardDuration:30,autoCleanupMinBackwardDuration:30,stashSize:393216,seekType:"range"}},function(e,t,r){(function(e){(function(t){var r="undefined"!=typeof window?window:void 0!==e?e:"undefined"!=typeof self?self:{};function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function n(e,t){return e(t={exports:{}},t.exports),t.exports}var o=Math.ceil,a=Math.floor,s=function(e){return isNaN(e=+e)?0:(e>0?a:o)(e)},u=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e},c=n(function(e){var t=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=t)}),l=n(function(e){var t=e.exports={version:"2.5.1"};"number"==typeof __e&&(__e=t)}),d=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e},f=function(e,t,r){if(d(e),void 0===t)return e;switch(r){case 1:return function(r){return e.call(t,r)};case 2:return function(r,i){return e.call(t,r,i)};case 3:return function(r,i,n){return e.call(t,r,i,n)}}return function(){return e.apply(t,arguments)}},h=function(e){return"object"==typeof e?null!==e:"function"==typeof e},p=function(e){if(!h(e))throw TypeError(e+" is not an object!");return e},m=function(e){try{return!!e()}catch(e){return!0}},v=!m(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),g=c.document,y=h(g)&&h(g.createElement),_=function(e){return y?g.createElement(e):{}},b=!v&&!m(function(){return 7!=Object.defineProperty(_("div"),"a",{get:function(){return 7}}).a}),w=function(e,t){if(!h(e))return e;var r,i;if(t&&"function"==typeof(r=e.toString)&&!h(i=r.call(e)))return i;if("function"==typeof(r=e.valueOf)&&!h(i=r.call(e)))return i;if(!t&&"function"==typeof(r=e.toString)&&!h(i=r.call(e)))return i;throw TypeError("Can't convert object to primitive value")},E=Object.defineProperty,S={f:v?Object.defineProperty:function(e,t,r){if(p(e),t=w(t,!0),p(r),b)try{return E(e,t,r)}catch(e){}if("get"in r||"set"in r)throw TypeError("Accessors not supported!");return"value"in r&&(e[t]=r.value),e}},T=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},O=v?function(e,t,r){return S.f(e,t,T(1,r))}:function(e,t,r){return e[t]=r,e},A=function(e,t,r){var i,n,o,a=e&A.F,s=e&A.G,u=e&A.S,d=e&A.P,h=e&A.B,p=e&A.W,m=s?l:l[t]||(l[t]={}),v=m.prototype,g=s?c:u?c[t]:(c[t]||{}).prototype;for(i in s&&(r=t),r)(n=!a&&g&&void 0!==g[i])&&i in m||(o=n?g[i]:r[i],m[i]=s&&"function"!=typeof g[i]?r[i]:h&&n?f(o,c):p&&g[i]==o?function(e){var t=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,r)}return new e(t,r,i)}return e.apply(this,arguments)};return t.prototype=e.prototype,t}(o):d&&"function"==typeof o?f(Function.call,o):o,d&&((m.virtual||(m.virtual={}))[i]=o,e&A.R&&v&&!v[i]&&O(v,i,o)))};A.F=1,A.G=2,A.S=4,A.P=8,A.B=16,A.W=32,A.U=64,A.R=128;var $,k=A,D=O,I={}.hasOwnProperty,x=function(e,t){return I.call(e,t)},C={},M={}.toString,P=function(e){return M.call(e).slice(8,-1)},L=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==P(e)?e.split(""):Object(e)},R=function(e){return L(u(e))},N=Math.min,j=function(e){return e>0?N(s(e),9007199254740991):0},F=Math.max,B=Math.min,U=c["__core-js_shared__"]||(c["__core-js_shared__"]={}),z=function(e){return U[e]||(U[e]={})},G=0,W=Math.random(),H=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++G+W).toString(36))},V=z("keys"),Y=function(e){return V[e]||(V[e]=H(e))},K=($=!1,function(e,t,r){var i,n=R(e),o=j(n.length),a=function(e,t){return(e=s(e))<0?F(e+t,0):B(e,t)}(r,o);if($&&t!=t){for(;o>a;)if((i=n[a++])!=i)return!0}else for(;o>a;a++)if(($||a in n)&&n[a]===t)return $||a||0;return!$&&-1}),Z=Y("IE_PROTO"),Q=function(e,t){var r,i=R(e),n=0,o=[];for(r in i)r!=Z&&x(i,r)&&o.push(r);for(;t.length>n;)x(i,r=t[n++])&&(~K(o,r)||o.push(r));return o},X="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),q=Object.keys||function(e){return Q(e,X)},J=v?Object.defineProperties:function(e,t){p(e);for(var r,i=q(t),n=i.length,o=0;n>o;)S.f(e,r=i[o++],t[r]);return e},ee=c.document,te=ee&&ee.documentElement,re=Y("IE_PROTO"),ie=function(){},ne=function(){var e,t=_("iframe"),r=X.length;for(t.style.display="none",te.appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),ne=e.F;r--;)delete ne.prototype[X[r]];return ne()},oe=Object.create||function(e,t){var r;return null!==e?(ie.prototype=p(e),r=new ie,ie.prototype=null,r[re]=e):r=ne(),void 0===t?r:J(r,t)},ae=n(function(e){var t=z("wks"),r=c.Symbol,i="function"==typeof r;(e.exports=function(e){return t[e]||(t[e]=i&&r[e]||(i?r:H)("Symbol."+e))}).store=t}),se=S.f,ue=ae("toStringTag"),ce=function(e,t,r){e&&!x(e=r?e:e.prototype,ue)&&se(e,ue,{configurable:!0,value:t})},le={};O(le,ae("iterator"),function(){return this});var de,fe=function(e,t,r){e.prototype=oe(le,{next:T(1,r)}),ce(e,t+" Iterator")},he=function(e){return Object(u(e))},pe=Y("IE_PROTO"),me=Object.prototype,ve=Object.getPrototypeOf||function(e){return e=he(e),x(e,pe)?e[pe]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?me:null},ge=ae("iterator"),ye=!([].keys&&"next"in[].keys()),_e=function(){return this},be=function(e,t,r,i,n,o,a){fe(r,t,i);var s,u,c,l=function(e){if(!ye&&e in p)return p[e];switch(e){case"keys":case"values":return function(){return new r(this,e)}}return function(){return new r(this,e)}},d=t+" Iterator",f="values"==n,h=!1,p=e.prototype,m=p[ge]||p["@@iterator"]||n&&p[n],v=m||l(n),g=n?f?l("entries"):v:void 0,y="Array"==t&&p.entries||m;if(y&&(c=ve(y.call(new e)))!==Object.prototype&&c.next&&ce(c,d,!0),f&&m&&"values"!==m.name&&(h=!0,v=function(){return m.call(this)}),a&&(ye||h||!p[ge])&&O(p,ge,v),C[t]=v,C[d]=_e,n)if(s={values:f?v:l("values"),keys:o?v:l("keys"),entries:g},a)for(u in s)u in p||D(p,u,s[u]);else k(k.P+k.F*(ye||h),t,s);return s},we=(de=!0,function(e,t){var r,i,n=String(u(e)),o=s(t),a=n.length;return o<0||o>=a?de?"":void 0:(r=n.charCodeAt(o))<55296||r>56319||o+1===a||(i=n.charCodeAt(o+1))<56320||i>57343?de?n.charAt(o):r:de?n.slice(o,o+2):i-56320+(r-55296<<10)+65536});be(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,r=this._i;return r>=t.length?{value:void 0,done:!0}:(e=we(t,r),this._i+=e.length,{value:e,done:!1})});var Ee=function(e,t,r,i){try{return i?t(p(r)[0],r[1]):t(r)}catch(t){var n=e.return;throw void 0!==n&&p(n.call(e)),t}},Se=ae("iterator"),Te=Array.prototype,Oe=function(e){return void 0!==e&&(C.Array===e||Te[Se]===e)},Ae=function(e,t,r){t in e?S.f(e,t,T(0,r)):e[t]=r},$e=ae("toStringTag"),ke="Arguments"==P(function(){return arguments}()),De=function(e){var t,r,i;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=function(e,t){try{return e[t]}catch(e){}}(t=Object(e),$e))?r:ke?P(t):"Object"==(i=P(t))&&"function"==typeof t.callee?"Arguments":i},Ie=ae("iterator"),xe=l.getIteratorMethod=function(e){if(void 0!=e)return e[Ie]||e["@@iterator"]||C[De(e)]},Ce=ae("iterator"),Me=!1;try{[7][Ce]().return=function(){Me=!0}}catch(e){}var Pe=function(e,t){if(!t&&!Me)return!1;var r=!1;try{var i=[7],n=i[Ce]();n.next=function(){return{done:r=!0}},i[Ce]=function(){return n},e(i)}catch(e){}return r};k(k.S+k.F*!Pe(function(e){}),"Array",{from:function(e){var t,r,i,n,o=he(e),a="function"==typeof this?this:Array,s=arguments.length,u=s>1?arguments[1]:void 0,c=void 0!==u,l=0,d=xe(o);if(c&&(u=f(u,s>2?arguments[2]:void 0,2)),void 0==d||a==Array&&Oe(d))for(r=new a(t=j(o.length));t>l;l++)Ae(r,l,c?u(o[l],l):o[l]);else for(n=d.call(o),r=new a;!(i=n.next()).done;l++)Ae(r,l,c?Ee(n,u,[i.value,l],!0):i.value);return r.length=l,r}});var Le=l.Array.from,Re=n(function(e){e.exports={default:Le,__esModule:!0}}),Ne=i(Re),je=i(n(function(e,t){t.__esModule=!0;var r,i=(r=Re)&&r.__esModule?r:{default:r};t.default=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return(0,i.default)(e)}})),Fe=function(e,t){return{value:t,done:!!e}};be(Array,"Array",function(e,t){this._t=R(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,r=this._i++;return!e||r>=e.length?(this._t=void 0,Fe(1)):Fe(0,"keys"==t?r:"values"==t?e[r]:[r,e[r]])},"values");C.Arguments=C.Array;for(var Be=ae("toStringTag"),Ue="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),ze=0;ze<Ue.length;ze++){var Ge=Ue[ze],We=c[Ge],He=We&&We.prototype;He&&!He[Be]&&O(He,Be,Ge),C[Ge]=C.Array}var Ve={f:ae},Ye=Ve.f("iterator"),Ke=n(function(e){e.exports={default:Ye,__esModule:!0}});i(Ke);var Ze=n(function(e){var t=H("meta"),r=S.f,i=0,n=Object.isExtensible||function(){return!0},o=!m(function(){return n(Object.preventExtensions({}))}),a=function(e){r(e,t,{value:{i:"O"+ ++i,w:{}}})},s=e.exports={KEY:t,NEED:!1,fastKey:function(e,r){if(!h(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!x(e,t)){if(!n(e))return"F";if(!r)return"E";a(e)}return e[t].i},getWeak:function(e,r){if(!x(e,t)){if(!n(e))return!0;if(!r)return!1;a(e)}return e[t].w},onFreeze:function(e){return o&&s.NEED&&n(e)&&!x(e,t)&&a(e),e}}}),Qe=S.f,Xe=function(e){var t=l.Symbol||(l.Symbol={});"_"==e.charAt(0)||e in t||Qe(t,e,{value:Ve.f(e)})},qe={f:Object.getOwnPropertySymbols},Je={f:{}.propertyIsEnumerable},et=Array.isArray||function(e){return"Array"==P(e)},tt=X.concat("length","prototype"),rt={f:Object.getOwnPropertyNames||function(e){return Q(e,tt)}},it=rt.f,nt={}.toString,ot="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],at={f:function(e){return ot&&"[object Window]"==nt.call(e)?function(e){try{return it(e)}catch(e){return ot.slice()}}(e):it(R(e))}},st=Object.getOwnPropertyDescriptor,ut={f:v?st:function(e,t){if(e=R(e),t=w(t,!0),b)try{return st(e,t)}catch(e){}if(x(e,t))return T(!Je.f.call(e,t),e[t])}},ct=Ze.KEY,lt=ut.f,dt=S.f,ft=at.f,ht=c.Symbol,pt=c.JSON,mt=pt&&pt.stringify,vt=ae("_hidden"),gt=ae("toPrimitive"),yt={}.propertyIsEnumerable,_t=z("symbol-registry"),bt=z("symbols"),wt=z("op-symbols"),Et=Object.prototype,St="function"==typeof ht,Tt=c.QObject,Ot=!Tt||!Tt.prototype||!Tt.prototype.findChild,At=v&&m(function(){return 7!=oe(dt({},"a",{get:function(){return dt(this,"a",{value:7}).a}})).a})?function(e,t,r){var i=lt(Et,t);i&&delete Et[t],dt(e,t,r),i&&e!==Et&&dt(Et,t,i)}:dt,$t=function(e){var t=bt[e]=oe(ht.prototype);return t._k=e,t},kt=St&&"symbol"==typeof ht.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof ht},Dt=function(e,t,r){return e===Et&&Dt(wt,t,r),p(e),t=w(t,!0),p(r),x(bt,t)?(r.enumerable?(x(e,vt)&&e[vt][t]&&(e[vt][t]=!1),r=oe(r,{enumerable:T(0,!1)})):(x(e,vt)||dt(e,vt,T(1,{})),e[vt][t]=!0),At(e,t,r)):dt(e,t,r)},It=function(e,t){p(e);for(var r,i=function(e){var t=q(e),r=qe.f;if(r)for(var i,n=r(e),o=Je.f,a=0;n.length>a;)o.call(e,i=n[a++])&&t.push(i);return t}(t=R(t)),n=0,o=i.length;o>n;)Dt(e,r=i[n++],t[r]);return e},xt=function(e){var t=yt.call(this,e=w(e,!0));return!(this===Et&&x(bt,e)&&!x(wt,e))&&(!(t||!x(this,e)||!x(bt,e)||x(this,vt)&&this[vt][e])||t)},Ct=function(e,t){if(e=R(e),t=w(t,!0),e!==Et||!x(bt,t)||x(wt,t)){var r=lt(e,t);return!r||!x(bt,t)||x(e,vt)&&e[vt][t]||(r.enumerable=!0),r}},Mt=function(e){for(var t,r=ft(R(e)),i=[],n=0;r.length>n;)x(bt,t=r[n++])||t==vt||t==ct||i.push(t);return i},Pt=function(e){for(var t,r=e===Et,i=ft(r?wt:R(e)),n=[],o=0;i.length>o;)!x(bt,t=i[o++])||r&&!x(Et,t)||n.push(bt[t]);return n};St||(D((ht=function(){if(this instanceof ht)throw TypeError("Symbol is not a constructor!");var e=H(arguments.length>0?arguments[0]:void 0),t=function(r){this===Et&&t.call(wt,r),x(this,vt)&&x(this[vt],e)&&(this[vt][e]=!1),At(this,e,T(1,r))};return v&&Ot&&At(Et,e,{configurable:!0,set:t}),$t(e)}).prototype,"toString",function(){return this._k}),ut.f=Ct,S.f=Dt,rt.f=at.f=Mt,Je.f=xt,qe.f=Pt,Ve.f=function(e){return $t(ae(e))}),k(k.G+k.W+k.F*!St,{Symbol:ht});for(var Lt="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),Rt=0;Lt.length>Rt;)ae(Lt[Rt++]);for(var Nt=q(ae.store),jt=0;Nt.length>jt;)Xe(Nt[jt++]);k(k.S+k.F*!St,"Symbol",{for:function(e){return x(_t,e+="")?_t[e]:_t[e]=ht(e)},keyFor:function(e){if(!kt(e))throw TypeError(e+" is not a symbol!");for(var t in _t)if(_t[t]===e)return t},useSetter:function(){Ot=!0},useSimple:function(){Ot=!1}}),k(k.S+k.F*!St,"Object",{create:function(e,t){return void 0===t?oe(e):It(oe(e),t)},defineProperty:Dt,defineProperties:It,getOwnPropertyDescriptor:Ct,getOwnPropertyNames:Mt,getOwnPropertySymbols:Pt}),pt&&k(k.S+k.F*(!St||m(function(){var e=ht();return"[null]"!=mt([e])||"{}"!=mt({a:e})||"{}"!=mt(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!kt(e)){for(var t,r,i=[e],n=1;arguments.length>n;)i.push(arguments[n++]);return"function"==typeof(t=i[1])&&(r=t),!r&&et(t)||(t=function(e,t){if(r&&(t=r.call(this,e,t)),!kt(t))return t}),i[1]=t,mt.apply(pt,i)}}}),ht.prototype[gt]||O(ht.prototype,gt,ht.prototype.valueOf),ce(ht,"Symbol"),ce(Math,"Math",!0),ce(c.JSON,"JSON",!0),Xe("asyncIterator"),Xe("observable");var Ft=l.Symbol,Bt=n(function(e){e.exports={default:Ft,__esModule:!0}});i(Bt);var Ut,zt,Gt,Wt,Ht=i(n(function(e,t){t.__esModule=!0;var r=o(Ke),i=o(Bt),n="function"==typeof i.default&&"symbol"==typeof r.default?function(e){return typeof e}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":typeof e};function o(e){return e&&e.__esModule?e:{default:e}}t.default="function"==typeof i.default&&"symbol"===n(r.default)?function(e){return void 0===e?"undefined":n(e)}:function(e){return e&&"function"==typeof i.default&&e.constructor===i.default&&e!==i.default.prototype?"symbol":void 0===e?"undefined":n(e)}}));Ut="keys",zt=function(){return function(e){return q(he(e))}},Gt=(l.Object||{})[Ut]||Object[Ut],(Wt={})[Ut]=zt(Gt),k(k.S+k.F*m(function(){Gt(1)}),"Object",Wt);var Vt=l.Object.keys,Yt=i(n(function(e){e.exports={default:Vt,__esModule:!0}})),Kt=Math.floor;k(k.S,"Number",{isInteger:function(e){return!h(e)&&isFinite(e)&&Kt(e)===e}});var Zt=l.Number.isInteger,Qt=i(n(function(e){e.exports={default:Zt,__esModule:!0}})),Xt="\t\n\v\f\r \u2028\u2029\ufeff",qt="["+Xt+"]",Jt=RegExp("^"+qt+qt+"*"),er=RegExp(qt+qt+"*$"),tr=function(e,t,r){var i={},n=m(function(){return!!Xt[e]()||"
"!="
"[e]()}),o=i[e]=n?t(rr):Xt[e];r&&(i[r]=o),k(k.P+k.F*n,"String",i)},rr=tr.trim=function(e,t){return e=String(u(e)),1&t&&(e=e.replace(Jt,"")),2&t&&(e=e.replace(er,"")),e},ir=tr,nr=c.parseFloat,or=ir.trim,ar=1/nr(Xt+"-0")!=-1/0?function(e){var t=or(String(e),3),r=nr(t);return 0===r&&"-"==t.charAt(0)?-0:r}:nr;k(k.S+k.F*(Number.parseFloat!=ar),"Number",{parseFloat:ar});var sr=parseFloat,ur=i(n(function(e){e.exports={default:sr,__esModule:!0}}));function cr(e){return void 0===e||null===e}function lr(e){return Array.isArray(e)}function dr(e){return"function"==typeof e}function fr(e){return Object(e)===e&&"[object Object]"===String(e)&&!dr(e)&&!lr(e)}function hr(e){return"number"==typeof e}function pr(e){return e instanceof Blob}function mr(e){return"string"==typeof e||e instanceof String}function vr(e){return"boolean"==typeof e}function gr(e){return cr(e)||vr(e)||mr(e)||hr(e)}function yr(e){return!!("object"===("undefined"==typeof Node?"undefined":Ht(Node))?e instanceof Node:e&&"object"===(void 0===e?"undefined":Ht(e))&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName)}function _r(e){return function t(r,i,n){if(lr(r)||fr(r)){for(var o in i=gr(i)?fr(r)?{}:[]:i,r)i[o]=t(r[o],i[o],o);return i}return e(r,i,n)}}var br=_r(function(e){return e});function wr(e,t){return e.replace(/(^|[^a-zA-Z]+)([a-zA-Z])/g,function(e,r,i,n){return t||0!==n?i.toUpperCase():i.toLowerCase()})}function Er(){return(65536*(1+Math.random())|0).toString(16).substring(1)}var Sr,Tr,Or,Ar=n(function(e){var t={},r={},i=e.exports=function(e,i,n,o,a){var s,u,c,l,d=a?function(){return e}:xe(e),h=f(n,o,i?2:1),m=0;if("function"!=typeof d)throw TypeError(e+" is not iterable!");if(Oe(d)){for(s=j(e.length);s>m;m++)if((l=i?h(p(u=e[m])[0],u[1]):h(e[m]))===t||l===r)return l}else for(c=d.call(e);!(u=c.next()).done;)if((l=Ee(c,h,u.value,i))===t||l===r)return l};i.BREAK=t,i.RETURN=r}),$r=ae("species"),kr=function(e,t){var r,i=p(e).constructor;return void 0===i||void 0==(r=p(i)[$r])?t:d(r)},Dr=c.process,Ir=c.setImmediate,xr=c.clearImmediate,Cr=c.MessageChannel,Mr=c.Dispatch,Pr=0,Lr={},Rr=function(){var e=+this;if(Lr.hasOwnProperty(e)){var t=Lr[e];delete Lr[e],t()}},Nr=function(e){Rr.call(e.data)};Ir&&xr||(Ir=function(e){for(var t=[],r=1;arguments.length>r;)t.push(arguments[r++]);return Lr[++Pr]=function(){!function(e,t,r){var i=void 0===r;switch(t.length){case 0:return i?e():e.call(r);case 1:return i?e(t[0]):e.call(r,t[0]);case 2:return i?e(t[0],t[1]):e.call(r,t[0],t[1]);case 3:return i?e(t[0],t[1],t[2]):e.call(r,t[0],t[1],t[2]);case 4:return i?e(t[0],t[1],t[2],t[3]):e.call(r,t[0],t[1],t[2],t[3])}e.apply(r,t)}("function"==typeof e?e:Function(e),t)},Sr(Pr),Pr},xr=function(e){delete Lr[e]},"process"==P(Dr)?Sr=function(e){Dr.nextTick(f(Rr,e,1))}:Mr&&Mr.now?Sr=function(e){Mr.now(f(Rr,e,1))}:Cr?(Or=(Tr=new Cr).port2,Tr.port1.onmessage=Nr,Sr=f(Or.postMessage,Or,1)):c.addEventListener&&"function"==typeof postMessage&&!c.importScripts?(Sr=function(e){c.postMessage(e+"","*")},c.addEventListener("message",Nr,!1)):Sr="onreadystatechange"in _("script")?function(e){te.appendChild(_("script")).onreadystatechange=function(){te.removeChild(this),Rr.call(e)}}:function(e){setTimeout(f(Rr,e,1),0)});var jr={set:Ir,clear:xr},Fr=jr.set,Br=c.MutationObserver||c.WebKitMutationObserver,Ur=c.process,zr=c.Promise,Gr="process"==P(Ur);var Wr,Hr,Vr,Yr,Kr={f:function(e){return new function(e){var t,r;this.promise=new e(function(e,i){if(void 0!==t||void 0!==r)throw TypeError("Bad Promise constructor");t=e,r=i}),this.resolve=d(t),this.reject=d(r)}(e)}},Zr=function(e){try{return{e:!1,v:e()}}catch(e){return{e:!0,v:e}}},Qr=function(e,t){if(p(e),h(t)&&t.constructor===e)return t;var r=Kr.f(e);return(0,r.resolve)(t),r.promise},Xr=ae("species"),qr=jr.set,Jr=function(){var e,t,r,i=function(){var i,n;for(Gr&&(i=Ur.domain)&&i.exit();e;){n=e.fn,e=e.next;try{n()}catch(i){throw e?r():t=void 0,i}}t=void 0,i&&i.enter()};if(Gr)r=function(){Ur.nextTick(i)};else if(Br){var n=!0,o=document.createTextNode("");new Br(i).observe(o,{characterData:!0}),r=function(){o.data=n=!n}}else if(zr&&zr.resolve){var a=zr.resolve();r=function(){a.then(i)}}else r=function(){Fr.call(c,i)};return function(i){var n={fn:i,next:void 0};t&&(t.next=n),e||(e=n,r()),t=n}}(),ei=c.TypeError,ti=c.process,ri=c.Promise,ii="process"==De(ti),ni=function(){},oi=Hr=Kr.f,ai=!!function(){try{var e=ri.resolve(1),t=(e.constructor={})[ae("species")]=function(e){e(ni,ni)};return(ii||"function"==typeof PromiseRejectionEvent)&&e.then(ni)instanceof t}catch(e){}}(),si=function(e){var t;return!(!h(e)||"function"!=typeof(t=e.then))&&t},ui=function(e,t){if(!e._n){e._n=!0;var r=e._c;Jr(function(){for(var i=e._v,n=1==e._s,o=0,a=function(t){var r,o,a=n?t.ok:t.fail,s=t.resolve,u=t.reject,c=t.domain;try{a?(n||(2==e._h&&di(e),e._h=1),!0===a?r=i:(c&&c.enter(),r=a(i),c&&c.exit()),r===t.promise?u(ei("Promise-chain cycle")):(o=si(r))?o.call(r,s,u):s(r)):u(i)}catch(e){u(e)}};r.length>o;)a(r[o++]);e._c=[],e._n=!1,t&&!e._h&&ci(e)})}},ci=function(e){qr.call(c,function(){var t,r,i,n=e._v,o=li(e);if(o&&(t=Zr(function(){ii?ti.emit("unhandledRejection",n,e):(r=c.onunhandledrejection)?r({promise:e,reason:n}):(i=c.console)&&i.error&&i.error("Unhandled promise rejection",n)}),e._h=ii||li(e)?2:1),e._a=void 0,o&&t.e)throw t.v})},li=function(e){if(1==e._h)return!1;for(var t,r=e._a||e._c,i=0;r.length>i;)if((t=r[i++]).fail||!li(t.promise))return!1;return!0},di=function(e){qr.call(c,function(){var t;ii?ti.emit("rejectionHandled",e):(t=c.onrejectionhandled)&&t({promise:e,reason:e._v})})},fi=function(e){var t=this;t._d||(t._d=!0,(t=t._w||t)._v=e,t._s=2,t._a||(t._a=t._c.slice()),ui(t,!0))},hi=function(e){var t,r=this;if(!r._d){r._d=!0,r=r._w||r;try{if(r===e)throw ei("Promise can't be resolved itself");(t=si(e))?Jr(function(){var i={_w:r,_d:!1};try{t.call(e,f(hi,i,1),f(fi,i,1))}catch(e){fi.call(i,e)}}):(r._v=e,r._s=1,ui(r,!1))}catch(e){fi.call({_w:r,_d:!1},e)}}};ai||(ri=function(e){!function(e,t,r,i){if(!(e instanceof t)||void 0!==i&&i in e)throw TypeError(r+": incorrect invocation!")}(this,ri,"Promise","_h"),d(e),Wr.call(this);try{e(f(hi,this,1),f(fi,this,1))}catch(e){fi.call(this,e)}},(Wr=function(e){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1}).prototype=function(e,t,r){for(var i in t)r&&e[i]?e[i]=t[i]:O(e,i,t[i]);return e}(ri.prototype,{then:function(e,t){var r=oi(kr(this,ri));return r.ok="function"!=typeof e||e,r.fail="function"==typeof t&&t,r.domain=ii?ti.domain:void 0,this._c.push(r),this._a&&this._a.push(r),this._s&&ui(this,!1),r.promise},catch:function(e){return this.then(void 0,e)}}),Vr=function(){var e=new Wr;this.promise=e,this.resolve=f(hi,e,1),this.reject=f(fi,e,1)},Kr.f=oi=function(e){return e===ri||e===Yr?new Vr(e):Hr(e)}),k(k.G+k.W+k.F*!ai,{Promise:ri}),ce(ri,"Promise"),function(e){var t="function"==typeof l[e]?l[e]:c[e];v&&t&&!t[Xr]&&S.f(t,Xr,{configurable:!0,get:function(){return this}})}("Promise"),Yr=l.Promise,k(k.S+k.F*!ai,"Promise",{reject:function(e){var t=oi(this);return(0,t.reject)(e),t.promise}}),k(k.S+!0*k.F,"Promise",{resolve:function(e){return Qr(this===Yr?ri:this,e)}}),k(k.S+k.F*!(ai&&Pe(function(e){ri.all(e).catch(ni)})),"Promise",{all:function(e){var t=this,r=oi(t),i=r.resolve,n=r.reject,o=Zr(function(){var r=[],o=0,a=1;Ar(e,!1,function(e){var s=o++,u=!1;r.push(void 0),a++,t.resolve(e).then(function(e){u||(u=!0,r[s]=e,--a||i(r))},n)}),--a||i(r)});return o.e&&n(o.v),r.promise},race:function(e){var t=this,r=oi(t),i=r.reject,n=Zr(function(){Ar(e,!1,function(e){t.resolve(e).then(r.resolve,i)})});return n.e&&i(n.v),r.promise}}),k(k.P+k.R,"Promise",{finally:function(e){var t=kr(this,l.Promise||c.Promise),r="function"==typeof e;return this.then(r?function(r){return Qr(t,e()).then(function(){return r})}:e,r?function(r){return Qr(t,e()).then(function(){throw r})}:e)}}),k(k.S,"Promise",{try:function(e){var t=Kr.f(this),r=Zr(e);return(r.e?t.reject:t.resolve)(r.v),t.promise}});var pi=l.Promise,mi=i(n(function(e){e.exports={default:pi,__esModule:!0}})),vi="undefined"!=typeof window&&"[object Object]"!==Object.prototype.toString.call(window);function gi(e,t,r){var i=e;if(t+r<i.length){for(;r--;)if(128!=(192&i[++t]))return!1;return!0}return!1}var yi=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||window.oRequestAnimationFrame||function(e){return setTimeout(e,17)},_i=window.cancelAnimationFrame||window.mozCancelAnimationFrame||window.webkitCancelAnimationFrame||window.webkitCancelRequestAnimationFrame||window.msCancelAnimationFrame||window.oCancelAnimationFrame||function(e){clearTimeout(e)};function bi(e,t){var r=t,i=(e=""+(e||"")).length;return(((t=(t||i)-i)>0?e.repeat?"0".repeat(t):new Array(t+1).join("0"):"")+e).slice(0,r)}var wi=i(n(function(e,t){t.__esModule=!0,t.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}}));k(k.S+k.F*!v,"Object",{defineProperty:S.f});var Ei=l.Object,Si=function(e,t,r){return Ei.defineProperty(e,t,r)},Ti=n(function(e){e.exports={default:Si,__esModule:!0}});i(Ti);var Oi=i(n(function(e,t){t.__esModule=!0;var r,i=(r=Ti)&&r.__esModule?r:{default:r};t.default=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),(0,i.default)(e,n.key,n)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}()})),Ai=Object.assign,$i=!Ai||m(function(){var e={},t={},r=Symbol(),i="abcdefghijklmnopqrst";return e[r]=7,i.split("").forEach(function(e){t[e]=e}),7!=Ai({},e)[r]||Object.keys(Ai({},t)).join("")!=i})?function(e,t){for(var r=he(e),i=arguments.length,n=1,o=qe.f,a=Je.f;i>n;)for(var s,u=L(arguments[n++]),c=o?q(u).concat(o(u)):q(u),l=c.length,d=0;l>d;)a.call(u,s=c[d++])&&(r[s]=u[s]);return r}:Ai;k(k.S+k.F,"Object",{assign:$i});var ki=l.Object.assign,Di=i(n(function(e){e.exports={default:ki,__esModule:!0}}));k(k.S,"Object",{create:oe});var Ii=l.Object,xi=function(e,t){return Ii.create(e,t)},Ci=i(n(function(e){e.exports={default:xi,__esModule:!0}})),Mi=Ci(null);function Pi(e,t){var r=e.__evt_id;r||(Object.defineProperty(e,"__evt_id",{writable:!0,enumerable:!1,configurable:!0}),r=e.__evt_id=++Mi.count);var i=r+"_"+t,n=Mi[i];return n||(n=Mi[i]=[]),n}function Li(e,t,r){var i=Ci(null);i.type=t,i.target=e,r&&Di(i,fr(r)?r:{data:r}),Pi(e,t).forEach(function(t){(t[1]||t[0]).apply(e,[i])})}function Ri(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments[4];dr(i)&&!n&&(n=i,i=void 0);var o=[r,void 0,i];i&&!n&&(n=function(){Ni(e,t,r,i);for(var n=arguments.length,o=Array(n),a=0;a<n;a++)o[a]=arguments[a];r.apply(e,o)}),n&&(o[1]=n),Pi(e,t).push(o)}function Ni(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=Pi(e,t);if(r||i){var o=-1,a=void 0;return n.find(function(e,t){if((!r||e[0]===r)&&(!i||e[2]))return o=t,a=e[1],!0}),-1!==o&&n.splice(o,1),a}n.length=0}Mi.count=0;var ji=function(){function e(t,r){var i=this;if(wi(this,e),Object.defineProperty(this,"__target",{writable:!0,enumerable:!1,configurable:!0}),this.__target=this,t){if("object"!==(void 0===t?"undefined":Ht(t)))throw new Error("CusEvent target are not object");this.__target=t,r&&["on","once","off","emit"].forEach(function(e){t[e]=i[e]})}}return Oi(e,[{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return Ri(this.__target,e,t,r),this}},{key:"once",value:function(e,t){return this.on(e,t,!0)}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return Ni(this.__target,e,t,r),this}},{key:"emit",value:function(e,t){return Li(this.__target,e,{data:t}),this}}]),e}(),Fi=Ci(null);function Bi(e,t){var r=e.__evt_id;r||(Object.defineProperty(e,"__evt_id",{writable:!0,enumerable:!1,configurable:!0}),r=e.__evt_id=++Fi.count);var i=r+"_"+t,n=Fi[i];return n||(n=Fi[i]=[]),n}function Ui(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments[4];dr(i)&&!n&&(n=i,i=void 0);var o=[r,void 0,i];i&&!n&&(n=function(){zi(e,t,r,i);for(var n=arguments.length,o=Array(n),a=0;a<n;a++)o[a]=arguments[a];r.apply(e,o)}),n&&(o[1]=n),Bi(e,t).push(o)}function zi(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=Bi(e,t);if(r||i){var o=-1,a=void 0;return n.find(function(e,t){if((!r||e[0]===r)&&(!i||e[2]))return o=t,a=e[1],!0}),-1!==o&&n.splice(o,1),a}n.length=0}Fi.count=0;(function(){function e(t,r){var i=this;if(wi(this,e),Object.defineProperty(this,"__target",{writable:!0,enumerable:!1,configurable:!0}),this.__target=this,t){if("object"!==(void 0===t?"undefined":Ht(t)))throw new Error("CusEvent target are not object");this.__target=t,r&&["on","once","off","emit"].forEach(function(e){t[e]=i[e]})}}Oi(e,[{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return Ui(this.__target,e,t,r),this}},{key:"once",value:function(e,t){return this.on(e,t,!0)}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return zi(this.__target,e,t,r),this}},{key:"emit",value:function(e,t){return function(e,t,r){var i=Ci(null);i.type=t,i.target=e,r&&Di(i,fr(r)?r:{data:r}),Bi(e,t).forEach(function(t){(t[1]||t[0]).apply(e,[i])})}(this.__target,e,{data:t}),this}}])})(),"undefined"!=typeof window&&Object.prototype.toString.call(window);var Gi=document.createElement("div"),Wi="innerText";"textContent"in Gi&&(Wi="textContent");var Hi=Array.prototype;function Vi(e,t){return e.getAttribute(t)}function Yi(e,t,r){void 0===r?e.removeAttribute(t):e.setAttribute(t,r)}function Ki(e,t){if(t&&(t=t.trim())){var r=t.split(/\s+/);if(e.classList)r.forEach(function(t){return e.classList.add(t)});else{var i=" "+(e.className||"")+" ";r.forEach(function(e){-1===i.indexOf(" "+e+" ")&&(i+=" "+e)}),e.className=i.trim()}}}function Zi(e,t){if(t&&(t=t.trim())){var r=t.split(/\s+/);if(e.classList)r.forEach(function(t){return e.classList.remove(t)});else{var i=" "+e.className+" ";r.forEach(function(e){for(var t=" "+e+" ";-1!==i.indexOf(t);)i=i.replace(t," ")}),e.className=i.trim()}}}function Qi(e,t){return new RegExp("(?:^|\\s)"+t+"(?=\\s|$)").test(e.className)}t.supportsPassive=!1;try{var Xi=Object.defineProperty({},"passive",{get:function(){t.supportsPassive=!0}});window.addEventListener("test",null,Xi)}catch(e){}var qi=!!t.supportsPassive&&{passive:!0};function Ji(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:qi;if(i){var o=zi(e,t+"_once",r);o&&(r=o)}e.removeEventListener(t,r,n)}function en(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:qi;if(i){var o=r;Ui(e,t+"_once",o,r=function(){for(var a=arguments.length,s=Array(a),u=0;u<a;u++)s[u]=arguments[u];o.apply(this,s),Ji(e,t,r,i,n)})}e.addEventListener(t,r,n)}function tn(e,t,r,i){var n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:qi,o=function(r){var n=un(r.target||r.srcElement,e,!0),o=an(t,e,!0),a=void 0;o.find?a=o.find(function(e){return n.find(function(t){return e===t})}):o.forEach(function(e){return!a&&n.forEach(function(t){a||e!==t||(a=t)})}),a&&i.apply(a,arguments)};Ui(e,r+"_delegate_"+t,i,o),e.addEventListener(r,o,n)}function rn(e,t,r,i){var n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:qi,o=zi(e,r+"_delegate_"+t,i);o&&e.removeEventListener(r,o,n)}function nn(e,t){return(e.currentStyle||document.defaultView.getComputedStyle(e,null))[t]||e.style[t]}function on(e,t,r){if(fr(t))for(var i in t)on(e,i,t[i]);else e.style[t]=r}function an(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document,r=arguments[2],i=t.querySelectorAll(e);return r?Ne(i):i}function sn(e){e.parentNode.removeChild(e)}function un(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=arguments[2],i=arguments[3],n=[];for(r&&n.push(e);e&&e.parentNode!==t;)(e=e.parentNode)&&n.push(e);return i&&n.push(t),n}function cn(e,t){return e.constructor===ln?e:new ln(e,t)}var ln=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document;wi(this,e);this.selector=t;var i=void 0;t&&t.constructor===NodeList?i=Ne(t):lr(t)?i=t:mr(t)?0===t.indexOf("<")?(Gi.innerHTML=t,i=an("*",Gi,!0)):i=an(t,r,!0):i=[t],Di(this,i),this.length=i.length}return Oi(e,[{key:"each",value:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return Hi.forEach.apply(this,t),this}},{key:"push",value:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return Hi.push.apply(this,t),this}},{key:"splice",value:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return cn(Hi.splice.apply(this,t))}},{key:"find",value:function(e){var t=[];this.each(function(r){t=t.concat(an(e,r,!0))});var r=cn(t);return r.parent=this,r.selector=e,r}},{key:"append",value:function(e){var t=cn(e),r=this[0];return t.each(function(e){return r.appendChild(e)}),this}},{key:"appendTo",value:function(e){return cn(e).append(this),this}},{key:"text",value:function(e){return 0===arguments.length?this[0][Wi]:this.each(function(t){t[Wi]=e})}},{key:"html",value:function(e){return 0===arguments.length?this[0].innerHTML:this.each(function(t){t.innerHTML=e})}},{key:"attr",value:function(e,t){return 1===arguments.length?Vi(this[0],e):this.each(function(r){return Yi(r,e,t)})}},{key:"data",value:function(e,t){return 0===arguments.length?this[0].dataset||{}:1===arguments.length?(this[0].dataset||{})[e]:this.each(function(r){(r.dataset||(r.dataset={}))[e]=t})}},{key:"css",value:function(e,t){return 1!==arguments.length||fr(e)?this.each(function(r){return on(r,e,t)}):nn(this[0],e)}},{key:"addClass",value:function(e){return this.each(function(t){return Ki(t,e)})}},{key:"removeClass",value:function(e){return this.each(function(t){return Zi(t,e)})}},{key:"hasClass",value:function(e){return Qi(this[0],e)}},{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:qi;return this.each(function(n){return en(n,e,t,r,i)})}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:qi;return this.each(function(n){return Ji(n,e,t,r,i)})}},{key:"delegate",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:qi;return this.each(function(n){return tn(n,e,t,r,i)})}},{key:"undelegate",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:qi;return this.each(function(n){return rn(n,e,t,r,i)})}},{key:"remove",value:function(){return this.each(function(e){return sn(e)})}}]),e}();function dn(e,t){if(!mr(e))throw new TypeError("Log's method only acccept string as argument, but not "+e+" in "+(void 0===e?"undefined":Ht(e)));return mr(t)?"["+(e=fn.FORCE_GLOBAL_TAG?fn.GLOBAL_TAG:e||fn.GLOBAL_TAG)+"] > "+t:"["+fn.GLOBAL_TAG+"] > "+e}var fn=function(){function e(){wi(this,e)}return Oi(e,null,[{key:"error",value:function(t,r){e.ENABLE_ERROR&&(console.error||console.warn||console.log)(dn(t,r))}},{key:"info",value:function(t,r){e.ENABLE_INFO&&(console.info||console.log)(dn(t,r))}},{key:"warn",value:function(t,r){e.ENABLE_WARN&&(console.warn||console.log)(dn(t,r))}},{key:"debug",value:function(t,r){e.ENABLE_DEBUG&&(console.debug||console.log)(dn(t,r))}},{key:"verbose",value:function(t,r){e.ENABLE_VERBOSE&&console.log(dn(t,r))}}]),e}();fn.GLOBAL_TAG="chimee",fn.FORCE_GLOBAL_TAG=!1,fn.ENABLE_ERROR=!0,fn.ENABLE_INFO=!0,fn.ENABLE_WARN=!0,fn.ENABLE_DEBUG=!0,fn.ENABLE_VERBOSE=!0;var hn=n(function(e,t){!function(r,i){var n="model",o="name",a="type",s="vendor",u="version",c="mobile",l="tablet",d={extend:function(e,t){var r={};for(var i in e)t[i]&&t[i].length%2==0?r[i]=t[i].concat(e[i]):r[i]=e[i];return r},has:function(e,t){return"string"==typeof e&&-1!==t.toLowerCase().indexOf(e.toLowerCase())},lowerize:function(e){return e.toLowerCase()},major:function(e){return"string"==typeof e?e.replace(/[^\d\.]/g,"").split(".")[0]:void 0},trim:function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}},f={rgx:function(e,t){for(var r,i,n,o,a,s,u=0;u<t.length&&!a;){var c=t[u],l=t[u+1];for(r=i=0;r<c.length&&!a;)if(a=c[r++].exec(e))for(n=0;n<l.length;n++)s=a[++i],"object"==typeof(o=l[n])&&o.length>0?2==o.length?"function"==typeof o[1]?this[o[0]]=o[1].call(this,s):this[o[0]]=o[1]:3==o.length?"function"!=typeof o[1]||o[1].exec&&o[1].test?this[o[0]]=s?s.replace(o[1],o[2]):void 0:this[o[0]]=s?o[1].call(this,s,o[2]):void 0:4==o.length&&(this[o[0]]=s?o[3].call(this,s.replace(o[1],o[2])):void 0):this[o]=s||void 0;u+=2}},str:function(e,t){for(var r in t)if("object"==typeof t[r]&&t[r].length>0){for(var i=0;i<t[r].length;i++)if(d.has(t[r][i],e))return"?"===r?void 0:r}else if(d.has(t[r],e))return"?"===r?void 0:r;return e}},h={browser:{oldsafari:{version:{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}}},device:{amazon:{model:{"Fire Phone":["SD","KF"]}},sprint:{model:{"Evo Shift 4G":"7373KT"},vendor:{HTC:"APA",Sprint:"Sprint"}}},os:{windows:{version:{ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2000:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"}}}},p={browser:[[/(opera\smini)\/([\w\.-]+)/i,/(opera\s[mobiletab]+).+version\/([\w\.-]+)/i,/(opera).+version\/([\w\.]+)/i,/(opera)[\/\s]+([\w\.]+)/i],[o,u],[/(opios)[\/\s]+([\w\.]+)/i],[[o,"Opera Mini"],u],[/\s(opr)\/([\w\.]+)/i],[[o,"Opera"],u],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]+)*/i,/(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?([\w\.]*)/i,/(?:ms|\()(ie)\s([\w\.]+)/i,/(rekonq)\/([\w\.]+)*/i,/(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser)\/([\w\.-]+)/i],[o,u],[/(trident).+rv[:\s]([\w\.]+).+like\sgecko/i],[[o,"IE"],u],[/(edge)\/((\d+)?[\w\.]+)/i],[o,u],[/(yabrowser)\/([\w\.]+)/i],[[o,"Yandex"],u],[/(puffin)\/([\w\.]+)/i],[[o,"Puffin"],u],[/((?:[\s\/])uc?\s?browser|(?:juc.+)ucweb)[\/\s]?([\w\.]+)/i],[[o,"UCBrowser"],u],[/(comodo_dragon)\/([\w\.]+)/i],[[o,/_/g," "],u],[/(micromessenger)\/([\w\.]+)/i],[[o,"WeChat"],u],[/(QQ)\/([\d\.]+)/i],[o,u],[/m?(qqbrowser)[\/\s]?([\w\.]+)/i],[o,u],[/xiaomi\/miuibrowser\/([\w\.]+)/i],[u,[o,"MIUI Browser"]],[/;fbav\/([\w\.]+);/i],[u,[o,"Facebook"]],[/headlesschrome(?:\/([\w\.]+)|\s)/i],[u,[o,"Chrome Headless"]],[/\swv\).+(chrome)\/([\w\.]+)/i],[[o,/(.+)/,"$1 WebView"],u],[/((?:oculus|samsung)browser)\/([\w\.]+)/i],[[o,/(.+(?:g|us))(.+)/,"$1 $2"],u],[/android.+version\/([\w\.]+)\s+(?:mobile\s?safari|safari)*/i],[u,[o,"Android Browser"]],[/(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i],[o,u],[/(dolfin)\/([\w\.]+)/i],[[o,"Dolphin"],u],[/((?:android.+)crmo|crios)\/([\w\.]+)/i],[[o,"Chrome"],u],[/(coast)\/([\w\.]+)/i],[[o,"Opera Coast"],u],[/fxios\/([\w\.-]+)/i],[u,[o,"Firefox"]],[/version\/([\w\.]+).+?mobile\/\w+\s(safari)/i],[u,[o,"Mobile Safari"]],[/version\/([\w\.]+).+?(mobile\s?safari|safari)/i],[u,o],[/webkit.+?(gsa)\/([\w\.]+).+?(mobile\s?safari|safari)(\/[\w\.]+)/i],[[o,"GSA"],u],[/webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i],[o,[u,f.str,h.browser.oldsafari.version]],[/(konqueror)\/([\w\.]+)/i,/(webkit|khtml)\/([\w\.]+)/i],[o,u],[/(navigator|netscape)\/([\w\.-]+)/i],[[o,"Netscape"],u],[/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i,/(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/([\w\.-]+)/i,/(mozilla)\/([\w\.]+).+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir)[\/\s]?([\w\.]+)/i,/(links)\s\(([\w\.]+)/i,/(gobrowser)\/?([\w\.]+)*/i,/(ice\s?browser)\/v?([\w\._]+)/i,/(mosaic)[\/\s]([\w\.]+)/i],[o,u]],cpu:[[/(?:(amd|x(?:(?:86|64)[_-])?|wow|win)64)[;\)]/i],[["architecture","amd64"]],[/(ia32(?=;))/i],[["architecture",d.lowerize]],[/((?:i[346]|x)86)[;\)]/i],[["architecture","ia32"]],[/windows\s(ce|mobile);\sppc;/i],[["architecture","arm"]],[/((?:ppc|powerpc)(?:64)?)(?:\smac|;|\))/i],[["architecture",/ower/,"",d.lowerize]],[/(sun4\w)[;\)]/i],[["architecture","sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|arm(?:64|(?=v\d+;))|(?=atmel\s)avr|(?:irix|mips|sparc)(?:64)?(?=;)|pa-risc)/i],[["architecture",d.lowerize]]],device:[[/\((ipad|playbook);[\w\s\);-]+(rim|apple)/i],[n,s,[a,l]],[/applecoremedia\/[\w\.]+ \((ipad)/],[n,[s,"Apple"],[a,l]],[/(apple\s{0,1}tv)/i],[[n,"Apple TV"],[s,"Apple"]],[/(archos)\s(gamepad2?)/i,/(hp).+(touchpad)/i,/(hp).+(tablet)/i,/(kindle)\/([\w\.]+)/i,/\s(nook)[\w\s]+build\/(\w+)/i,/(dell)\s(strea[kpr\s\d]*[\dko])/i],[s,n,[a,l]],[/(kf[A-z]+)\sbuild\/[\w\.]+.*silk\//i],[n,[s,"Amazon"],[a,l]],[/(sd|kf)[0349hijorstuw]+\sbuild\/[\w\.]+.*silk\//i],[[n,f.str,h.device.amazon.model],[s,"Amazon"],[a,c]],[/\((ip[honed|\s\w*]+);.+(apple)/i],[n,s,[a,c]],[/\((ip[honed|\s\w*]+);/i],[n,[s,"Apple"],[a,c]],[/(blackberry)[\s-]?(\w+)/i,/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[\s_-]?([\w-]+)*/i,/(hp)\s([\w\s]+\w)/i,/(asus)-?(\w+)/i],[s,n,[a,c]],[/\(bb10;\s(\w+)/i],[n,[s,"BlackBerry"],[a,c]],[/android.+(transfo[prime\s]{4,10}\s\w+|eeepc|slider\s\w+|nexus 7|padfone)/i],[n,[s,"Asus"],[a,l]],[/(sony)\s(tablet\s[ps])\sbuild\//i,/(sony)?(?:sgp.+)\sbuild\//i],[[s,"Sony"],[n,"Xperia Tablet"],[a,l]],[/android.+\s([c-g]\d{4}|so[-l]\w+)\sbuild\//i],[n,[s,"Sony"],[a,c]],[/\s(ouya)\s/i,/(nintendo)\s([wids3u]+)/i],[s,n,[a,"console"]],[/android.+;\s(shield)\sbuild/i],[n,[s,"Nvidia"],[a,"console"]],[/(playstation\s[34portablevi]+)/i],[n,[s,"Sony"],[a,"console"]],[/(sprint\s(\w+))/i],[[s,f.str,h.device.sprint.vendor],[n,f.str,h.device.sprint.model],[a,c]],[/(lenovo)\s?(S(?:5000|6000)+(?:[-][\w+]))/i],[s,n,[a,l]],[/(htc)[;_\s-]+([\w\s]+(?=\))|\w+)*/i,/(zte)-(\w+)*/i,/(alcatel|geeksphone|lenovo|nexian|panasonic|(?=;\s)sony)[_\s-]?([\w-]+)*/i],[s,[n,/_/g," "],[a,c]],[/(nexus\s9)/i],[n,[s,"HTC"],[a,l]],[/d\/huawei([\w\s-]+)[;\)]/i,/(nexus\s6p)/i],[n,[s,"Huawei"],[a,c]],[/(microsoft);\s(lumia[\s\w]+)/i],[s,n,[a,c]],[/[\s\(;](xbox(?:\sone)?)[\s\);]/i],[n,[s,"Microsoft"],[a,"console"]],[/(kin\.[onetw]{3})/i],[[n,/\./g," "],[s,"Microsoft"],[a,c]],[/\s(milestone|droid(?:[2-4x]|\s(?:bionic|x2|pro|razr))?(:?\s4g)?)[\w\s]+build\//i,/mot[\s-]?(\w+)*/i,/(XT\d{3,4}) build\//i,/(nexus\s6)/i],[n,[s,"Motorola"],[a,c]],[/android.+\s(mz60\d|xoom[\s2]{0,2})\sbuild\//i],[n,[s,"Motorola"],[a,l]],[/hbbtv\/\d+\.\d+\.\d+\s+\([\w\s]*;\s*(\w[^;]*);([^;]*)/i],[[s,d.trim],[n,d.trim],[a,"smarttv"]],[/hbbtv.+maple;(\d+)/i],[[n,/^/,"SmartTV"],[s,"Samsung"],[a,"smarttv"]],[/\(dtv[\);].+(aquos)/i],[n,[s,"Sharp"],[a,"smarttv"]],[/android.+((sch-i[89]0\d|shw-m380s|gt-p\d{4}|gt-n\d+|sgh-t8[56]9|nexus 10))/i,/((SM-T\w+))/i],[[s,"Samsung"],n,[a,l]],[/smart-tv.+(samsung)/i],[s,[a,"smarttv"],n],[/((s[cgp]h-\w+|gt-\w+|galaxy\snexus|sm-\w[\w\d]+))/i,/(sam[sung]*)[\s-]*(\w+-?[\w-]*)*/i,/sec-((sgh\w+))/i],[[s,"Samsung"],n,[a,c]],[/sie-(\w+)*/i],[n,[s,"Siemens"],[a,c]],[/(maemo|nokia).*(n900|lumia\s\d+)/i,/(nokia)[\s_-]?([\w-]+)*/i],[[s,"Nokia"],n,[a,c]],[/android\s3\.[\s\w;-]{10}(a\d{3})/i],[n,[s,"Acer"],[a,l]],[/android.+([vl]k\-?\d{3})\s+build/i],[n,[s,"LG"],[a,l]],[/android\s3\.[\s\w;-]{10}(lg?)-([06cv9]{3,4})/i],[[s,"LG"],n,[a,l]],[/(lg) netcast\.tv/i],[s,n,[a,"smarttv"]],[/(nexus\s[45])/i,/lg[e;\s\/-]+(\w+)*/i,/android.+lg(\-?[\d\w]+)\s+build/i],[n,[s,"LG"],[a,c]],[/android.+(ideatab[a-z0-9\-\s]+)/i],[n,[s,"Lenovo"],[a,l]],[/linux;.+((jolla));/i],[s,n,[a,c]],[/((pebble))app\/[\d\.]+\s/i],[s,n,[a,"wearable"]],[/android.+;\s(oppo)\s?([\w\s]+)\sbuild/i],[s,n,[a,c]],[/crkey/i],[[n,"Chromecast"],[s,"Google"]],[/android.+;\s(glass)\s\d/i],[n,[s,"Google"],[a,"wearable"]],[/android.+;\s(pixel c)\s/i],[n,[s,"Google"],[a,l]],[/android.+;\s(pixel xl|pixel)\s/i],[n,[s,"Google"],[a,c]],[/android.+(\w+)\s+build\/hm\1/i,/android.+(hm[\s\-_]*note?[\s_]*(?:\d\w)?)\s+build/i,/android.+(mi[\s\-_]*(?:one|one[\s_]plus|note lte)?[\s_]*(?:\d\w)?)\s+build/i,/android.+(redmi[\s\-_]*(?:note)?(?:[\s_]*[\w\s]+)?)\s+build/i],[[n,/_/g," "],[s,"Xiaomi"],[a,c]],[/android.+(mi[\s\-_]*(?:pad)?(?:[\s_]*[\w\s]+)?)\s+build/i],[[n,/_/g," "],[s,"Xiaomi"],[a,l]],[/android.+;\s(m[1-5]\snote)\sbuild/i],[n,[s,"Meizu"],[a,l]],[/android.+a000(1)\s+build/i],[n,[s,"OnePlus"],[a,c]],[/android.+[;\/]\s*(RCT[\d\w]+)\s+build/i],[n,[s,"RCA"],[a,l]],[/android.+[;\/]\s*(Venue[\d\s]*)\s+build/i],[n,[s,"Dell"],[a,l]],[/android.+[;\/]\s*(Q[T|M][\d\w]+)\s+build/i],[n,[s,"Verizon"],[a,l]],[/android.+[;\/]\s+(Barnes[&\s]+Noble\s+|BN[RT])(V?.*)\s+build/i],[[s,"Barnes & Noble"],n,[a,l]],[/android.+[;\/]\s+(TM\d{3}.*\b)\s+build/i],[n,[s,"NuVision"],[a,l]],[/android.+[;\/]\s*(zte)?.+(k\d{2})\s+build/i],[[s,"ZTE"],n,[a,l]],[/android.+[;\/]\s*(gen\d{3})\s+build.*49h/i],[n,[s,"Swiss"],[a,c]],[/android.+[;\/]\s*(zur\d{3})\s+build/i],[n,[s,"Swiss"],[a,l]],[/android.+[;\/]\s*((Zeki)?TB.*\b)\s+build/i],[n,[s,"Zeki"],[a,l]],[/(android).+[;\/]\s+([YR]\d{2}x?.*)\s+build/i,/android.+[;\/]\s+(Dragon[\-\s]+Touch\s+|DT)(.+)\s+build/i],[[s,"Dragon Touch"],n,[a,l]],[/android.+[;\/]\s*(NS-?.+)\s+build/i],[n,[s,"Insignia"],[a,l]],[/android.+[;\/]\s*((NX|Next)-?.+)\s+build/i],[n,[s,"NextBook"],[a,l]],[/android.+[;\/]\s*(Xtreme\_?)?(V(1[045]|2[015]|30|40|60|7[05]|90))\s+build/i],[[s,"Voice"],n,[a,c]],[/android.+[;\/]\s*(LVTEL\-?)?(V1[12])\s+build/i],[[s,"LvTel"],n,[a,c]],[/android.+[;\/]\s*(V(100MD|700NA|7011|917G).*\b)\s+build/i],[n,[s,"Envizen"],[a,l]],[/android.+[;\/]\s*(Le[\s\-]+Pan)[\s\-]+(.*\b)\s+build/i],[s,n,[a,l]],[/android.+[;\/]\s*(Trio[\s\-]*.*)\s+build/i],[n,[s,"MachSpeed"],[a,l]],[/android.+[;\/]\s*(Trinity)[\-\s]*(T\d{3})\s+build/i],[s,n,[a,l]],[/android.+[;\/]\s*TU_(1491)\s+build/i],[n,[s,"Rotor"],[a,l]],[/android.+(KS(.+))\s+build/i],[n,[s,"Amazon"],[a,l]],[/android.+(Gigaset)[\s\-]+(Q.+)\s+build/i],[s,n,[a,l]],[/\s(tablet|tab)[;\/]/i,/\s(mobile)(?:[;\/]|\ssafari)/i],[[a,d.lowerize],s,n],[/(android.+)[;\/].+build/i],[n,[s,"Generic"]]],engine:[[/windows.+\sedge\/([\w\.]+)/i],[u,[o,"EdgeHTML"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i,/(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i,/(icab)[\/\s]([23]\.[\d\.]+)/i],[o,u],[/rv\:([\w\.]+).*(gecko)/i],[u,o]],os:[[/microsoft\s(windows)\s(vista|xp)/i],[o,u],[/(windows)\snt\s6\.2;\s(arm)/i,/(windows\sphone(?:\sos)*)[\s\/]?([\d\.\s]+\w)*/i,/(windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i],[o,[u,f.str,h.os.windows.version]],[/(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i],[[o,"Windows"],[u,f.str,h.os.windows.version]],[/\((bb)(10);/i],[[o,"BlackBerry"],u],[/(blackberry)\w*\/?([\w\.]+)*/i,/(tizen)[\/\s]([\w\.]+)/i,/(android|webos|palm\sos|qnx|bada|rim\stablet\sos|meego|contiki)[\/\s-]?([\w\.]+)*/i,/linux;.+(sailfish);/i],[o,u],[/(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i],[[o,"Symbian"],u],[/\((series40);/i],[o],[/mozilla.+\(mobile;.+gecko.+firefox/i],[[o,"Firefox OS"],u],[/(nintendo|playstation)\s([wids34portablevu]+)/i,/(mint)[\/\s\(]?(\w+)*/i,/(mageia|vectorlinux)[;\s]/i,/(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|(?=\s)arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus)[\/\s-]?(?!chrom)([\w\.-]+)*/i,/(hurd|linux)\s?([\w\.]+)*/i,/(gnu)\s?([\w\.]+)*/i],[o,u],[/(cros)\s[\w]+\s([\w\.]+\w)/i],[[o,"Chromium OS"],u],[/(sunos)\s?([\w\.]+\d)*/i],[[o,"Solaris"],u],[/\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i],[o,u],[/(haiku)\s(\w+)/i],[o,u],[/cfnetwork\/.+darwin/i,/ip[honead]+(?:.*os\s([\w]+)\slike\smac|;\sopera)/i],[[u,/_/g,"."],[o,"iOS"]],[/(mac\sos\sx)\s?([\w\s\.]+\w)*/i,/(macintosh|mac(?=_powerpc)\s)/i],[[o,"Mac OS"],[u,/_/g,"."]],[/((?:open)?solaris)[\/\s-]?([\w\.]+)*/i,/(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i,/(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms)/i,/(unix)\s?([\w\.]+)*/i],[o,u]]},m=function(e,t){if("object"==typeof e&&(t=e,e=void 0),!(this instanceof m))return new m(e,t).getResult();var i=e||(r&&r.navigator&&r.navigator.userAgent?r.navigator.userAgent:""),n=t?d.extend(p,t):p;return this.getBrowser=function(){var e={name:void 0,version:void 0};return f.rgx.call(e,i,n.browser),e.major=d.major(e.version),e},this.getCPU=function(){var e={architecture:void 0};return f.rgx.call(e,i,n.cpu),e},this.getDevice=function(){var e={vendor:void 0,model:void 0,type:void 0};return f.rgx.call(e,i,n.device),e},this.getEngine=function(){var e={name:void 0,version:void 0};return f.rgx.call(e,i,n.engine),e},this.getOS=function(){var e={name:void 0,version:void 0};return f.rgx.call(e,i,n.os),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return i},this.setUA=function(e){return i=e,this},this};m.VERSION="0.7.17",m.BROWSER={NAME:o,MAJOR:"major",VERSION:u},m.CPU={ARCHITECTURE:"architecture"},m.DEVICE={MODEL:n,VENDOR:s,TYPE:a,CONSOLE:"console",MOBILE:c,SMARTTV:"smarttv",TABLET:l,WEARABLE:"wearable",EMBEDDED:"embedded"},m.ENGINE={NAME:o,VERSION:u},m.OS={NAME:o,VERSION:u},e.exports&&(t=e.exports=m),t.UAParser=m;var v=r&&(r.jQuery||r.Zepto);if(void 0!==v){var g=new m;v.ua=g.getResult(),v.ua.get=function(){return g.getUA()},v.ua.set=function(e){g.setUA(e);var t=g.getResult();for(var r in t)v.ua[r]=t[r]}}}("object"==typeof window?window:r)});t.Log=fn,t.UAParser=hn,t.genTraversalHandler=_r,t.deepClone=function(e){if(gr(e))throw new TypeError("deepClone only accept non primitive type");return br(e)},t.deepAssign=function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(t.length<2)throw new Error("deepAssign accept two and more argument");for(var i=t.length-1;i>-1;i--)if(gr(t[i]))throw new TypeError("deepAssign only accept non primitive type");var n=t.shift();return t.forEach(function(e){return br(e,n)}),n},t.camelize=wr,t.hypenate=function(e){return wr(e).replace(/([A-Z])/g,function(e){return"-"+e.toLowerCase()})},t.bind=function(e,t){return e.bind?e.bind(t):e.apply?function(){for(var r=arguments.length,i=Array(r),n=0;n<r;n++)i[n]=arguments[n];return e.apply(t,i)}:function(){for(var r=arguments.length,i=Array(r),n=0;n<r;n++)i[n]=arguments[n];return e.call.apply(e,[t].concat(je(i)))}},t.uuid=function(){return Er()+Er()+"-"+Er()+"-"+Er()+"-"+Er()+"-"+Er()+Er()+Er()},t.S4=Er,t.rand=function(e){for(var t="";t.length<e;)t+=Er();return t.slice(0,e)},t.getDeepProperty=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=r.throwError,n=void 0!==i&&i,o=r.backup;if(mr(t)&&(t=t.split(".")),!lr(t))throw new TypeError("keys of getDeepProperty must be string or Array<string>");for(var a=[],s=e,u=0,c=t.length;u<c;u++){var l=t[u];if(cr(s)){if(n)throw new Error("obj"+(a.length>0?"."+a.join("."):" itself")+" is "+s);return o}s=s[l],a.push(l)}return s},t.defined=function(e){return void 0!==e},t.isVoid=cr,t.isArray=lr,t.isFunction=dr,t.isObject=fr,t.isNumber=hr,t.isNumeric=function(e){return!lr(e)&&e-ur(e)+1>=0},t.isInteger=function(e){return Qt(e)},t.isEmpty=function(e){return lr(e)?0===e.length:fr(e)?0===Yt(e).length:!e},t.isEvent=function(e){return e instanceof Event||(e&&e.originalEvent)instanceof Event},t.isBlob=pr,t.isFile=function(e){return pr(e)&&mr(e.name)},t.isDate=function(e){return"[object Date]"===Object.prototype.toString.call(e)},t.isString=mr,t.isBoolean=vr,t.isPromise=function(e){return!!e&&("object"===(void 0===e?"undefined":Ht(e))||"function"==typeof e)&&"function"==typeof e.then},t.isPrimitive=gr,t.isUrl=function(e){return mr(e)&&!!e.match(/^((https?|ftp|rtsp|mms):\/\/)(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6}|localhost)(:[0-9]{1,4})?((\/?)|(\/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+\/?)$/i)},t.isNode=yr,t.isElement=function(e){return!!("object"===("undefined"==typeof HTMLElement?"undefined":Ht(HTMLElement))?e instanceof HTMLElement:e&&"object"===(void 0===e?"undefined":Ht(e))&&null!==e&&1===e.nodeType&&"string"==typeof e.nodeName)},t.isChildNode=function(e,t){return!(!yr(e)||!yr(t))&&t.parentNode===e},t.isPosterityNode=function(e,t){if(!yr(e)||!yr(t))return!1;for(;t.parentNode;)if((t=t.parentNode)===e)return!0;return!1},t.isHTMLString=function(e){return/<[^>]+?>/.test(e)},t.isError=function(e){return e instanceof Error},t.isRegExp=function(e){return e instanceof RegExp},t.inBrowser=vi,t.makeArray=function(e){return Ne(e)},t.transObjectAttrIntoArray=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e,t){return+e-+t};return Yt(e).sort(t).reduce(function(t,r){return t.concat(e[r])},[])},t.runRejectableQueue=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return new mi(function(t,i){!function n(o){if(!(o>=e.length)){var a=dr(e[o])?e[o].apply(e,je(r)):e[o];return!1===a?i("stop"):mi.resolve(a).then(function(){return n(o+1)}).catch(function(e){return i(e||"stop")})}t()}(0)})},t.runStoppableQueue=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return function t(i){return i>=e.length||!1!==(dr(e[i])?e[i].apply(e,je(r)):e[i])&&t(++i)}(0)},t.decodeUTF8=function(e){for(var t=[],r=e,i=0,n=e.length;i<n;)if(r[i]<128)t.push(String.fromCharCode(r[i])),++i;else{if(r[i]<192);else if(r[i]<224){if(gi(r,i,1)){var o=(31&r[i])<<6|63&r[i+1];if(o>=128){t.push(String.fromCharCode(65535&o)),i+=2;continue}}}else if(r[i]<240){if(gi(r,i,2)){var a=(15&r[i])<<12|(63&r[i+1])<<6|63&r[i+2];if(a>=2048&&55296!=(63488&a)){t.push(String.fromCharCode(65535&a)),i+=3;continue}}}else if(r[i]<248&&gi(r,i,3)){var s=(7&r[i])<<18|(63&r[i+1])<<12|(63&r[i+2])<<6|63&r[i+3];if(s>65536&&s<1114112){s-=65536,t.push(String.fromCharCode(s>>>10|55296)),t.push(String.fromCharCode(1023&s|56320)),i+=4;continue}}t.push(String.fromCharCode(65533)),++i}return t.join("")},t.debounce=function(e,t,r){var i=void 0,n=void 0,o=void 0,a=void 0,s=void 0,u=function u(){var c=new Date-a;c<t&&c>=0?i=setTimeout(u,t-c):(i=null,r||(s=e.apply(o,n),i||(o=n=null)))};return function(){o=this,n=arguments,a=new Date;var c=r&&!i;return i||(i=setTimeout(u,t)),c&&(s=e.apply(o,n),o=n=null),s}},t.throttle=function(e,t,r,i){var n=void 0,o=void 0,a=void 0,s=null,u=0;r||(r={});var c=function(){u=!1===r.leading?0:new Date-0,s=null,a=e.apply(n,o),s||(n=o=null)};return t=t||0,function(){var l=new Date;u||!1!==r.leading||(u=l);var d=t-(l-u);return n=i||this,o=arguments,d<=0||d>t?(s&&(clearTimeout(s),s=null),u=l,a=e.apply(n,o),s||(n=o=null)):s||!1===r.trailing||(s=setTimeout(c,d)),a}},t.raf=yi,t.caf=_i,t.strRepeat=bi,t.formatTime=function(e){var t=Math.floor(e/3600);e=Math.floor(e%3600);var r=bi(Math.floor(e/60),2),i=bi(e=Math.floor(e%60),2);return t>=1?t+":"+r+":"+i:r+":"+i},t.appendCSS=function(e){var t=document,r=t.querySelector("style");if(!r){r=t.createElement("style");var i=t.querySelector("head");i&&i.appendChild(r)}return r.appendChild(t.createTextNode(e)),r},t.formatDate=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new Date,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"yyyy-MM-dd hh:mm:ss.i",r=e.getFullYear().toString(),i={M:e.getMonth()+1,d:e.getDate(),h:e.getHours(),m:e.getMinutes(),s:e.getSeconds(),i:e.getMilliseconds()};t=t.replace(/(y+)/gi,function(e,t){return r.substr(4-Math.min(4,t.length))});var n=function(e){t=t.replace(new RegExp("("+e+"+)","g"),function(t,r){return(i[e]<10&&r.length>1?"0":"")+i[e]})};for(var o in i)n(o);return t},t.getLocalStorage=function(e){try{return window.localStorage.getItem(e)}catch(r){try{var t=document.cookie.match(new RegExp("(^| )"+e+"=([^;]*)(;|$)"));return lr(t)?unescape(t[2]):""}catch(e){return""}}},t.setLocalStorage=function(e,t){try{window.localStorage.setItem(e,t)}catch(i){var r=new Date;r.setTime(r.getTime()+2592e7);try{document.cookie=e+"="+escape(t)+";expires="+r.toUTCString()+";path=/;"}catch(e){}}},t.emitEventCache=Li,t.addEventCache=Ri,t.removeEventCache=Ni,t.CustEvent=ji,t.getAttr=Vi,t.setAttr=Yi,t.addClassName=Ki,t.removeClassName=Zi,t.hasClassName=Qi,t.removeEvent=Ji,t.addEvent=en,t.addDelegate=tn,t.removeDelegate=rn,t.getStyle=nn,t.setStyle=on,t.query=an,t.removeEl=sn,t.findParents=un,t.$=cn,t.NodeWrap=ln,Object.defineProperty(t,"__esModule",{value:!0})})(t)}).call(t,r(19))},function(module,exports){var g;g=function(){return this}();try{g=g||Function("return this")()||eval("this")}catch(e){"object"==typeof window&&(g=window)}module.exports=g}]).default},module.exports=factory()}),chimeeKernelFlv=unwrapExports(lib$2);function styleInject(e,t){void 0===t&&(t={});var r=t.insertAt;if(e&&"undefined"!=typeof document){var i=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css","top"===r&&i.firstChild?i.insertBefore(n,i.firstChild):i.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}}var css=".chimee-container container{position:relative;display:block;width:100%;height:100%}.chimee-container video{display:block;width:100%;height:100%;background:#000;outline:0}.chimee-container video:focus{outline:0}.chimee-container chimee-center-state-loading{box-sizing:initial}";styleInject(css);var classCallCheck$2=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},inherits$2=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},possibleConstructorReturn$2=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t};Chimee.install(chimeeControl),Chimee.install(chimeeCenterState),Chimee.install(contextmenuConf),Chimee.install(index$1);var ChimeePlayer=function(e){function t(e){if(classCallCheck$2(this,t),!isObject(e))throw new TypeError("You must pass an Object as config when you new ChimeePlayer");e.plugin=e.plugin||e.plugins,isArray(e.plugin)||(e.plugin=[]);var r=[chimeeControl.name,chimeeCenterState.name,contextmenuConf.name,index$1.name],i=e.plugin.map(function(e){return isObject(e)?e.name:e});r.forEach(function(t){i.indexOf(t)>-1||e.plugin.push(t)}),isObject(e.preset)||(e.preset={hls:Hls,flv:chimeeKernelFlv});var n=possibleConstructorReturn$2(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.on("play",function(){return n.chimeeContextmenu.updatemenu([{text:"暂停",action:"pause"}])}),n.on("pause",function(){return n.chimeeContextmenu.updatemenu([{text:"播放",action:"play"}])}),n}return inherits$2(t,Chimee),t}();return ChimeePlayer.popupFactory=popupFactory,ChimeePlayer});
|
const nodemailer = require('nodemailer')
const pw = process.env.EMAIL_PW || require('../../secrets').pw
const ccEmail = process.env.CC_EMAIL || require('../../secrets').ccEmail
const email = 'yoshis.yodelers@gmail.com'
const sendEmail = (userEmail, order) => {
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: email,
pass: pw
}
})
const mailOptions = {
from: email,
to: `${userEmail}`,
cc: ccEmail,
subject: 'Bass Shopper Order Confirmation!',
text: `Thank you for your order. It will be shipping soon. Order Number: ${order}`
}
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error)
} else {
console.log('Email sent: ' + info.response)
}
})
}
module.exports = sendEmail
|
import HeaderSearch from './HeaderSearch/HeaderSearch';
import Header from './Header/Header';
import HeaderBoard from './HeaderBoard/HeaderBoardContainer';
import HeaderUser from './HeaderUser/HeaderUserContainer';
import BoardsMenu from './BoardsMenu/BoardsMenuContainer';
import PopOver from './PopOver/PopOverContainer';
import BoardOptionsItems from './BoardOptionsItems/BoardOptionsItems';
import BoardOptionsItem from './BoardOptionsItem/BoardOptionsItem';
import BoardOptions from './BoardOptions/BoardOptions';
import Board from './Board/Board';
import BoardItem from './BoardItem/BoardItemContainer';
import Boards from './Boards/BoardsContainer';
import {
CreateOrganization,
CreateBoard
} from './Forms/index';
import Notification from './Notification/Notification';
export {
HeaderSearch,
HeaderBoard,
BoardsMenu,
Header,
HeaderUser,
PopOver,
BoardOptionsItems,
BoardOptionsItem,
BoardOptions,
Board,
BoardItem,
Boards,
CreateOrganization,
CreateBoard,
Notification
}
|
function optionChanged() {
let drop_year = d3.select('#selDataset_year').node().value;
let drop_gender = d3.select('#selDataset_gender').node().value;
// createBarbyGender(drop_year,drop_gender);
createDonut();
createBarbySexualExploit();
console.log(drop_year)
}
createBarbySexualExploit2();
createBarbySexualExploit();
function createBarbySexualExploit() {
let url = ["https://assaultdb.herokuapp.com/gender"]
// let url2 = `/api/${year}/${gender}`
d3.json(url, function (testData) {
// console.log(testData)
let y_select = d3.select('#selDataset_year').node().value;
let g_select = d3.select('#selDataset_gender').node().value;
let filter = testData.filter(y => y.yearOfRegistration === parseInt(y_select) && y.gender === g_select);
let bar2 = d3.select('#bar2')
bar2.html("");
// let yeartest = yearid.filter(i = i.obj === yearselect)[0];
// console.log(test)
let genderM = [];
let yearfemalearray = [];
let yearmalearray = [];
let exploitmale = [];
let exploitfemale = [];
let meansofControlPAM = [];
let meansofControlPAF = [];
let meansofControlPSM = [];
let meansofControlPSF = [];
let meansofControlPsAM = [];
let meansofControlPsAF = [];
let meansofControlRMM = [];
let meansofControlRMF = [];
let meansofControlSAM = [];
let meansofControlSAF = [];
let meansofControlTEM = [];
let meansofControlTEF = [];
let meansofControlToLM = [];
let meansofControlToLF = [];
let meansofControlTM = [];
let meansofControlTF = [];
let meansofControlUCM = [];
let meansofControlUCF = [];
let recFamilyM = [];
let recFamilyF = [];
let recFriendM = [];
let recFriendF = [];
let recRomancM = [];
let recRomancF = [];
let recOtherM = [];
let recOtherF = [];
let genderF = [];
let genderALL = [];
filter.map((testDatum) => {
// console.log(testDatum)
if (testDatum.gender === "Male") {
genderM.push(testDatum.gender);
yearmalearray.push(testDatum.yearOfRegistration);
exploitmale.push(testDatum.isSexualExploit);
meansofControlPAM.push(testDatum.meansOfControlPhysicalAbuse)
meansofControlPSM.push(testDatum.meansOfControlPsychoactiveSubstances)
meansofControlPsAM.push(testDatum.meansOfControlPsychologicalAbuse)
meansofControlRMM.push(testDatum.meansOfControlRestrictsMovement)
meansofControlSAM.push(testDatum.meansOfControlSexualAbuse)
meansofControlTEM.push(testDatum.meansOfControlTakesEarnings)
meansofControlToLM.push(testDatum.meansOfControlThreatOfLawEnforcement)
meansofControlTM.push(testDatum.meansOfControlThreats)
meansofControlUCM.push(testDatum.meansOfControlUsesChildren)
recFamilyM.push(testDatum.recruiterRelationFamily)
recFriendM.push(testDatum.recruiterRelationFriend)
recRomancM.push(testDatum.recruiterRelationIntimatePartner)
recOtherM.push(testDatum.reacruiterRelationOther)
let PAFtrace = {
x: genderF,
y: meansofControlPAF,
name: `# of Physical Abuse ${meansofControlPAF}`,
type: 'bar',
hoverinfo: false
};
let PAFtrace2 = {
x: genderM,
y: meansofControlPAM,
name: `# of Physical Abuse ${meansofControlPAM}`,
type: 'bar',
hoverinfo: false
};
let PStrace = {
x: genderF,
y: meansofControlPSF,
name: `# of Pschoactive Substance Usage ${meansofControlPSF}`,
type: 'bar',
hoverinfo: false
};
let PStrace2 = {
x: genderM,
y: meansofControlPSM,
name: `# of Pschoactive Substance Usage ${meansofControlPSM}`,
type: 'bar',
hoverinfo: false
};
let PsAtrace = {
x: genderF,
y: meansofControlPsAF,
name: `# of Psychological Abuse ${meansofControlPsAF}`,
type: 'bar',
hoverinfo: false
}
let PsAtrace2 = {
x: genderM,
y: meansofControlPsAM,
name: `# of Psychological Abuse ${meansofControlPsAM}`,
type: 'bar',
hoverinfo: false
}
let RMtrace = {
x: genderF,
y: meansofControlRMF,
name: `# of Restriction of Movement ${meansofControlRMF}`,
type: 'bar',
hoverinfo: false
}
let RMtrace2 = {
x: genderM,
y: meansofControlRMM,
name: `# of Restriction of Movement ${meansofControlRMM}`,
type: 'bar',
hoverinfo: false
}
let SAtrace = {
x: genderF,
y: meansofControlSAF,
name: `# of Sexual Abuse ${meansofControlSAF}`,
type: 'bar',
hoverinfo: false
}
let SAtrace2 = {
x: genderM,
y: meansofControlSAM,
name: `# of Sexual Abuse ${meansofControlSAM}`,
type: 'bar',
hoverinfo: false
}
let TEtrace = {
x: genderF,
y: meansofControlTEF,
name: `# of Taking Earnings ${meansofControlTEF}`,
type: 'bar',
hoverinfo: false
}
let TEtrace2 = {
x: genderM,
y: meansofControlTEM,
name: `# of Taking Earnings ${meansofControlTEM}`,
type: 'bar',
hoverinfo: false
}
let ToLtrace = {
x: genderF,
y: meansofControlToLF,
name: `# of Threats of Law Enforcement ${meansofControlToLF}`,
type: 'bar',
hoverinfo: false
}
let ToLtrace2 = {
x: genderM,
y: meansofControlToLM,
name: `# of Threats of Law Enforcement ${meansofControlToLM}`,
type: 'bar',
hoverinfo: false
}
let Ttrace = {
x: genderF,
y: meansofControlTF,
name: `# of Threats (General) ${meansofControlTF}`,
type: 'bar',
hoverinfo: false,
}
let Ttrace2 = {
x: genderM,
y: meansofControlTM,
name: `# of Threats (General) ${meansofControlTM}`,
type: 'bar',
hoverinfo: false
}
let data = [PAFtrace, PStrace, PsAtrace, RMtrace, SAtrace, TEtrace, ToLtrace, Ttrace,
PAFtrace2, PStrace2, PsAtrace2, RMtrace2, SAtrace2, TEtrace2, ToLtrace2, Ttrace2]
let layout = {
// barmode: 'stack',
colorway: ['#f7fbff', '#deebf7', '#c6dbef', '#9ecae1', '#6baed6', '#4292c6', '#2171b5', '#08519c', '#08306b'],
title: `Types of Control for ${g_select} in ${y_select}`,
font: {
family: 'Raleway, sans-serif'
},
showlegend: true,
legend: {
x: 1,
y: 0.5
},
yaxis: {
zeroline: false,
gridwidth: 2
},
bargap: 0.2,
width: 700,
height: 600
};
Plotly.newPlot("bar2", data, layout)
}
else {
genderF.push(testDatum.gender);
yearfemalearray.push(testDatum.yearOfRegistration);
exploitfemale.push(testDatum.isSexualExploit);
meansofControlPAF.push(testDatum.meansOfControlPhysicalAbuse)
meansofControlPSF.push(testDatum.meansOfControlPsychoactiveSubstances)
meansofControlPsAF.push(testDatum.meansOfControlPsychologicalAbuse)
meansofControlRMF.push(testDatum.meansOfControlRestrictsMovement)
meansofControlSAF.push(testDatum.meansOfControlSexualAbuse)
meansofControlTEF.push(testDatum.meansOfControlTakesEarnings)
meansofControlToLF.push(testDatum.meansOfControlThreatOfLawEnforcement)
meansofControlTF.push(testDatum.meansOfControlThreats)
meansofControlUCF.push(testDatum.meansOfControlUsesChildren)
recFamilyF.push(testDatum.recruiterRelationFamily)
recFriendF.push(testDatum.recruiterRelationFriend)
recRomancF.push(testDatum.recruiterRelationIntimatePartner)
recOtherF.push(testDatum.reacruiterRelationOther)
let PAFtrace = {
x: genderF,
y: meansofControlPAF,
name: `# of Physical Abuse ${meansofControlPAF}`,
type: 'bar',
hoverinfo: false
};
let PAFtrace2 = {
x: genderM,
y: meansofControlPAM,
name: `# of Physical Abuse ${meansofControlPAM}`,
type: 'bar',
hoverinfo: false
};
let PStrace = {
x: genderF,
y: meansofControlPSF,
name: `# of Pschoactive Substance Usage ${meansofControlPSF}`,
type: 'bar',
hoverinfo: false
};
let PStrace2 = {
x: genderM,
y: meansofControlPSM,
name: `# of Pschoactive Substance Usage ${meansofControlPSM}`,
type: 'bar',
hoverinfo: false
};
let PsAtrace = {
x: genderF,
y: meansofControlPsAF,
name: `# of Psychological Abuse ${meansofControlPsAF}`,
type: 'bar',
hoverinfo: false
}
let PsAtrace2 = {
x: genderM,
y: meansofControlPsAM,
name: `# of Psychological Abuse ${meansofControlPsAM}`,
type: 'bar',
hoverinfo: false
}
let RMtrace = {
x: genderF,
y: meansofControlRMF,
name: `# of Restriction of Movement ${meansofControlRMF}`,
type: 'bar',
hoverinfo: false
}
let RMtrace2 = {
x: genderM,
y: meansofControlRMM,
name: `# of Restriction of Movement ${meansofControlRMM}`,
type: 'bar',
hoverinfo: false
}
let SAtrace = {
x: genderF,
y: meansofControlSAF,
name: `# of Sexual Abuse ${meansofControlSAF}`,
type: 'bar',
hoverinfo: false
}
let SAtrace2 = {
x: genderM,
y: meansofControlSAM,
name: `# of Sexual Abuse ${meansofControlSAM}`,
type: 'bar',
hoverinfo: false
}
let TEtrace = {
x: genderF,
y: meansofControlTEF,
name: `# of Taking Earnings ${meansofControlTEF}`,
type: 'bar',
hoverinfo: false
}
let TEtrace2 = {
x: genderM,
y: meansofControlTEM,
name: `# of Taking Earnings ${meansofControlTEM}`,
type: 'bar',
hoverinfo: false
}
let ToLtrace = {
x: genderF,
y: meansofControlToLF,
name: `# of Threats of Law Enforcement ${meansofControlToLF}`,
type: 'bar',
hoverinfo: false
}
let ToLtrace2 = {
x: genderM,
y: meansofControlToLM,
name: `# of Threats of Law Enforcement ${meansofControlToLM}`,
type: 'bar',
hoverinfo: false
}
let Ttrace = {
x: genderF,
y: meansofControlTF,
name: `# of Threats (General) ${meansofControlTF}`,
type: 'bar',
hoverinfo: false,
}
let Ttrace2 = {
x: genderM,
y: meansofControlTM,
name: `# of Threats (General) ${meansofControlTM}`,
type: 'bar',
hoverinfo: false
}
let data = [PAFtrace, PStrace, PsAtrace, RMtrace, SAtrace, TEtrace, ToLtrace, Ttrace,
PAFtrace2, PStrace2, PsAtrace2, RMtrace2, SAtrace2, TEtrace2, ToLtrace2, Ttrace2]
let layout = {
// barmode: 'stack',
colorway: ['#f7fbff', '#deebf7', '#c6dbef', '#9ecae1', '#6baed6', '#4292c6', '#2171b5', '#08519c', '#08306b'],
title: `# of Control-Types for ${g_select} in ${y_select}`,
font: {
family: 'Raleway, sans-serif'
},
showlegend: true,
legend: {"orientation": "h"},
margin: {
l: 125,
r: 5,
b: 30,
t: 30,
pad: 0,
},
yaxis: {
zeroline: false,
gridwidth: 2
},
bargap: 0.2,
width: 500,
height: 400
};
Plotly.newPlot("bar2", data, layout)
}
})
})
}
function createBarbySexualExploit2() {
let url = ["https://assaultdb.herokuapp.com/gender"]
// let url2 = `/api/${year}/${gender}`
d3.json(url, function (testData) {
// console.log(testData)
let bar2 = d3.select('#bar2')
bar2.html("");
// let yeartest = yearid.filter(i = i.obj === yearselect)[0];
// console.log(test)
let genderM = [];
let yearfemalearray = [];
let yearmalearray = [];
let exploitmale = [];
let exploitfemale = [];
let genderF = [];
testData.map((testDatum) => {
// console.log(testDatum)
if (testDatum.gender === "Male") {
genderM.push(testDatum.gender);
yearmalearray.push(testDatum.yearOfRegistration);
exploitmale.push(testDatum.isSexualExploit);
}
else {
genderF.push(testDatum.gender);
yearfemalearray.push(testDatum.yearOfRegistration);
exploitfemale.push(testDatum.isSexualExploit);
}
let traceF = {
x: yearfemalearray,
y: exploitfemale,
name: 'Sexual Exploits against Females',
mode: 'lines'
};
let traceM = {
x: yearmalearray,
y: exploitmale,
name: 'Sexual Exploits against Males',
mode: 'lines'
}
let dataexploit = [traceF, traceM]
let layout = {
title: '# of Sexual Exploitation accounts Male & Female',
colorway: ['#08519c', '#08306b'],
xaxis: {
title: "Exploitation 2015 - 2018"
},
showlegend: true,
legend: {
x: 1,
y: 0.5
},
width: 600,
height: 300
};
Plotly.newPlot("bar", dataexploit, layout)
})
})
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const lib_1 = require("../../lib");
const util_1 = require("../util");
test('shows new AssumeRolePolicyDocument', () => {
// WHEN
const diff = lib_1.diffTemplate({}, util_1.template({
MyRole: util_1.role({
AssumeRolePolicyDocument: util_1.poldoc({
Action: 'sts:AssumeRole',
Effect: 'Allow',
Principal: { Service: 'lambda.amazonaws.com' },
}),
}),
}));
// THEN
expect(diff.iamChanges.toJson()).toEqual({
statementAdditions: [
{
effect: 'Allow',
resources: { not: false, values: ['${MyRole.Arn}'] },
principals: { not: false, values: ['Service:lambda.amazonaws.com'] },
actions: { not: false, values: ['sts:AssumeRole'] },
},
],
});
});
test('implicitly knows principal of identity policy for all resource types', () => {
for (const attr of ['Roles', 'Users', 'Groups']) {
// WHEN
const diff = lib_1.diffTemplate({}, util_1.template({
MyPolicy: util_1.policy({
[attr]: [{ Ref: 'MyRole' }],
PolicyDocument: util_1.poldoc({
Effect: 'Allow',
Action: 's3:DoThatThing',
Resource: '*',
}),
}),
}));
// THEN
expect(diff.iamChanges.toJson()).toEqual({
statementAdditions: [
{
effect: 'Allow',
resources: { not: false, values: ['*'] },
principals: { not: false, values: ['AWS:${MyRole}'] },
actions: { not: false, values: ['s3:DoThatThing'] },
},
],
});
}
});
test('policies on an identity object', () => {
for (const resourceType of ['Role', 'User', 'Group']) {
// WHEN
const diff = lib_1.diffTemplate({}, util_1.template({
MyIdentity: util_1.resource(`AWS::IAM::${resourceType}`, {
Policies: [
{
PolicyName: 'Polly',
PolicyDocument: util_1.poldoc({
Effect: 'Allow',
Action: 's3:DoThatThing',
Resource: '*',
}),
},
],
}),
}));
// THEN
expect(diff.iamChanges.toJson()).toEqual({
statementAdditions: [
{
effect: 'Allow',
resources: { not: false, values: ['*'] },
principals: { not: false, values: ['AWS:${MyIdentity}'] },
actions: { not: false, values: ['s3:DoThatThing'] },
},
],
});
}
});
test('if policy is attached to multiple roles all are shown', () => {
// WHEN
const diff = lib_1.diffTemplate({}, util_1.template({
MyPolicy: util_1.policy({
Roles: [{ Ref: 'MyRole' }, { Ref: 'ThyRole' }],
PolicyDocument: util_1.poldoc({
Effect: 'Allow',
Action: 's3:DoThatThing',
Resource: '*',
}),
}),
}));
// THEN
expect(diff.iamChanges.toJson()).toEqual({
statementAdditions: [
{
effect: 'Allow',
resources: { not: false, values: ['*'] },
principals: { not: false, values: ['AWS:${MyRole}'] },
actions: { not: false, values: ['s3:DoThatThing'] },
},
{
effect: 'Allow',
resources: { not: false, values: ['*'] },
principals: { not: false, values: ['AWS:${ThyRole}'] },
actions: { not: false, values: ['s3:DoThatThing'] },
},
],
});
});
test('correctly parses Lambda permissions', () => {
// WHEN
const diff = lib_1.diffTemplate({}, util_1.template({
MyPermission: util_1.resource('AWS::Lambda::Permission', {
Action: 'lambda:InvokeFunction',
FunctionName: { Ref: 'MyFunction' },
Principal: 's3.amazonaws.com',
SourceAccount: { Ref: 'AWS::AccountId' },
SourceArn: { 'Fn::GetAtt': ['MyBucketF68F3FF0', 'Arn'] },
}),
}));
// THEN
expect(diff.iamChanges.toJson()).toEqual({
statementAdditions: [
{
effect: 'Allow',
resources: { not: false, values: ['${MyFunction}'] },
principals: { not: false, values: ['Service:s3.amazonaws.com'] },
actions: { not: false, values: ['lambda:InvokeFunction'] },
condition: {
StringEquals: { 'AWS:SourceAccount': '${AWS::AccountId}' },
ArnLike: { 'AWS:SourceArn': '${MyBucketF68F3FF0.Arn}' },
},
},
],
});
});
test('implicitly knows resource of (queue) resource policy even if * given', () => {
// WHEN
const diff = lib_1.diffTemplate({}, util_1.template({
QueuePolicy: util_1.resource('AWS::SQS::QueuePolicy', {
Queues: [{ Ref: 'MyQueue' }],
PolicyDocument: util_1.poldoc({
Effect: 'Allow',
Action: 'sqs:SendMessage',
Resource: '*',
Principal: { Service: 'sns.amazonaws.com' },
}),
}),
}));
// THEN
expect(diff.iamChanges.toJson()).toEqual({
statementAdditions: [
{
effect: 'Allow',
resources: { not: false, values: ['${MyQueue}'] },
principals: { not: false, values: ['Service:sns.amazonaws.com'] },
actions: { not: false, values: ['sqs:SendMessage'] },
},
],
});
});
test('finds sole statement removals', () => {
// WHEN
const diff = lib_1.diffTemplate(util_1.template({
BucketPolicy: util_1.resource('AWS::S3::BucketPolicy', {
Bucket: { Ref: 'MyBucket' },
PolicyDocument: util_1.poldoc({
Effect: 'Allow',
Action: 's3:PutObject',
Resource: '*',
Principal: { AWS: 'me' },
}),
}),
}), {});
// THEN
expect(diff.iamChanges.toJson()).toEqual({
statementRemovals: [
{
effect: 'Allow',
resources: { not: false, values: ['${MyBucket}'] },
principals: { not: false, values: ['AWS:me'] },
actions: { not: false, values: ['s3:PutObject'] },
},
],
});
});
test('finds one of many statement removals', () => {
// WHEN
const diff = lib_1.diffTemplate(util_1.template({
BucketPolicy: util_1.resource('AWS::S3::BucketPolicy', {
Bucket: { Ref: 'MyBucket' },
PolicyDocument: util_1.poldoc({
Effect: 'Allow',
Action: 's3:PutObject',
Resource: '*',
Principal: { AWS: 'me' },
}, {
Effect: 'Allow',
Action: 's3:LookAtObject',
Resource: '*',
Principal: { AWS: 'me' },
}),
}),
}), util_1.template({
BucketPolicy: util_1.resource('AWS::S3::BucketPolicy', {
Bucket: { Ref: 'MyBucket' },
PolicyDocument: util_1.poldoc({
Effect: 'Allow',
Action: 's3:LookAtObject',
Resource: '*',
Principal: { AWS: 'me' },
}),
}),
}));
// THEN
expect(diff.iamChanges.toJson()).toEqual({
statementRemovals: [
{
effect: 'Allow',
resources: { not: false, values: ['${MyBucket}'] },
principals: { not: false, values: ['AWS:me'] },
actions: { not: false, values: ['s3:PutObject'] },
},
],
});
});
test('finds policy attachments', () => {
// WHEN
const diff = lib_1.diffTemplate({}, util_1.template({
SomeRole: util_1.resource('AWS::IAM::Role', {
ManagedPolicyArns: ['arn:policy'],
}),
}));
// THEN
expect(diff.iamChanges.toJson()).toEqual({
managedPolicyAdditions: [
{
identityArn: '${SomeRole}',
managedPolicyArn: 'arn:policy',
},
],
});
});
test('finds policy removals', () => {
// WHEN
const diff = lib_1.diffTemplate(util_1.template({
SomeRole: util_1.resource('AWS::IAM::Role', {
ManagedPolicyArns: ['arn:policy', 'arn:policy2'],
}),
}), util_1.template({
SomeRole: util_1.resource('AWS::IAM::Role', {
ManagedPolicyArns: ['arn:policy2'],
}),
}));
// THEN
expect(diff.iamChanges.toJson()).toEqual({
managedPolicyRemovals: [
{
identityArn: '${SomeRole}',
managedPolicyArn: 'arn:policy',
},
],
});
});
test('queuepolicy queue change counts as removal+addition', () => {
// WHEN
const diff = lib_1.diffTemplate(util_1.template({
QueuePolicy: util_1.resource('AWS::SQS::QueuePolicy', {
Queues: [{ Ref: 'MyQueue1' }],
PolicyDocument: util_1.poldoc({
Effect: 'Allow',
Action: 'sqs:SendMessage',
Resource: '*',
Principal: { Service: 'sns.amazonaws.com' },
}),
}),
}), util_1.template({
QueuePolicy: util_1.resource('AWS::SQS::QueuePolicy', {
Queues: [{ Ref: 'MyQueue2' }],
PolicyDocument: util_1.poldoc({
Effect: 'Allow',
Action: 'sqs:SendMessage',
Resource: '*',
Principal: { Service: 'sns.amazonaws.com' },
}),
}),
}));
// THEN
expect(diff.iamChanges.toJson()).toEqual({
statementAdditions: [
{
effect: 'Allow',
resources: { not: false, values: ['${MyQueue2}'] },
principals: { not: false, values: ['Service:sns.amazonaws.com'] },
actions: { not: false, values: ['sqs:SendMessage'] },
},
],
statementRemovals: [
{
effect: 'Allow',
resources: { not: false, values: ['${MyQueue1}'] },
principals: { not: false, values: ['Service:sns.amazonaws.com'] },
actions: { not: false, values: ['sqs:SendMessage'] },
},
],
});
});
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGV0ZWN0LWNoYW5nZXMudGVzdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbImRldGVjdC1jaGFuZ2VzLnRlc3QudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxtQ0FBeUM7QUFDekMsa0NBQW1FO0FBRW5FLElBQUksQ0FBQyxvQ0FBb0MsRUFBRSxHQUFHLEVBQUU7SUFDOUMsT0FBTztJQUNQLE1BQU0sSUFBSSxHQUFHLGtCQUFZLENBQUMsRUFBRSxFQUFFLGVBQVEsQ0FBQztRQUNyQyxNQUFNLEVBQUUsV0FBSSxDQUFDO1lBQ1gsd0JBQXdCLEVBQUUsYUFBTSxDQUFDO2dCQUMvQixNQUFNLEVBQUUsZ0JBQWdCO2dCQUN4QixNQUFNLEVBQUUsT0FBTztnQkFDZixTQUFTLEVBQUUsRUFBRSxPQUFPLEVBQUUsc0JBQXNCLEVBQUU7YUFDL0MsQ0FBQztTQUNILENBQUM7S0FDSCxDQUFDLENBQUMsQ0FBQztJQUVKLE9BQU87SUFDUCxNQUFNLENBQUMsSUFBSSxDQUFDLFVBQVUsQ0FBQyxNQUFNLEVBQUUsQ0FBQyxDQUFDLE9BQU8sQ0FBQztRQUN2QyxrQkFBa0IsRUFBRTtZQUNsQjtnQkFDRSxNQUFNLEVBQUUsT0FBTztnQkFDZixTQUFTLEVBQUUsRUFBRSxHQUFHLEVBQUUsS0FBSyxFQUFFLE1BQU0sRUFBRSxDQUFFLGVBQWUsQ0FBRSxFQUFFO2dCQUN0RCxVQUFVLEVBQUUsRUFBRSxHQUFHLEVBQUUsS0FBSyxFQUFFLE1BQU0sRUFBRSxDQUFFLDhCQUE4QixDQUFFLEVBQUU7Z0JBQ3RFLE9BQU8sRUFBRSxFQUFFLEdBQUcsRUFBRSxLQUFLLEVBQUUsTUFBTSxFQUFFLENBQUUsZ0JBQWdCLENBQUUsRUFBRTthQUN0RDtTQUNGO0tBQ0YsQ0FBQyxDQUFDO0FBQ0wsQ0FBQyxDQUFDLENBQUM7QUFFSCxJQUFJLENBQUMsc0VBQXNFLEVBQUUsR0FBRyxFQUFFO0lBQ2hGLEtBQUssTUFBTSxJQUFJLElBQUksQ0FBQyxPQUFPLEVBQUUsT0FBTyxFQUFFLFFBQVEsQ0FBQyxFQUFFO1FBQy9DLE9BQU87UUFDUCxNQUFNLElBQUksR0FBRyxrQkFBWSxDQUFDLEVBQUUsRUFBRSxlQUFRLENBQUM7WUFDckMsUUFBUSxFQUFFLGFBQU0sQ0FBQztnQkFDZixDQUFDLElBQUksQ0FBQyxFQUFFLENBQUMsRUFBRSxHQUFHLEVBQUUsUUFBUSxFQUFFLENBQUM7Z0JBQzNCLGNBQWMsRUFBRSxhQUFNLENBQUM7b0JBQ3JCLE1BQU0sRUFBRSxPQUFPO29CQUNmLE1BQU0sRUFBRSxnQkFBZ0I7b0JBQ3hCLFFBQVEsRUFBRSxHQUFHO2lCQUNkLENBQUM7YUFDSCxDQUFDO1NBQ0gsQ0FBQyxDQUFDLENBQUM7UUFFSixPQUFPO1FBQ1AsTUFBTSxDQUFDLElBQUksQ0FBQyxVQUFVLENBQUMsTUFBTSxFQUFFLENBQUMsQ0FBQyxPQUFPLENBQUM7WUFDdkMsa0JBQWtCLEVBQUU7Z0JBQ2xCO29CQUNFLE1BQU0sRUFBRSxPQUFPO29CQUNmLFNBQVMsRUFBRSxFQUFFLEdBQUcsRUFBRSxLQUFLLEVBQUUsTUFBTSxFQUFFLENBQUUsR0FBRyxDQUFFLEVBQUU7b0JBQzFDLFVBQVUsRUFBRSxFQUFFLEdBQUcsRUFBRSxLQUFLLEVBQUUsTUFBTSxFQUFFLENBQUUsZUFBZSxDQUFFLEVBQUU7b0JBQ3ZELE9BQU8sRUFBRSxFQUFFLEdBQUcsRUFBRSxLQUFLLEVBQUUsTUFBTSxFQUFFLENBQUUsZ0JBQWdCLENBQUUsRUFBRTtpQkFDdEQ7YUFDRjtTQUNGLENBQUMsQ0FBQztLQUNKO0FBQ0gsQ0FBQyxDQUFDLENBQUM7QUFFSCxJQUFJLENBQUMsZ0NBQWdDLEVBQUUsR0FBRyxFQUFFO0lBQzFDLEtBQUssTUFBTSxZQUFZLElBQUksQ0FBQyxNQUFNLEVBQUUsTUFBTSxFQUFFLE9BQU8sQ0FBQyxFQUFFO1FBQ3BELE9BQU87UUFDUCxNQUFNLElBQUksR0FBRyxrQkFBWSxDQUFDLEVBQUUsRUFBRSxlQUFRLENBQUM7WUFDckMsVUFBVSxFQUFFLGVBQVEsQ0FBQyxhQUFhLFlBQVksRUFBRSxFQUFFO2dCQUNoRCxRQUFRLEVBQUU7b0JBQ1I7d0JBQ0UsVUFBVSxFQUFFLE9BQU87d0JBQ25CLGNBQWMsRUFBRSxhQUFNLENBQUM7NEJBQ3JCLE1BQU0sRUFBRSxPQUFPOzRCQUNmLE1BQU0sRUFBRSxnQkFBZ0I7NEJBQ3hCLFFBQVEsRUFBRSxHQUFHO3lCQUNkLENBQUM7cUJBQ0g7aUJBQ0Y7YUFDRixDQUFDO1NBQ0gsQ0FBQyxDQUFDLENBQUM7UUFFSixPQUFPO1FBQ1AsTUFBTSxDQUFDLElBQUksQ0FBQyxVQUFVLENBQUMsTUFBTSxFQUFFLENBQUMsQ0FBQyxPQUFPLENBQUM7WUFDdkMsa0JBQWtCLEVBQUU7Z0JBQ2xCO29CQUNFLE1BQU0sRUFBRSxPQUFPO29CQUNmLFNBQVMsRUFBRSxFQUFFLEdBQUcsRUFBRSxLQUFLLEVBQUUsTUFBTSxFQUFFLENBQUUsR0FBRyxDQUFFLEVBQUU7b0JBQzFDLFVBQVUsRUFBRSxFQUFFLEdBQUcsRUFBRSxLQUFLLEVBQUUsTUFBTSxFQUFFLENBQUUsbUJBQW1CLENBQUUsRUFBRTtvQkFDM0QsT0FBTyxFQUFFLEVBQUUsR0FBRyxFQUFFLEtBQUssRUFBRSxNQUFNLEVBQUUsQ0FBRSxnQkFBZ0IsQ0FBRSxFQUFFO2lCQUN0RDthQUNGO1NBQ0YsQ0FBQyxDQUFDO0tBQ0o7QUFDSCxDQUFDLENBQUMsQ0FBQztBQUVILElBQUksQ0FBQyx1REFBdUQsRUFBRSxHQUFHLEVBQUU7SUFDakUsT0FBTztJQUNQLE1BQU0sSUFBSSxHQUFHLGtCQUFZLENBQUMsRUFBRSxFQUFFLGVBQVEsQ0FBQztRQUNyQyxRQUFRLEVBQUUsYUFBTSxDQUFDO1lBQ2YsS0FBSyxFQUFFLENBQUMsRUFBRSxHQUFHLEVBQUUsUUFBUSxFQUFFLEVBQUUsRUFBRSxHQUFHLEVBQUUsU0FBUyxFQUFFLENBQUM7WUFDOUMsY0FBYyxFQUFFLGFBQU0sQ0FBQztnQkFDckIsTUFBTSxFQUFFLE9BQU87Z0JBQ2YsTUFBTSxFQUFFLGdCQUFnQjtnQkFDeEIsUUFBUSxFQUFFLEdBQUc7YUFDZCxDQUFDO1NBQ0gsQ0FBQztLQUNILENBQUMsQ0FBQyxDQUFDO0lBRUosT0FBTztJQUNQLE1BQU0sQ0FBQyxJQUFJLENBQUMsVUFBVSxDQUFDLE1BQU0sRUFBRSxDQUFDLENBQUMsT0FBTyxDQUFDO1FBQ3ZDLGtCQUFrQixFQUFFO1lBQ2xCO2dCQUNFLE1BQU0sRUFBRSxPQUFPO2dCQUNmLFNBQVMsRUFBRSxFQUFFLEdBQUcsRUFBRSxLQUFLLEVBQUUsTUFBTSxFQUFFLENBQUUsR0FBRyxDQUFFLEVBQUU7Z0JBQzFDLFVBQVUsRUFBRSxFQUFFLEdBQUcsRUFBRSxLQUFLLEVBQUUsTUFBTSxFQUFFLENBQUUsZUFBZSxDQUFFLEVBQUU7Z0JBQ3ZELE9BQU8sRUFBRSxFQUFFLEdBQUcsRUFBRSxLQUFLLEVBQUUsTUFBTSxFQUFFLENBQUUsZ0JBQWdCLENBQUUsRUFBRTthQUN0RDtZQUNEO2dCQUNFLE1BQU0sRUFBRSxPQUFPO2dCQUNmLFNBQVMsRUFBRSxFQUFFLEdBQUcsRUFBRSxLQUFLLEVBQUUsTUFBTSxFQUFFLENBQUUsR0FBRyxDQUFFLEVBQUU7Z0JBQzFDLFVBQVUsRUFBRSxFQUFFLEdBQUcsRUFBRSxLQUFLLEVBQUUsTUFBTSxFQUFFLENBQUUsZ0JBQWdCLENBQUUsRUFBRTtnQkFDeEQsT0FBTyxFQUFFLEVBQUUsR0FBRyxFQUFFLEtBQUssRUFBRSxNQUFNLEVBQUUsQ0FBRSxnQkFBZ0IsQ0FBRSxFQUFFO2FBQ3REO1NBQ0Y7S0FDRixDQUFDLENBQUM7QUFDTCxDQUFDLENBQUMsQ0FBQztBQUVILElBQUksQ0FBQyxxQ0FBcUMsRUFBRSxHQUFHLEVBQUU7SUFDL0MsT0FBTztJQUNQLE1BQU0sSUFBSSxHQUFHLGtCQUFZLENBQUMsRUFBRSxFQUFFLGVBQVEsQ0FBQztRQUNyQyxZQUFZLEVBQUUsZUFBUSxDQUFDLHlCQUF5QixFQUFFO1lBQ2hELE1BQU0sRUFBRSx1QkFBdUI7WUFDL0IsWUFBWSxFQUFFLEVBQUUsR0FBRyxFQUFFLFlBQVksRUFBRTtZQUNuQyxTQUFTLEVBQUUsa0JBQWtCO1lBQzdCLGFBQWEsRUFBRSxFQUFDLEdBQUcsRUFBRSxnQkFBZ0IsRUFBRTtZQUN2QyxTQUFTLEVBQUUsRUFBQyxZQUFZLEVBQUUsQ0FBQyxrQkFBa0IsRUFBRSxLQUFLLENBQUMsRUFBQztTQUN2RCxDQUFDO0tBQ0gsQ0FBQyxDQUFDLENBQUM7SUFFSixPQUFPO0lBQ1AsTUFBTSxDQUFDLElBQUksQ0FBQyxVQUFVLENBQUMsTUFBTSxFQUFFLENBQUMsQ0FBQyxPQUFPLENBQUM7UUFDdkMsa0JBQWtCLEVBQUU7WUFDbEI7Z0JBQ0UsTUFBTSxFQUFFLE9BQU87Z0JBQ2YsU0FBUyxFQUFFLEVBQUUsR0FBRyxFQUFFLEtBQUssRUFBRSxNQUFNLEVBQUUsQ0FBRSxlQUFlLENBQUUsRUFBRTtnQkFDdEQsVUFBVSxFQUFFLEVBQUUsR0FBRyxFQUFFLEtBQUssRUFBRSxNQUFNLEVBQUUsQ0FBRSwwQkFBMEIsQ0FBRSxFQUFFO2dCQUNsRSxPQUFPLEVBQUUsRUFBRSxHQUFHLEVBQUUsS0FBSyxFQUFFLE1BQU0sRUFBRSxDQUFFLHVCQUF1QixDQUFFLEVBQUU7Z0JBQzVELFNBQVMsRUFBRTtvQkFDVCxZQUFZLEVBQUUsRUFBRSxtQkFBbUIsRUFBRSxtQkFBbUIsRUFBRTtvQkFDMUQsT0FBTyxFQUFFLEVBQUUsZUFBZSxFQUFFLHlCQUF5QixFQUFFO2lCQUN4RDthQUNGO1NBQ0Y7S0FDRixDQUFDLENBQUM7QUFDTCxDQUFDLENBQUMsQ0FBQztBQUVILElBQUksQ0FBQyxzRUFBc0UsRUFBRSxHQUFHLEVBQUU7SUFDaEYsT0FBTztJQUNQLE1BQU0sSUFBSSxHQUFHLGtCQUFZLENBQUMsRUFBRSxFQUFFLGVBQVEsQ0FBQztRQUNyQyxXQUFXLEVBQUUsZUFBUSxDQUFDLHVCQUF1QixFQUFFO1lBQzdDLE1BQU0sRUFBRSxDQUFFLEVBQUUsR0FBRyxFQUFFLFNBQVMsRUFBRSxDQUFFO1lBQzlCLGNBQWMsRUFBRSxhQUFNLENBQUM7Z0JBQ3JCLE1BQU0sRUFBRSxPQUFPO2dCQUNmLE1BQU0sRUFBRSxpQkFBaUI7Z0JBQ3pCLFFBQVEsRUFBRSxHQUFHO2dCQUNiLFNBQVMsRUFBRSxFQUFFLE9BQU8sRUFBRSxtQkFBbUIsRUFBRTthQUM1QyxDQUFDO1NBQ0gsQ0FBQztLQUNILENBQUMsQ0FBQyxDQUFDO0lBRUosT0FBTztJQUNQLE1BQU0sQ0FBQyxJQUFJLENBQUMsVUFBVSxDQUFDLE1BQU0sRUFBRSxDQUFDLENBQUMsT0FBTyxDQUFDO1FBQ3ZDLGtCQUFrQixFQUFFO1lBQ2xCO2dCQUNFLE1BQU0sRUFBRSxPQUFPO2dCQUNmLFNBQVMsRUFBRSxFQUFFLEdBQUcsRUFBRSxLQUFLLEVBQUUsTUFBTSxFQUFFLENBQUUsWUFBWSxDQUFFLEVBQUU7Z0JBQ25ELFVBQVUsRUFBRSxFQUFFLEdBQUcsRUFBRSxLQUFLLEVBQUUsTUFBTSxFQUFFLENBQUUsMkJBQTJCLENBQUUsRUFBRTtnQkFDbkUsT0FBTyxFQUFFLEVBQUUsR0FBRyxFQUFFLEtBQUssRUFBRSxNQUFNLEVBQUUsQ0FBRSxpQkFBaUIsQ0FBRSxFQUFFO2FBQ3ZEO1NBQ0Y7S0FDRixDQUFDLENBQUM7QUFDTCxDQUFDLENBQUMsQ0FBQztBQUVILElBQUksQ0FBQywrQkFBK0IsRUFBRSxHQUFHLEVBQUU7SUFDekMsT0FBTztJQUNQLE1BQU0sSUFBSSxHQUFHLGtCQUFZLENBQUMsZUFBUSxDQUFDO1FBQ2pDLFlBQVksRUFBRSxlQUFRLENBQUMsdUJBQXVCLEVBQUU7WUFDOUMsTUFBTSxFQUFFLEVBQUUsR0FBRyxFQUFFLFVBQVUsRUFBRTtZQUMzQixjQUFjLEVBQUUsYUFBTSxDQUFDO2dCQUNyQixNQUFNLEVBQUUsT0FBTztnQkFDZixNQUFNLEVBQUUsY0FBYztnQkFDdEIsUUFBUSxFQUFFLEdBQUc7Z0JBQ2IsU0FBUyxFQUFFLEVBQUUsR0FBRyxFQUFFLElBQUksRUFBRTthQUN6QixDQUFDO1NBQ0gsQ0FBQztLQUNILENBQUMsRUFBRSxFQUFFLENBQUMsQ0FBQztJQUVSLE9BQU87SUFDUCxNQUFNLENBQUMsSUFBSSxDQUFDLFVBQVUsQ0FBQyxNQUFNLEVBQUUsQ0FBQyxDQUFDLE9BQU8sQ0FBQztRQUN2QyxpQkFBaUIsRUFBRTtZQUNqQjtnQkFDRSxNQUFNLEVBQUUsT0FBTztnQkFDZixTQUFTLEVBQUUsRUFBRSxHQUFHLEVBQUUsS0FBSyxFQUFFLE1BQU0sRUFBRSxDQUFFLGFBQWEsQ0FBRSxFQUFFO2dCQUNwRCxVQUFVLEVBQUUsRUFBRSxHQUFHLEVBQUUsS0FBSyxFQUFFLE1BQU0sRUFBRSxDQUFFLFFBQVEsQ0FBRSxFQUFFO2dCQUNoRCxPQUFPLEVBQUUsRUFBRSxHQUFHLEVBQUUsS0FBSyxFQUFFLE1BQU0sRUFBRSxDQUFFLGNBQWMsQ0FBRSxFQUFFO2FBQ3BEO1NBQ0Y7S0FDRixDQUFDLENBQUM7QUFDTCxDQUFDLENBQUMsQ0FBQztBQUVILElBQUksQ0FBQyxzQ0FBc0MsRUFBRSxHQUFHLEVBQUU7SUFDaEQsT0FBTztJQUNQLE1BQU0sSUFBSSxHQUFHLGtCQUFZLENBQ3ZCLGVBQVEsQ0FBQztRQUNQLFlBQVksRUFBRSxlQUFRLENBQUMsdUJBQXVCLEVBQUU7WUFDOUMsTUFBTSxFQUFFLEVBQUUsR0FBRyxFQUFFLFVBQVUsRUFBRTtZQUMzQixjQUFjLEVBQUUsYUFBTSxDQUFDO2dCQUNyQixNQUFNLEVBQUUsT0FBTztnQkFDZixNQUFNLEVBQUUsY0FBYztnQkFDdEIsUUFBUSxFQUFFLEdBQUc7Z0JBQ2IsU0FBUyxFQUFFLEVBQUUsR0FBRyxFQUFFLElBQUksRUFBRTthQUN6QixFQUFFO2dCQUNELE1BQU0sRUFBRSxPQUFPO2dCQUNmLE1BQU0sRUFBRSxpQkFBaUI7Z0JBQ3pCLFFBQVEsRUFBRSxHQUFHO2dCQUNiLFNBQVMsRUFBRSxFQUFFLEdBQUcsRUFBRSxJQUFJLEVBQUU7YUFDekIsQ0FBQztTQUNILENBQUM7S0FDSCxDQUFDLEVBQ0YsZUFBUSxDQUFDO1FBQ1AsWUFBWSxFQUFFLGVBQVEsQ0FBQyx1QkFBdUIsRUFBRTtZQUM5QyxNQUFNLEVBQUUsRUFBRSxHQUFHLEVBQUUsVUFBVSxFQUFFO1lBQzNCLGNBQWMsRUFBRSxhQUFNLENBQUM7Z0JBQ3JCLE1BQU0sRUFBRSxPQUFPO2dCQUNmLE1BQU0sRUFBRSxpQkFBaUI7Z0JBQ3pCLFFBQVEsRUFBRSxHQUFHO2dCQUNiLFNBQVMsRUFBRSxFQUFFLEdBQUcsRUFBRSxJQUFJLEVBQUU7YUFDekIsQ0FBQztTQUNILENBQUM7S0FDSCxDQUFDLENBQUMsQ0FBQztJQUVOLE9BQU87SUFDUCxNQUFNLENBQUMsSUFBSSxDQUFDLFVBQVUsQ0FBQyxNQUFNLEVBQUUsQ0FBQyxDQUFDLE9BQU8sQ0FBQztRQUN2QyxpQkFBaUIsRUFBRTtZQUNqQjtnQkFDRSxNQUFNLEVBQUUsT0FBTztnQkFDZixTQUFTLEVBQUUsRUFBRSxHQUFHLEVBQUUsS0FBSyxFQUFFLE1BQU0sRUFBRSxDQUFFLGFBQWEsQ0FBRSxFQUFFO2dCQUNwRCxVQUFVLEVBQUUsRUFBRSxHQUFHLEVBQUUsS0FBSyxFQUFFLE1BQU0sRUFBRSxDQUFFLFFBQVEsQ0FBRSxFQUFFO2dCQUNoRCxPQUFPLEVBQUUsRUFBRSxHQUFHLEVBQUUsS0FBSyxFQUFFLE1BQU0sRUFBRSxDQUFFLGNBQWMsQ0FBRSxFQUFFO2FBQ3BEO1NBQ0Y7S0FDRixDQUFDLENBQUM7QUFDTCxDQUFDLENBQUMsQ0FBQztBQUVILElBQUksQ0FBQywwQkFBMEIsRUFBRSxHQUFHLEVBQUU7SUFDcEMsT0FBTztJQUNQLE1BQU0sSUFBSSxHQUFHLGtCQUFZLENBQUMsRUFBRSxFQUFFLGVBQVEsQ0FBQztRQUNyQyxRQUFRLEVBQUUsZUFBUSxDQUFDLGdCQUFnQixFQUFFO1lBQ25DLGlCQUFpQixFQUFFLENBQUMsWUFBWSxDQUFDO1NBQ2xDLENBQUM7S0FDSCxDQUFDLENBQUMsQ0FBQztJQUVKLE9BQU87SUFDUCxNQUFNLENBQUMsSUFBSSxDQUFDLFVBQVUsQ0FBQyxNQUFNLEVBQUUsQ0FBQyxDQUFDLE9BQU8sQ0FBQztRQUN2QyxzQkFBc0IsRUFBRTtZQUN0QjtnQkFDRSxXQUFXLEVBQUUsYUFBYTtnQkFDMUIsZ0JBQWdCLEVBQUUsWUFBWTthQUMvQjtTQUNGO0tBQ0YsQ0FBQyxDQUFDO0FBQ0wsQ0FBQyxDQUFDLENBQUM7QUFFSCxJQUFJLENBQUMsdUJBQXVCLEVBQUUsR0FBRyxFQUFFO0lBQ2pDLE9BQU87SUFDUCxNQUFNLElBQUksR0FBRyxrQkFBWSxDQUN2QixlQUFRLENBQUM7UUFDUCxRQUFRLEVBQUUsZUFBUSxDQUFDLGdCQUFnQixFQUFFO1lBQ25DLGlCQUFpQixFQUFFLENBQUMsWUFBWSxFQUFFLGFBQWEsQ0FBQztTQUNqRCxDQUFDO0tBQ0gsQ0FBQyxFQUNGLGVBQVEsQ0FBQztRQUNQLFFBQVEsRUFBRSxlQUFRLENBQUMsZ0JBQWdCLEVBQUU7WUFDbkMsaUJBQWlCLEVBQUUsQ0FBQyxhQUFhLENBQUM7U0FDbkMsQ0FBQztLQUNILENBQUMsQ0FBQyxDQUFDO0lBRU4sT0FBTztJQUNQLE1BQU0sQ0FBQyxJQUFJLENBQUMsVUFBVSxDQUFDLE1BQU0sRUFBRSxDQUFDLENBQUMsT0FBTyxDQUFDO1FBQ3ZDLHFCQUFxQixFQUFFO1lBQ3JCO2dCQUNFLFdBQVcsRUFBRSxhQUFhO2dCQUMxQixnQkFBZ0IsRUFBRSxZQUFZO2FBQy9CO1NBQ0Y7S0FDRixDQUFDLENBQUM7QUFDTCxDQUFDLENBQUMsQ0FBQztBQUVILElBQUksQ0FBQyxxREFBcUQsRUFBRSxHQUFHLEVBQUU7SUFDL0QsT0FBTztJQUNQLE1BQU0sSUFBSSxHQUFHLGtCQUFZLENBQUMsZUFBUSxDQUFDO1FBQ2pDLFdBQVcsRUFBRSxlQUFRLENBQUMsdUJBQXVCLEVBQUU7WUFDN0MsTUFBTSxFQUFFLENBQUUsRUFBRSxHQUFHLEVBQUUsVUFBVSxFQUFFLENBQUU7WUFDL0IsY0FBYyxFQUFFLGFBQU0sQ0FBQztnQkFDckIsTUFBTSxFQUFFLE9BQU87Z0JBQ2YsTUFBTSxFQUFFLGlCQUFpQjtnQkFDekIsUUFBUSxFQUFFLEdBQUc7Z0JBQ2IsU0FBUyxFQUFFLEVBQUUsT0FBTyxFQUFFLG1CQUFtQixFQUFFO2FBQzVDLENBQUM7U0FDSCxDQUFDO0tBQ0gsQ0FBQyxFQUFFLGVBQVEsQ0FBQztRQUNYLFdBQVcsRUFBRSxlQUFRLENBQUMsdUJBQXVCLEVBQUU7WUFDN0MsTUFBTSxFQUFFLENBQUUsRUFBRSxHQUFHLEVBQUUsVUFBVSxFQUFFLENBQUU7WUFDL0IsY0FBYyxFQUFFLGFBQU0sQ0FBQztnQkFDckIsTUFBTSxFQUFFLE9BQU87Z0JBQ2YsTUFBTSxFQUFFLGlCQUFpQjtnQkFDekIsUUFBUSxFQUFFLEdBQUc7Z0JBQ2IsU0FBUyxFQUFFLEVBQUUsT0FBTyxFQUFFLG1CQUFtQixFQUFFO2FBQzVDLENBQUM7U0FDSCxDQUFDO0tBQ0gsQ0FBQyxDQUFDLENBQUM7SUFFSixPQUFPO0lBQ1AsTUFBTSxDQUFDLElBQUksQ0FBQyxVQUFVLENBQUMsTUFBTSxFQUFFLENBQUMsQ0FBQyxPQUFPLENBQUM7UUFDdkMsa0JBQWtCLEVBQUU7WUFDbEI7Z0JBQ0UsTUFBTSxFQUFFLE9BQU87Z0JBQ2YsU0FBUyxFQUFFLEVBQUUsR0FBRyxFQUFFLEtBQUssRUFBRSxNQUFNLEVBQUUsQ0FBRSxhQUFhLENBQUUsRUFBRTtnQkFDcEQsVUFBVSxFQUFFLEVBQUUsR0FBRyxFQUFFLEtBQUssRUFBRSxNQUFNLEVBQUUsQ0FBRSwyQkFBMkIsQ0FBRSxFQUFFO2dCQUNuRSxPQUFPLEVBQUUsRUFBRSxHQUFHLEVBQUUsS0FBSyxFQUFFLE1BQU0sRUFBRSxDQUFFLGlCQUFpQixDQUFFLEVBQUU7YUFDdkQ7U0FDRjtRQUNELGlCQUFpQixFQUFFO1lBQ2pCO2dCQUNFLE1BQU0sRUFBRSxPQUFPO2dCQUNmLFNBQVMsRUFBRSxFQUFFLEdBQUcsRUFBRSxLQUFLLEVBQUUsTUFBTSxFQUFFLENBQUUsYUFBYSxDQUFFLEVBQUU7Z0JBQ3BELFVBQVUsRUFBRSxFQUFFLEdBQUcsRUFBRSxLQUFLLEVBQUUsTUFBTSxFQUFFLENBQUUsMkJBQTJCLENBQUUsRUFBRTtnQkFDbkUsT0FBTyxFQUFFLEVBQUUsR0FBRyxFQUFFLEtBQUssRUFBRSxNQUFNLEVBQUUsQ0FBRSxpQkFBaUIsQ0FBRSxFQUFFO2FBQ3ZEO1NBQ0Y7S0FDRixDQUFDLENBQUM7QUFDTCxDQUFDLENBQUMsQ0FBQyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7IGRpZmZUZW1wbGF0ZSB9IGZyb20gJy4uLy4uL2xpYic7XG5pbXBvcnQgeyBwb2xkb2MsIHBvbGljeSwgcmVzb3VyY2UsIHJvbGUsIHRlbXBsYXRlIH0gZnJvbSAnLi4vdXRpbCc7XG5cbnRlc3QoJ3Nob3dzIG5ldyBBc3N1bWVSb2xlUG9saWN5RG9jdW1lbnQnLCAoKSA9PiB7XG4gIC8vIFdIRU5cbiAgY29uc3QgZGlmZiA9IGRpZmZUZW1wbGF0ZSh7fSwgdGVtcGxhdGUoe1xuICAgIE15Um9sZTogcm9sZSh7XG4gICAgICBBc3N1bWVSb2xlUG9saWN5RG9jdW1lbnQ6IHBvbGRvYyh7XG4gICAgICAgIEFjdGlvbjogJ3N0czpBc3N1bWVSb2xlJyxcbiAgICAgICAgRWZmZWN0OiAnQWxsb3cnLFxuICAgICAgICBQcmluY2lwYWw6IHsgU2VydmljZTogJ2xhbWJkYS5hbWF6b25hd3MuY29tJyB9LFxuICAgICAgfSksXG4gICAgfSksXG4gIH0pKTtcblxuICAvLyBUSEVOXG4gIGV4cGVjdChkaWZmLmlhbUNoYW5nZXMudG9Kc29uKCkpLnRvRXF1YWwoe1xuICAgIHN0YXRlbWVudEFkZGl0aW9uczogW1xuICAgICAge1xuICAgICAgICBlZmZlY3Q6ICdBbGxvdycsXG4gICAgICAgIHJlc291cmNlczogeyBub3Q6IGZhbHNlLCB2YWx1ZXM6IFsgJyR7TXlSb2xlLkFybn0nIF0gfSxcbiAgICAgICAgcHJpbmNpcGFsczogeyBub3Q6IGZhbHNlLCB2YWx1ZXM6IFsgJ1NlcnZpY2U6bGFtYmRhLmFtYXpvbmF3cy5jb20nIF0gfSxcbiAgICAgICAgYWN0aW9uczogeyBub3Q6IGZhbHNlLCB2YWx1ZXM6IFsgJ3N0czpBc3N1bWVSb2xlJyBdIH0sXG4gICAgICB9LFxuICAgIF0sXG4gIH0pO1xufSk7XG5cbnRlc3QoJ2ltcGxpY2l0bHkga25vd3MgcHJpbmNpcGFsIG9mIGlkZW50aXR5IHBvbGljeSBmb3IgYWxsIHJlc291cmNlIHR5cGVzJywgKCkgPT4ge1xuICBmb3IgKGNvbnN0IGF0dHIgb2YgWydSb2xlcycsICdVc2VycycsICdHcm91cHMnXSkge1xuICAgIC8vIFdIRU5cbiAgICBjb25zdCBkaWZmID0gZGlmZlRlbXBsYXRlKHt9LCB0ZW1wbGF0ZSh7XG4gICAgICBNeVBvbGljeTogcG9saWN5KHtcbiAgICAgICAgW2F0dHJdOiBbeyBSZWY6ICdNeVJvbGUnIH1dLFxuICAgICAgICBQb2xpY3lEb2N1bWVudDogcG9sZG9jKHtcbiAgICAgICAgICBFZmZlY3Q6ICdBbGxvdycsXG4gICAgICAgICAgQWN0aW9uOiAnczM6RG9UaGF0VGhpbmcnLFxuICAgICAgICAgIFJlc291cmNlOiAnKicsXG4gICAgICAgIH0pLFxuICAgICAgfSksXG4gICAgfSkpO1xuXG4gICAgLy8gVEhFTlxuICAgIGV4cGVjdChkaWZmLmlhbUNoYW5nZXMudG9Kc29uKCkpLnRvRXF1YWwoe1xuICAgICAgc3RhdGVtZW50QWRkaXRpb25zOiBbXG4gICAgICAgIHtcbiAgICAgICAgICBlZmZlY3Q6ICdBbGxvdycsXG4gICAgICAgICAgcmVzb3VyY2VzOiB7IG5vdDogZmFsc2UsIHZhbHVlczogWyAnKicgXSB9LFxuICAgICAgICAgIHByaW5jaXBhbHM6IHsgbm90OiBmYWxzZSwgdmFsdWVzOiBbICdBV1M6JHtNeVJvbGV9JyBdIH0sXG4gICAgICAgICAgYWN0aW9uczogeyBub3Q6IGZhbHNlLCB2YWx1ZXM6IFsgJ3MzOkRvVGhhdFRoaW5nJyBdIH0sXG4gICAgICAgIH0sXG4gICAgICBdLFxuICAgIH0pO1xuICB9XG59KTtcblxudGVzdCgncG9saWNpZXMgb24gYW4gaWRlbnRpdHkgb2JqZWN0JywgKCkgPT4ge1xuICBmb3IgKGNvbnN0IHJlc291cmNlVHlwZSBvZiBbJ1JvbGUnLCAnVXNlcicsICdHcm91cCddKSB7XG4gICAgLy8gV0hFTlxuICAgIGNvbnN0IGRpZmYgPSBkaWZmVGVtcGxhdGUoe30sIHRlbXBsYXRlKHtcbiAgICAgIE15SWRlbnRpdHk6IHJlc291cmNlKGBBV1M6OklBTTo6JHtyZXNvdXJjZVR5cGV9YCwge1xuICAgICAgICBQb2xpY2llczogW1xuICAgICAgICAgIHtcbiAgICAgICAgICAgIFBvbGljeU5hbWU6ICdQb2xseScsXG4gICAgICAgICAgICBQb2xpY3lEb2N1bWVudDogcG9sZG9jKHtcbiAgICAgICAgICAgICAgRWZmZWN0OiAnQWxsb3cnLFxuICAgICAgICAgICAgICBBY3Rpb246ICdzMzpEb1RoYXRUaGluZycsXG4gICAgICAgICAgICAgIFJlc291cmNlOiAnKicsXG4gICAgICAgICAgICB9KSxcbiAgICAgICAgICB9LFxuICAgICAgICBdLFxuICAgICAgfSksXG4gICAgfSkpO1xuXG4gICAgLy8gVEhFTlxuICAgIGV4cGVjdChkaWZmLmlhbUNoYW5nZXMudG9Kc29uKCkpLnRvRXF1YWwoe1xuICAgICAgc3RhdGVtZW50QWRkaXRpb25zOiBbXG4gICAgICAgIHtcbiAgICAgICAgICBlZmZlY3Q6ICdBbGxvdycsXG4gICAgICAgICAgcmVzb3VyY2VzOiB7IG5vdDogZmFsc2UsIHZhbHVlczogWyAnKicgXSB9LFxuICAgICAgICAgIHByaW5jaXBhbHM6IHsgbm90OiBmYWxzZSwgdmFsdWVzOiBbICdBV1M6JHtNeUlkZW50aXR5fScgXSB9LFxuICAgICAgICAgIGFjdGlvbnM6IHsgbm90OiBmYWxzZSwgdmFsdWVzOiBbICdzMzpEb1RoYXRUaGluZycgXSB9LFxuICAgICAgICB9LFxuICAgICAgXSxcbiAgICB9KTtcbiAgfVxufSk7XG5cbnRlc3QoJ2lmIHBvbGljeSBpcyBhdHRhY2hlZCB0byBtdWx0aXBsZSByb2xlcyBhbGwgYXJlIHNob3duJywgKCkgPT4ge1xuICAvLyBXSEVOXG4gIGNvbnN0IGRpZmYgPSBkaWZmVGVtcGxhdGUoe30sIHRlbXBsYXRlKHtcbiAgICBNeVBvbGljeTogcG9saWN5KHtcbiAgICAgIFJvbGVzOiBbeyBSZWY6ICdNeVJvbGUnIH0sIHsgUmVmOiAnVGh5Um9sZScgfV0sXG4gICAgICBQb2xpY3lEb2N1bWVudDogcG9sZG9jKHtcbiAgICAgICAgRWZmZWN0OiAnQWxsb3cnLFxuICAgICAgICBBY3Rpb246ICdzMzpEb1RoYXRUaGluZycsXG4gICAgICAgIFJlc291cmNlOiAnKicsXG4gICAgICB9KSxcbiAgICB9KSxcbiAgfSkpO1xuXG4gIC8vIFRIRU5cbiAgZXhwZWN0KGRpZmYuaWFtQ2hhbmdlcy50b0pzb24oKSkudG9FcXVhbCh7XG4gICAgc3RhdGVtZW50QWRkaXRpb25zOiBbXG4gICAgICB7XG4gICAgICAgIGVmZmVjdDogJ0FsbG93JyxcbiAgICAgICAgcmVzb3VyY2VzOiB7IG5vdDogZmFsc2UsIHZhbHVlczogWyAnKicgXSB9LFxuICAgICAgICBwcmluY2lwYWxzOiB7IG5vdDogZmFsc2UsIHZhbHVlczogWyAnQVdTOiR7TXlSb2xlfScgXSB9LFxuICAgICAgICBhY3Rpb25zOiB7IG5vdDogZmFsc2UsIHZhbHVlczogWyAnczM6RG9UaGF0VGhpbmcnIF0gfSxcbiAgICAgIH0sXG4gICAgICB7XG4gICAgICAgIGVmZmVjdDogJ0FsbG93JyxcbiAgICAgICAgcmVzb3VyY2VzOiB7IG5vdDogZmFsc2UsIHZhbHVlczogWyAnKicgXSB9LFxuICAgICAgICBwcmluY2lwYWxzOiB7IG5vdDogZmFsc2UsIHZhbHVlczogWyAnQVdTOiR7VGh5Um9sZX0nIF0gfSxcbiAgICAgICAgYWN0aW9uczogeyBub3Q6IGZhbHNlLCB2YWx1ZXM6IFsgJ3MzOkRvVGhhdFRoaW5nJyBdIH0sXG4gICAgICB9LFxuICAgIF0sXG4gIH0pO1xufSk7XG5cbnRlc3QoJ2NvcnJlY3RseSBwYXJzZXMgTGFtYmRhIHBlcm1pc3Npb25zJywgKCkgPT4ge1xuICAvLyBXSEVOXG4gIGNvbnN0IGRpZmYgPSBkaWZmVGVtcGxhdGUoe30sIHRlbXBsYXRlKHtcbiAgICBNeVBlcm1pc3Npb246IHJlc291cmNlKCdBV1M6OkxhbWJkYTo6UGVybWlzc2lvbicsIHtcbiAgICAgIEFjdGlvbjogJ2xhbWJkYTpJbnZva2VGdW5jdGlvbicsXG4gICAgICBGdW5jdGlvbk5hbWU6IHsgUmVmOiAnTXlGdW5jdGlvbicgfSxcbiAgICAgIFByaW5jaXBhbDogJ3MzLmFtYXpvbmF3cy5jb20nLFxuICAgICAgU291cmNlQWNjb3VudDoge1JlZjogJ0FXUzo6QWNjb3VudElkJyB9LFxuICAgICAgU291cmNlQXJuOiB7J0ZuOjpHZXRBdHQnOiBbJ015QnVja2V0RjY4RjNGRjAnLCAnQXJuJ119LFxuICAgIH0pLFxuICB9KSk7XG5cbiAgLy8gVEhFTlxuICBleHBlY3QoZGlmZi5pYW1DaGFuZ2VzLnRvSnNvbigpKS50b0VxdWFsKHtcbiAgICBzdGF0ZW1lbnRBZGRpdGlvbnM6IFtcbiAgICAgIHtcbiAgICAgICAgZWZmZWN0OiAnQWxsb3cnLFxuICAgICAgICByZXNvdXJjZXM6IHsgbm90OiBmYWxzZSwgdmFsdWVzOiBbICcke015RnVuY3Rpb259JyBdIH0sXG4gICAgICAgIHByaW5jaXBhbHM6IHsgbm90OiBmYWxzZSwgdmFsdWVzOiBbICdTZXJ2aWNlOnMzLmFtYXpvbmF3cy5jb20nIF0gfSxcbiAgICAgICAgYWN0aW9uczogeyBub3Q6IGZhbHNlLCB2YWx1ZXM6IFsgJ2xhbWJkYTpJbnZva2VGdW5jdGlvbicgXSB9LFxuICAgICAgICBjb25kaXRpb246IHtcbiAgICAgICAgICBTdHJpbmdFcXVhbHM6IHsgJ0FXUzpTb3VyY2VBY2NvdW50JzogJyR7QVdTOjpBY2NvdW50SWR9JyB9LFxuICAgICAgICAgIEFybkxpa2U6IHsgJ0FXUzpTb3VyY2VBcm4nOiAnJHtNeUJ1Y2tldEY2OEYzRkYwLkFybn0nIH0sXG4gICAgICAgIH0sXG4gICAgICB9LFxuICAgIF0sXG4gIH0pO1xufSk7XG5cbnRlc3QoJ2ltcGxpY2l0bHkga25vd3MgcmVzb3VyY2Ugb2YgKHF1ZXVlKSByZXNvdXJjZSBwb2xpY3kgZXZlbiBpZiAqIGdpdmVuJywgKCkgPT4ge1xuICAvLyBXSEVOXG4gIGNvbnN0IGRpZmYgPSBkaWZmVGVtcGxhdGUoe30sIHRlbXBsYXRlKHtcbiAgICBRdWV1ZVBvbGljeTogcmVzb3VyY2UoJ0FXUzo6U1FTOjpRdWV1ZVBvbGljeScsIHtcbiAgICAgIFF1ZXVlczogWyB7IFJlZjogJ015UXVldWUnIH0gXSxcbiAgICAgIFBvbGljeURvY3VtZW50OiBwb2xkb2Moe1xuICAgICAgICBFZmZlY3Q6ICdBbGxvdycsXG4gICAgICAgIEFjdGlvbjogJ3NxczpTZW5kTWVzc2FnZScsXG4gICAgICAgIFJlc291cmNlOiAnKicsXG4gICAgICAgIFByaW5jaXBhbDogeyBTZXJ2aWNlOiAnc25zLmFtYXpvbmF3cy5jb20nIH0sXG4gICAgICB9KSxcbiAgICB9KSxcbiAgfSkpO1xuXG4gIC8vIFRIRU5cbiAgZXhwZWN0KGRpZmYuaWFtQ2hhbmdlcy50b0pzb24oKSkudG9FcXVhbCh7XG4gICAgc3RhdGVtZW50QWRkaXRpb25zOiBbXG4gICAgICB7XG4gICAgICAgIGVmZmVjdDogJ0FsbG93JyxcbiAgICAgICAgcmVzb3VyY2VzOiB7IG5vdDogZmFsc2UsIHZhbHVlczogWyAnJHtNeVF1ZXVlfScgXSB9LFxuICAgICAgICBwcmluY2lwYWxzOiB7IG5vdDogZmFsc2UsIHZhbHVlczogWyAnU2VydmljZTpzbnMuYW1hem9uYXdzLmNvbScgXSB9LFxuICAgICAgICBhY3Rpb25zOiB7IG5vdDogZmFsc2UsIHZhbHVlczogWyAnc3FzOlNlbmRNZXNzYWdlJyBdIH0sXG4gICAgICB9LFxuICAgIF0sXG4gIH0pO1xufSk7XG5cbnRlc3QoJ2ZpbmRzIHNvbGUgc3RhdGVtZW50IHJlbW92YWxzJywgKCkgPT4ge1xuICAvLyBXSEVOXG4gIGNvbnN0IGRpZmYgPSBkaWZmVGVtcGxhdGUodGVtcGxhdGUoe1xuICAgIEJ1Y2tldFBvbGljeTogcmVzb3VyY2UoJ0FXUzo6UzM6OkJ1Y2tldFBvbGljeScsIHtcbiAgICAgIEJ1Y2tldDogeyBSZWY6ICdNeUJ1Y2tldCcgfSxcbiAgICAgIFBvbGljeURvY3VtZW50OiBwb2xkb2Moe1xuICAgICAgICBFZmZlY3Q6ICdBbGxvdycsXG4gICAgICAgIEFjdGlvbjogJ3MzOlB1dE9iamVjdCcsXG4gICAgICAgIFJlc291cmNlOiAnKicsXG4gICAgICAgIFByaW5jaXBhbDogeyBBV1M6ICdtZScgfSxcbiAgICAgIH0pLFxuICAgIH0pLFxuICB9KSwge30pO1xuXG4gIC8vIFRIRU5cbiAgZXhwZWN0KGRpZmYuaWFtQ2hhbmdlcy50b0pzb24oKSkudG9FcXVhbCh7XG4gICAgc3RhdGVtZW50UmVtb3ZhbHM6IFtcbiAgICAgIHtcbiAgICAgICAgZWZmZWN0OiAnQWxsb3cnLFxuICAgICAgICByZXNvdXJjZXM6IHsgbm90OiBmYWxzZSwgdmFsdWVzOiBbICcke015QnVja2V0fScgXSB9LFxuICAgICAgICBwcmluY2lwYWxzOiB7IG5vdDogZmFsc2UsIHZhbHVlczogWyAnQVdTOm1lJyBdIH0sXG4gICAgICAgIGFjdGlvbnM6IHsgbm90OiBmYWxzZSwgdmFsdWVzOiBbICdzMzpQdXRPYmplY3QnIF0gfSxcbiAgICAgIH0sXG4gICAgXSxcbiAgfSk7XG59KTtcblxudGVzdCgnZmluZHMgb25lIG9mIG1hbnkgc3RhdGVtZW50IHJlbW92YWxzJywgKCkgPT4ge1xuICAvLyBXSEVOXG4gIGNvbnN0IGRpZmYgPSBkaWZmVGVtcGxhdGUoXG4gICAgdGVtcGxhdGUoe1xuICAgICAgQnVja2V0UG9saWN5OiByZXNvdXJjZSgnQVdTOjpTMzo6QnVja2V0UG9saWN5Jywge1xuICAgICAgICBCdWNrZXQ6IHsgUmVmOiAnTXlCdWNrZXQnIH0sXG4gICAgICAgIFBvbGljeURvY3VtZW50OiBwb2xkb2Moe1xuICAgICAgICAgIEVmZmVjdDogJ0FsbG93JyxcbiAgICAgICAgICBBY3Rpb246ICdzMzpQdXRPYmplY3QnLFxuICAgICAgICAgIFJlc291cmNlOiAnKicsXG4gICAgICAgICAgUHJpbmNpcGFsOiB7IEFXUzogJ21lJyB9LFxuICAgICAgICB9LCB7XG4gICAgICAgICAgRWZmZWN0OiAnQWxsb3cnLFxuICAgICAgICAgIEFjdGlvbjogJ3MzOkxvb2tBdE9iamVjdCcsXG4gICAgICAgICAgUmVzb3VyY2U6ICcqJyxcbiAgICAgICAgICBQcmluY2lwYWw6IHsgQVdTOiAnbWUnIH0sXG4gICAgICAgIH0pLFxuICAgICAgfSksXG4gICAgfSksXG4gICAgdGVtcGxhdGUoe1xuICAgICAgQnVja2V0UG9saWN5OiByZXNvdXJjZSgnQVdTOjpTMzo6QnVja2V0UG9saWN5Jywge1xuICAgICAgICBCdWNrZXQ6IHsgUmVmOiAnTXlCdWNrZXQnIH0sXG4gICAgICAgIFBvbGljeURvY3VtZW50OiBwb2xkb2Moe1xuICAgICAgICAgIEVmZmVjdDogJ0FsbG93JyxcbiAgICAgICAgICBBY3Rpb246ICdzMzpMb29rQXRPYmplY3QnLFxuICAgICAgICAgIFJlc291cmNlOiAnKicsXG4gICAgICAgICAgUHJpbmNpcGFsOiB7IEFXUzogJ21lJyB9LFxuICAgICAgICB9KSxcbiAgICAgIH0pLFxuICAgIH0pKTtcblxuICAvLyBUSEVOXG4gIGV4cGVjdChkaWZmLmlhbUNoYW5nZXMudG9Kc29uKCkpLnRvRXF1YWwoe1xuICAgIHN0YXRlbWVudFJlbW92YWxzOiBbXG4gICAgICB7XG4gICAgICAgIGVmZmVjdDogJ0FsbG93JyxcbiAgICAgICAgcmVzb3VyY2VzOiB7IG5vdDogZmFsc2UsIHZhbHVlczogWyAnJHtNeUJ1Y2tldH0nIF0gfSxcbiAgICAgICAgcHJpbmNpcGFsczogeyBub3Q6IGZhbHNlLCB2YWx1ZXM6IFsgJ0FXUzptZScgXSB9LFxuICAgICAgICBhY3Rpb25zOiB7IG5vdDogZmFsc2UsIHZhbHVlczogWyAnczM6UHV0T2JqZWN0JyBdIH0sXG4gICAgICB9LFxuICAgIF0sXG4gIH0pO1xufSk7XG5cbnRlc3QoJ2ZpbmRzIHBvbGljeSBhdHRhY2htZW50cycsICgpID0+IHtcbiAgLy8gV0hFTlxuICBjb25zdCBkaWZmID0gZGlmZlRlbXBsYXRlKHt9LCB0ZW1wbGF0ZSh7XG4gICAgU29tZVJvbGU6IHJlc291cmNlKCdBV1M6OklBTTo6Um9sZScsIHtcbiAgICAgIE1hbmFnZWRQb2xpY3lBcm5zOiBbJ2Fybjpwb2xpY3knXSxcbiAgICB9KSxcbiAgfSkpO1xuXG4gIC8vIFRIRU5cbiAgZXhwZWN0KGRpZmYuaWFtQ2hhbmdlcy50b0pzb24oKSkudG9FcXVhbCh7XG4gICAgbWFuYWdlZFBvbGljeUFkZGl0aW9uczogW1xuICAgICAge1xuICAgICAgICBpZGVudGl0eUFybjogJyR7U29tZVJvbGV9JyxcbiAgICAgICAgbWFuYWdlZFBvbGljeUFybjogJ2Fybjpwb2xpY3knLFxuICAgICAgfSxcbiAgICBdLFxuICB9KTtcbn0pO1xuXG50ZXN0KCdmaW5kcyBwb2xpY3kgcmVtb3ZhbHMnLCAoKSA9PiB7XG4gIC8vIFdIRU5cbiAgY29uc3QgZGlmZiA9IGRpZmZUZW1wbGF0ZShcbiAgICB0ZW1wbGF0ZSh7XG4gICAgICBTb21lUm9sZTogcmVzb3VyY2UoJ0FXUzo6SUFNOjpSb2xlJywge1xuICAgICAgICBNYW5hZ2VkUG9saWN5QXJuczogWydhcm46cG9saWN5JywgJ2Fybjpwb2xpY3kyJ10sXG4gICAgICB9KSxcbiAgICB9KSxcbiAgICB0ZW1wbGF0ZSh7XG4gICAgICBTb21lUm9sZTogcmVzb3VyY2UoJ0FXUzo6SUFNOjpSb2xlJywge1xuICAgICAgICBNYW5hZ2VkUG9saWN5QXJuczogWydhcm46cG9saWN5MiddLFxuICAgICAgfSksXG4gICAgfSkpO1xuXG4gIC8vIFRIRU5cbiAgZXhwZWN0KGRpZmYuaWFtQ2hhbmdlcy50b0pzb24oKSkudG9FcXVhbCh7XG4gICAgbWFuYWdlZFBvbGljeVJlbW92YWxzOiBbXG4gICAgICB7XG4gICAgICAgIGlkZW50aXR5QXJuOiAnJHtTb21lUm9sZX0nLFxuICAgICAgICBtYW5hZ2VkUG9saWN5QXJuOiAnYXJuOnBvbGljeScsXG4gICAgICB9LFxuICAgIF0sXG4gIH0pO1xufSk7XG5cbnRlc3QoJ3F1ZXVlcG9saWN5IHF1ZXVlIGNoYW5nZSBjb3VudHMgYXMgcmVtb3ZhbCthZGRpdGlvbicsICgpID0+IHtcbiAgLy8gV0hFTlxuICBjb25zdCBkaWZmID0gZGlmZlRlbXBsYXRlKHRlbXBsYXRlKHtcbiAgICBRdWV1ZVBvbGljeTogcmVzb3VyY2UoJ0FXUzo6U1FTOjpRdWV1ZVBvbGljeScsIHtcbiAgICAgIFF1ZXVlczogWyB7IFJlZjogJ015UXVldWUxJyB9IF0sXG4gICAgICBQb2xpY3lEb2N1bWVudDogcG9sZG9jKHtcbiAgICAgICAgRWZmZWN0OiAnQWxsb3cnLFxuICAgICAgICBBY3Rpb246ICdzcXM6U2VuZE1lc3NhZ2UnLFxuICAgICAgICBSZXNvdXJjZTogJyonLFxuICAgICAgICBQcmluY2lwYWw6IHsgU2VydmljZTogJ3Nucy5hbWF6b25hd3MuY29tJyB9LFxuICAgICAgfSksXG4gICAgfSksXG4gIH0pLCB0ZW1wbGF0ZSh7XG4gICAgUXVldWVQb2xpY3k6IHJlc291cmNlKCdBV1M6OlNRUzo6UXVldWVQb2xpY3knLCB7XG4gICAgICBRdWV1ZXM6IFsgeyBSZWY6ICdNeVF1ZXVlMicgfSBdLFxuICAgICAgUG9saWN5RG9jdW1lbnQ6IHBvbGRvYyh7XG4gICAgICAgIEVmZmVjdDogJ0FsbG93JyxcbiAgICAgICAgQWN0aW9uOiAnc3FzOlNlbmRNZXNzYWdlJyxcbiAgICAgICAgUmVzb3VyY2U6ICcqJyxcbiAgICAgICAgUHJpbmNpcGFsOiB7IFNlcnZpY2U6ICdzbnMuYW1hem9uYXdzLmNvbScgfSxcbiAgICAgIH0pLFxuICAgIH0pLFxuICB9KSk7XG5cbiAgLy8gVEhFTlxuICBleHBlY3QoZGlmZi5pYW1DaGFuZ2VzLnRvSnNvbigpKS50b0VxdWFsKHtcbiAgICBzdGF0ZW1lbnRBZGRpdGlvbnM6IFtcbiAgICAgIHtcbiAgICAgICAgZWZmZWN0OiAnQWxsb3cnLFxuICAgICAgICByZXNvdXJjZXM6IHsgbm90OiBmYWxzZSwgdmFsdWVzOiBbICcke015UXVldWUyfScgXSB9LFxuICAgICAgICBwcmluY2lwYWxzOiB7IG5vdDogZmFsc2UsIHZhbHVlczogWyAnU2VydmljZTpzbnMuYW1hem9uYXdzLmNvbScgXSB9LFxuICAgICAgICBhY3Rpb25zOiB7IG5vdDogZmFsc2UsIHZhbHVlczogWyAnc3FzOlNlbmRNZXNzYWdlJyBdIH0sXG4gICAgICB9LFxuICAgIF0sXG4gICAgc3RhdGVtZW50UmVtb3ZhbHM6IFtcbiAgICAgIHtcbiAgICAgICAgZWZmZWN0OiAnQWxsb3cnLFxuICAgICAgICByZXNvdXJjZXM6IHsgbm90OiBmYWxzZSwgdmFsdWVzOiBbICcke015UXVldWUxfScgXSB9LFxuICAgICAgICBwcmluY2lwYWxzOiB7IG5vdDogZmFsc2UsIHZhbHVlczogWyAnU2VydmljZTpzbnMuYW1hem9uYXdzLmNvbScgXSB9LFxuICAgICAgICBhY3Rpb25zOiB7IG5vdDogZmFsc2UsIHZhbHVlczogWyAnc3FzOlNlbmRNZXNzYWdlJyBdIH0sXG4gICAgICB9LFxuICAgIF0sXG4gIH0pO1xufSk7XG4iXX0=
|
// import important parts of sequelize library
const { Model, DataTypes } = require("sequelize");
// import our database connection from config.js
const sequelize = require("../config/connection");
const Category = require("./Category");
// Initialize Product model (table) by extending off Sequelize's Model class
class Product extends Model {}
// set up fields and rules for Product model
Product.init(
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
product_name: {
type: DataTypes.STRING,
allowNull: false,
},
price: {
type: DataTypes.DECIMAL,
allowNull: false,
validate: { isDecimal: true },
},
stock: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 10,
validate: {
isNumeric: true,
},
},
category_id: {
type: DataTypes.INTEGER,
references: {
model: "category",
key: "id",
},
},
},
{
sequelize,
timestamps: false,
freezeTableName: true,
underscored: true,
modelName: "product",
}
);
module.exports = Product;
|
/**
* map manual dialog
*/
define([
'jquery',
'app/init',
'app/util',
'app/render',
'bootbox',
], function($, Init, Util, Render, bootbox) {
'use strict';
let config = {
// global dialog
dialogNavigationClass: 'pf-dialog-navigation-list', // class for dialog navigation bar
dialogNavigationListItemClass: 'pf-dialog-navigation-list-item', // class for map manual li main navigation elements
// map manual dialog
mapManualScrollspyId: 'pf-manual-scrollspy' // id for map manual scrollspy
};
/**
* shows the map manual modal dialog
*/
$.fn.showMapManual = function(){
requirejs(['text!templates/dialog/map_manual.html', 'mustache'], function(template, Mustache) {
let data = {
dialogNavigationClass: config.dialogNavigationClass,
dialogNavLiClass: config.dialogNavigationListItemClass,
scrollspyId: config.mapManualScrollspyId,
pieChartClass : Init.classes.pieChart.pieChartMapCounterClass,
mapCounterClass : Init.classes.pieChart.pieChartMapCounterClass
};
let content = Mustache.render(template, data);
// show dialog
let mapManualDialog = bootbox.dialog({
title: 'Manual',
message: content,
size: 'large',
buttons: {
success: {
label: 'close',
className: 'btn-default',
callback: function() {
$(mapManualDialog).modal('hide');
}
}
},
show: true
});
// modal offset top
let modalOffsetTop = 200;
// disable on scroll event
let disableOnScrollEvent = false;
// scroll breakpoints
let scrolLBreakpointElements = null;
// scroll navigation links
let scrollNavLiElements = null;
mapManualDialog.on('shown.bs.modal', function(e) {
// modal on open
scrolLBreakpointElements = $('.pf-manual-scroll-break');
scrollNavLiElements = $('.' + config.dialogNavigationListItemClass);
});
let scrollspyElement = $('#' + config.mapManualScrollspyId);
let whileScrolling = function(){
if(disableOnScrollEvent === false){
for(let i = 0; i < scrolLBreakpointElements.length; i++){
let offset = $(scrolLBreakpointElements[i]).offset().top;
if( (offset - modalOffsetTop) > 0){
if(! $( scrollNavLiElements[i]).hasClass('active')){
// remove all active classes
scrollNavLiElements.removeClass('active');
// remove focus on links
scrollNavLiElements.find('a').blur();
$( scrollNavLiElements[i]).addClass('active');
}
break;
}
}
}
};
// init scrollbar
scrollspyElement.mCustomScrollbar({
axis: 'y',
theme: 'light-3',
scrollInertia: 200,
autoExpandScrollbar: false,
scrollButtons:{
enable: true,
scrollAmount: 30
},
advanced: {
updateOnContentResize: true
},
callbacks:{
onInit: function(){
// init fake-map update counter
scrollspyElement.find('.' + data.mapCounterClass).initMapUpdateCounter();
// set navigation button observer
let mainNavigationLinks = $('.' + config.dialogNavigationClass).find('a');
// text anchor links
let subNavigationLinks = scrollspyElement.find('a[data-target]');
let navigationLinks = mainNavigationLinks.add(subNavigationLinks);
navigationLinks.on('click', function(e){
e.preventDefault();
disableOnScrollEvent = true;
// scroll to anchor
scrollspyElement.mCustomScrollbar('scrollTo', $(this).attr('data-target'));
let mainNavigationLiElement = $(this).parent('.' + config.dialogNavigationListItemClass);
whileScrolling();
// if link is a main navigation link (not an anchor link)
if(mainNavigationLiElement.length > 0){
// remove all active classes
scrollNavLiElements.removeClass('active');
// set new active class
$(this).parent().addClass('active');
}
});
},
onScroll: function(){
disableOnScrollEvent = false;
whileScrolling();
},
whileScrolling: whileScrolling
},
mouseWheel:{
enable: true,
scrollAmount: 200,
axis: 'y',
preventDefault: true // do not scroll parent at the end
},
scrollbarPosition: 'outsite',
autoDraggerLength: true
});
});
};
});
|
if(typeof window=="undefined"){dojo.raise("attempt to use adobe svg hostenv when no window object");}
with(dojo.render){name=navigator.appName;ver=parseFloat(navigator.appVersion,10);switch(navigator.platform){case"MacOS":os.osx=true;break;case"Linux":os.linux=true;break;case"Windows":os.win=true;break;default:os.linux=true;break;}
svg.capable=true;svg.support.builtin=true;svg.adobe=true;}
dojo.hostenv.println=function(s){try{var ti=document.createElement("text");ti.setAttribute("x","50");var yPos=25+15*document.getElementsByTagName("text").length;ti.setAttribute("y",yPos);var tn=document.createTextNode(s);ti.appendChild(tn);document.documentElement.appendChild(ti);}
catch(e){}};dojo.debug=function(){if(!djConfig.isDebug){return;}
var args=arguments;if(typeof dojo.hostenv.println!="function"){dojo.raise("attempt to call dojo.debug when there is no dojo.hostenv println implementation (yet?)");}
var isJUM=dj_global["jum"];var s=isJUM?"":"DEBUG: ";for(var i=0;i<args.length;++i){s+=args[i];}
if(isJUM){jum.debug(s);}else{dojo.hostenv.println(s);}};dojo.hostenv.startPackage("dojo.hostenv");dojo.hostenv.name_="adobesvg";dojo.hostenv.anonCtr=0;dojo.hostenv.anon={};dojo.hostenv.nameAnonFunc=function(anonFuncPtr,namespaceObj){var ret="_"+this.anonCtr++;var nso=(namespaceObj||this.anon);while(typeof nso[ret]!="undefined"){ret="_"+this.anonCtr++;}
nso[ret]=anonFuncPtr;return ret;};dojo.hostenv.modulesLoadedFired=false;dojo.hostenv.modulesLoadedListeners=[];dojo.hostenv.getTextStack=[];dojo.hostenv.loadUriStack=[];dojo.hostenv.loadedUris=[];dojo.hostenv.modulesLoaded=function(){if(this.modulesLoadedFired){return;}
if((this.loadUriStack.length==0)&&(this.getTextStack.length==0)){if(this.inFlightCount>0){dojo.debug("couldn't initialize, there are files still in flight");return;}
this.modulesLoadedFired=true;var mll=this.modulesLoadedListeners;for(var x=0;x<mll.length;x++){mll[x]();}}};dojo.hostenv.getNewAnonFunc=function(){var ret="_"+this.anonCtr++;while(typeof this.anon[ret]!="undefined"){ret="_"+this.anonCtr++;}
eval("dojo.nostenv.anon."+ret+" = function(){};");return[ret,this.anon[ret]];};dojo.hostenv.displayStack=function(){var oa=[];var stack=this.loadUriStack;for(var x=0;x<stack.length;x++){oa.unshift([stack[x][0],(typeof stack[x][2])]);}
dojo.debug("<pre>"+oa.join("\n")+"</pre>");};dojo.hostenv.unwindUriStack=function(){var stack=this.loadUriStack;for(var x in dojo.hostenv.loadedUris){for(var y=stack.length-1;y>=0;y--){if(stack[y][0]==x){stack.splice(y,1);}}}
var next=stack.pop();if((!next)&&(stack.length==0)){return;}
for(var x=0;x<stack.length;x++){if((stack[x][0]==next[0])&&(stack[x][2])){next[2]==stack[x][2];}}
var last=next;while(dojo.hostenv.loadedUris[next[0]]){last=next;next=stack.pop();}
while(typeof next[2]=="string"){try{dj_eval(next[2]);next[1](true);}
catch(e){dojo.debug("we got an error when loading "+next[0]);dojo.debug("error: "+e);}
dojo.hostenv.loadedUris[next[0]]=true;dojo.hostenv.loadedUris.push(next[0]);last=next;next=stack.pop();if((!next)&&(stack.length==0)){break;}
while(dojo.hostenv.loadedUris[next[0]]){last=next;next=stack.pop();}}
if(next){stack.push(next);dojo.debug("### CHOKED ON: "+next[0]);}};dojo.hostenv.loadUri=function(uri,cb){if(dojo.hostenv.loadedUris[uri]){return;}
var stack=this.loadUriStack;stack.push([uri,cb,null]);var tcb=function(contents){if(contents.content){contents=contents.content;}
var next=stack.pop();if((!next)&&(stack.length==0)){dojo.hostenv.modulesLoaded();return;}
if(typeof contents=="string"){stack.push(next);for(var x=0;x<stack.length;x++){if(stack[x][0]==uri){stack[x][2]=contents;}}
next=stack.pop();}
if(dojo.hostenv.loadedUris[next[0]]){dojo.hostenv.unwindUriStack();return;}
stack.push(next);if(next[0]!=uri){if(typeof next[2]=="string"){dojo.hostenv.unwindUriStack();}}else{if(!contents){next[1](false);}else{var deps=dojo.hostenv.getDepsForEval(next[2]);if(deps.length>0){eval(deps.join(";"));}else{dojo.hostenv.unwindUriStack();}}}};this.getText(uri,tcb,true);};dojo.hostenv.loadModule=function(modulename,exact_only,omit_module_check){var module=this.findModule(modulename,0);if(module){return module;}
if(typeof this.loading_modules_[modulename]!=="undefined"){dojo.debug("recursive attempt to load module '"+modulename+"'");}else{this.addedToLoadingCount.push(modulename);}
this.loading_modules_[modulename]=1;var relpath=modulename.replace(/\./g,"/")+".js";var syms=modulename.split(".");var nsyms=modulename.split(".");if(syms[0]=="dojo"){syms[0]="src";}
var last=syms.pop();syms.push(last);var _this=this;var pfn=this.pkgFileName;if(last=="*"){modulename=(nsyms.slice(0,-1)).join(".");var module=this.findModule(modulename,0);if(module){_this.removedFromLoadingCount.push(modulename);return module;}
var nextTry=function(lastStatus){if(lastStatus){module=_this.findModule(modulename,false);if((!module)&&(syms[syms.length-1]!=pfn)){dojo.raise("Module symbol '"+modulename+"' is not defined after loading '"+relpath+"'");}
if(module){_this.removedFromLoadingCount.push(modulename);dojo.hostenv.modulesLoaded();return;}}
syms.pop();syms.push(pfn);relpath=syms.join("/")+".js";if(relpath.charAt(0)=="/"){relpath=relpath.slice(1);}
_this.loadPath(relpath,((!omit_module_check)?modulename:null),nextTry);};nextTry();}else{relpath=syms.join("/")+".js";modulename=nsyms.join(".");var nextTry=function(lastStatus){if(lastStatus){module=_this.findModule(modulename,false);if((!module)&&(syms[syms.length-1]!=pfn)){dojo.raise("Module symbol '"+modulename+"' is not defined after loading '"+relpath+"'");}
if(module){_this.removedFromLoadingCount.push(modulename);dojo.hostenv.modulesLoaded();return;}}
var setPKG=(syms[syms.length-1]==pfn)?false:true;syms.pop();if(setPKG){syms.push(pfn);}
relpath=syms.join("/")+".js";if(relpath.charAt(0)=="/"){relpath=relpath.slice(1);}
_this.loadPath(relpath,((!omit_module_check)?modulename:null),nextTry);};this.loadPath(relpath,((!omit_module_check)?modulename:null),nextTry);}
return;};dojo.hostenv.async_cb=null;dojo.hostenv.unWindGetTextStack=function(){if(dojo.hostenv.inFlightCount>0){setTimeout("dojo.hostenv.unWindGetTextStack()",100);return;}
dojo.hostenv.inFlightCount++;var next=dojo.hostenv.getTextStack.pop();if((!next)&&(dojo.hostenv.getTextStack.length==0)){dojo.hostenv.inFlightCount--;dojo.hostenv.async_cb=function(){};return;}
dojo.hostenv.async_cb=next[1];window.getURL(next[0],function(result){dojo.hostenv.inFlightCount--;dojo.hostenv.async_cb(result.content);dojo.hostenv.unWindGetTextStack();});};dojo.hostenv.getText=function(uri,async_cb,fail_ok){try{if(async_cb){dojo.hostenv.getTextStack.push([uri,async_cb,fail_ok]);dojo.hostenv.unWindGetTextStack();}else{return dojo.raise("No synchronous XMLHTTP implementation available, for uri "+uri);}}
catch(e){return dojo.raise("No XMLHTTP implementation available, for uri "+uri);}};dojo.hostenv.postText=function(uri,async_cb,text,fail_ok,mime_type,encoding){var http=null;var async_callback=function(httpResponse){if(!httpResponse.success){dojo.raise("Request for uri '"+uri+"' resulted in "+httpResponse.status);}
if(!httpResponse.content){if(!fail_ok){dojo.raise("Request for uri '"+uri+"' resulted in no content");}
return null;}
async_cb(httpResponse.content);};try{if(async_cb){http=window.postURL(uri,text,async_callback,mimeType,encoding);}else{return dojo.raise("No synchronous XMLHTTP post implementation available, for uri "+uri);}}
catch(e){return dojo.raise("No XMLHTTP post implementation available, for uri "+uri);}};function dj_last_script_src(){var scripts=window.document.getElementsByTagName("script");if(scripts.length<1){dojo.raise("No script elements in window.document, so can't figure out my script src");}
var li=scripts.length-1;var xlinkNS="http://www.w3.org/1999/xlink";var src=null;var script=null;while(!src){script=scripts.item(li);src=script.getAttributeNS(xlinkNS,"href");li--;if(li<0){break;}}
if(!src){dojo.raise("Last script element (out of "+scripts.length+") has no src");}
return src;}
if(!dojo.hostenv["library_script_uri_"]){dojo.hostenv.library_script_uri_=dj_last_script_src();}
dojo.requireIf((djConfig["isDebug"]||djConfig["debugAtAllCosts"]),"dojo.debug");
|
//var wikipediaLink = "https://en.wikipedia.org/wiki/Beyonc%C3%A9";
var wikipediaLink = "https://en.wikipedia.org/wiki/Justin_Timberlake";
var contentArray = []
var myTableArray = [];
function makeArrayFromTable(){
myTableArray = [];
$("table tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
var titel = $(this).find('th').text();
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
var thisRow = [];
thisRow[0] = titel;
thisRow[1] = arrayOfThisRow;
myTableArray.push(thisRow);
}
});
console.log(myTableArray);
}
function removeBrackets(inputText){
var startSplitter = "[";
var endSplitter = "]";
//console.log("removeBrackets")
var firstRemoved = inputText.split(startSplitter);
for(var i=0; i<firstRemoved.length; i++){
var currentLineArray = firstRemoved[i].split(endSplitter);
firstRemoved[i] = currentLineArray[currentLineArray.length-1]
}
var cleanText = firstRemoved.join();
//console.log(cleanText);
return cleanText;
}
function getTitleAndText(inputText){
var headerArray = inputText.split('class="mw-headline"');
//console.log(headerArray);
var titelAndTextArray = [];
for(var i =1; i<headerArray.length-3; i++){
var titelAndText = headerArray[i].substr(headerArray[i].indexOf('>')+1);
var titel = htmlToCleanText(titelAndText.substr(0,titelAndText.indexOf('</')));
var text = htmlToCleanText(titelAndText.substr(titelAndText.indexOf('</')));
var texts = text.split(".");
titelAndTextArray.push([titel, texts]);
}
return titelAndTextArray;
}
function htmlToCleanText(htmlText){
document.getElementById("tempDiv").innerHTML = htmlText;
var cleanText = removeBrackets($("#tempDiv").text()).replace(/(\r\n|\n|\r)/gm,"");
cleanText = cleanText.replace(/,/gi," COMMARHERE ");
cleanText = cleanText.replace(/NSYNC/gi," N sync ");
cleanText = cleanText.replace(/#/gi,"");
cleanText = cleanText.replace(/;/gi,"");
cleanText = cleanText.replace(/$/gi,"");
cleanText = cleanText.replace(/\//gi,"");
cleanText = cleanText.replace(/"/gi,"");
cleanText = cleanText.replace(/'/gi,"");
cleanText = cleanText.replace(/:/gi,"");
cleanText = cleanText.replace(/[()]/gi,"");
//cleanText = cleanText.replace(")","");
return cleanText;
}
function onload(){
console.log("Laddar..");
var theUrl = wikipediaLink;
$.ajax({
url: theUrl,
type: 'GET',
success: function(res) {
var text = res.responseText;
//console.log(text);
document.getElementById("tempDiv").innerHTML = text;
var content = document.getElementById("bodyContent").innerHTML;
makeArrayFromTable();
//console.log(content);
//document.getElementById("container").innerHTML = content;
contentArray = getTitleAndText(content);
console.log(contentArray);
document.getElementById("tempDiv").innerHTML = "";
createTopic();
}
});
}
function creatQuestionText(){
var dialogtxt = "";
return dialogtxt;
}
function createTopic(){
var dialogtxt = "";
//dialogtxt = "topic: ~ronaldTalk () \n language: enu";
//dialogtxt += "\nconcept:(music) [music artist]";
dialogtxt += "\nu:(storyMode) %storyMode $openPage=story Look at my stomach to see the headlines and tell me what you want to hear about?";
for(var i = 0; i<contentArray.length; i++){
var sentences = contentArray[i][1];
var titel = contentArray[i][0];
if(sentences.length>2){
//rubriker här
dialogtxt += "\n\tu1:("+titel+") Wikipedia says "+sentences[0].replace(/COMMARHERE/g," . ")+"";
//tre första meningarna
for(var j = 1; j<sentences.length && j<3; j++){
var thisScentence = sentences[j];
thisScentence = thisScentence.replace(/COMMARHERE/g," . ");
dialogtxt += thisScentence+" . ";
}
dialogtxt +=' ^first[" $pauseOn==true $pause=1 A. A. A. " " . "] Do you want to hear more about this topic? ';
dialogtxt += "\n\t\tu2:(~yes) ";
for(var j = 3; j<sentences.length; j++){
var thisScentence = sentences[j];
thisScentence = thisScentence.replace(/COMMARHERE/g," . ");
dialogtxt += thisScentence+" . ";
}
dialogtxt += "\n\t\tu2:(~no) ok ^goto(storyMode) \n";
}else{
dialogtxt += "\n\tu1:("+titel+") Wikipedia says "+sentences[0].replace(/COMMARHERE/g," . ")+"";
//tre första meningarna
for(var j = 1; j<sentences.length && j<3; j++){
var thisScentence = sentences[j];
thisScentence = thisScentence.replace(/COMMARHERE/g," . ");
dialogtxt += thisScentence+" . ";
}
}
}
//dialogtxt = creatQuestionText();
document.getElementById("topicArea").value = dialogtxt;
}
/*
function createTopic(){
var dialogtxt = "topic: ~ronaldTalk () \n language: enu";
dialogtxt += "\nconcept:(music) [music artist]";
for(var i = 0; i<contentArray.length; i++){
var sentences = contentArray[i][1];
var titel = contentArray[i][0];
dialogtxt += "\nu:("+titel+") Wikipedia says "+sentences[0]+"";
for(var j = 1; j<sentences.length; j++){
dialogtxt += "\n";
for(var t = 0; t<j; t++){
dialogtxt += "\t";
}
dialogtxt += "u"+j+":(more) "+sentences[j]+"";
}
}
document.getElementById("topicArea").value = dialogtxt;
}*/
//get html from website
jQuery.ajax = (function(_ajax){
var protocol = location.protocol,
hostname = location.hostname,
exRegex = RegExp(protocol + '//' + hostname),
YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
query = 'select * from html where url="{URL}" and xpath="*"';
function isExternal(url) {
return !exRegex.test(url) && /:\/\//.test(url);
}
return function(o) {
var url = o.url;
if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) ) {
// Manipulate options so that JSONP-x request is made to YQL
o.url = YQL;
o.dataType = 'json';
o.data = {
q: query.replace(
'{URL}',
url + (o.data ?
(/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
: '')
),
format: 'xml'
};
// Since it's a JSONP request
// complete === success
if (!o.success && o.complete) {
o.success = o.complete;
delete o.complete;
}
o.success = (function(_success){
return function(data) {
if (_success) {
// Fake XHR callback.
_success.call(this, {
responseText: data.results[0]
// YQL screws with <script>s
// Get rid of them
.replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
}, 'success');
}
};
})(o.success);
}
return _ajax.apply(this, arguments);
};
})(jQuery.ajax);
// -------------------------------------------------------- PHP Kod
/* $.post( "php/php.php", {
value: "test",
value2: "test2"
},
function( data ) {
console.log(data);
}); */
/*
var titles = [];
var pTexts = []
$( ".mw-headline" ).each(function( index ) {
titles.push([$(this).text(), 4]);
pTexts.push($(this).next());
//console.log( index + ": " + $( this ).text() );
});
console.log(titles);
var thePs = content.split("<p>");
//console.log(thePs);
var htmlText = "";
var thePsText = [];
for(var i=0; i<thePs.length; i++){
thePs[i] = thePs[i].split("<h")[0];
document.getElementById("container").innerHTML = thePs[i];
thePsText.push( removeBrackets($("#container").text()));
}
//var firstP = thePs[7];
document.getElementById("container").innerHTML = content;
//var firstPtext = $("#container").text();
//document.getElementById("container").innerHTML = firstPtext;
console.log(thePsText);
//cleanText = removeBrackets(firstPtext);
//document.getElementById("container").innerHTML = thePsText[7];
//createTopic();
//var pText = $( ".mw-headline" );
//var array = $(".mw-headline").html();
// then you can manipulate your text as you wish
//alert(text);
//makeArrayFromTable()
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.