code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
var NWM = function() { // Known layouts this.layouts = { tile: tile, wide: wide, grid: grid }; // monitors this.monitors = [ ]; this.windows = { }; // counter this.counter = 1; }; NWM.prototype.addMonitor = function (monitor) { this.monitors.push(new Monitor(this, monitor)); }; NWM.prototype.addWindow = function () { var id = this.counter++; // create new div $('<div id="w'+id+'" class="win">#'+id+'</div>').appendTo('#monitor'); // bind to enternotify var self = this; $('#w'+id).bind('mouseenter', function() { self.enterNotify({ id: id }); }); // add to management this.windows[id] = new Window(id); }; NWM.prototype.removeWindow = function(id) { delete this.windows[id]; $('#w'+id).remove(); if(Object.keys(nwm.windows).length > 0) { nwm.focusWindow(nwm.windows[Math.min.apply(Math, Object.keys(nwm.windows))].id); } }; NWM.prototype.focusWindow = function(id) { this.monitors[0].focused_window = id; $('.focus').removeClass('focus'); $('#w'+id).addClass('focus'); }; NWM.prototype.enterNotify = function(event) { this.focusWindow(event.id); }; NWM.prototype.rearrange = function() { this.monitors.forEach(function(monitor) { monitor.workspaces[0].rearrange(); }); }; NWM.prototype.nextLayout = function(name) { var keys = Object.keys(this.layouts); var pos = keys.indexOf(name); // Wrap around the array return (keys[pos+1] ? keys[pos+1] : keys[0] ); };
ellis/nwm
test/nwm.js
JavaScript
mit
1,458
define({ "queries": "Truy vấn", "addNew": "Thêm Mới", "newQuery": "Truy vấn Mới", "queryLayer": "Lớp Truy vấn", "setSource": "Thiết lập", "setDataSource": "Thiết lập Nguồn Dữ liệu", "name": "Tên", "querySource": "Nguồn dữ liệu", "queryName": "Tên tác vụ", "queryDefinition": "Định nghĩa Bộ lọc", "resultsSetting": "Thiết lập Kết quả", "symbolSetting": "Thiết lập Ký hiệu", "resultSettingTip": "Xác định nội dung và cách thức hiển thị kết quả đầu ra.", "resultItemTitle": "Tiêu đề của từng mục kết quả", "resultItemContent": "Các thuộc tính của trường này sẽ hiển thị", "fieldsSetTip": "Chọn các trường mà bạn muốn hiển thị. Chọn một trường để cập nhật bí danh, thứ tự và định dạng của trường đó.", "addField": "Thêm Trường", "visibility": "Khả năng hiển thị", "alias": "Bí danh", "specialType": "Loại đặc biệt", "actions": "Các hành động", "none": "Không có", "link": "Liên kết", "image": "Hình ảnh", "noField": "Không có trường nào", "operationalLayerTip": "Thêm kết quả như lớp hoạt động", "setLayerSymbolTip": "Thiết lập ký hiệu cho kết quả truy vấn: ", "setSelectedSymbolTip": "Thiết lập ký hiệu của đối tượng được chọn.", "notUseFilter": "Không sử dụng bộ lọc", "setSourceTip": "Vui lòng thiết lập nguồn truy vấn.", "setFilterTip": "Vui lòng thiết lập bộ lọc chính xác.", "ok": "OK", "cancel": "Hủy", "noFilterTip": "Nếu biểu thức bộ lọc không được xác định, tác vụ truy vấn này sẽ liệt kê tất cả các đối tượng trong nguồn dữ liệu đã chỉ định.", "relationships": "Mối quan hệ", "addRelationshipLayer": "Thêm Mối Quan hệ Mới", "relatedTo": "Liên quan đến", "selectOption": "Vui lòng chọn..", "resultItemSorting": "Sắp xếp Mục Kết quả", "field": "Trường", "sortingOrder": "Thứ tự", "configureFieldsTip": "Vui lòng cấu hình các trường dùng để sắp xếp truy vấn.", "setSortingFields": "Thiết lập Trường Sắp xếp", "ascending": "Tăng dần", "descending": "Giảm dần", "sortBy": "Sắp xếp theo", "thenBy": "Sau đó theo", "addTask": "Thêm Tác vụ", "noTasksTip": "Không có truy vấn được cấu hình. Nhấp vào \"${newQuery}\" để thêm một truy vấn mới.", "infoText": "Thông tin", "filters": "Bộ lọc", "results": "Kết quả", "optionsText": "Tùy chọn", "summaryText": "Tóm tắt", "attributeFilter": "Bộ lọc thuộc tính", "attributeFilterTip": "Xác định biểu thức thuộc tính sử dụng trong tiện ích để lọc lớp truy vấn.", "defineWhereClause": "Xác định mệnh đề where cho truy vấn.", "noExpressionDefinedTip": "Không có biểu thức nào được xác định. Tất cả bản ghi sẽ được trả về.", "setExpressions": "Thiết lập Biểu thức", "spatialFilter": "Bộ lọc không gian", "spatialFilterTip": "Chọn bộ lọc không gian sẽ sẵn có cho người dùng cuối.", "defaultOption": "Mặc định", "useCurrentExtentTip": "Chỉ trả về đối tượng trong phạm vi bản đồ hiện tại", "useDrawGraphicTip": "Chỉ trả về các đối tượng giao cắt với hình dạng đã được vẽ trên bản đồ", "useFeaturesTip": "Chỉ trả về đối tượng có mối quan hệ về không gian với đối tượng trong lớp khác", "noSpatialLimitTip": "Trả về đối tượng trong phạm vi đầy đủ của bản đồ", "drawingTools": "Chọn công cụ vẽ", "bufferSettings": "Bật tùy chọn vùng đệm", "defaultDistance": "Khoảng cách mặc định", "bufferDistance": "Khoảng cách vùng đệm", "defaultUnit": "Đơn vị mặc định", "miles": "Dặm", "kilometers": "Kilômét", "feet": "Feet", "meters": "Mét", "yards": "Thước", "nauticalMiles": "Hải lý", "availableSpatialRelationships": "Chọn quy tắc mối quan hệ không gian", "setSpatialRelationships": "Thiết lập Mối quan hệ Không gian", "availability": "Mức độ khả dụng", "relationship": "Mối quan hệ", "label": "Nhãn", "intersect": "giao cắt", "contain": "bao gồm", "areContainedIn": "được bao gồm trong", "cross": "gạch ngang", "envelopeIntersect": "đường bao giao cắt", "overlap": "xếp chồng", "areOverlapped": "bị xếp chồng", "touch": "chạm", "within": "bên trong", "areWithin": "ở bên trong", "indexIntersect": "chỉ số giao cắt", "itemTitle": "Tiêu đề Mục", "displayFields": "Trường Hiển thị", "sortingFields": "Phân loại các mục kết quả", "setDisplayFields": "Thiết lập Trường Hiển thị", "symbol": "Ký hiệu", "setSymbol": "Sử dụng ký hiệu tùy chỉnh", "changeSymbolAtRuntime": "Cho phép thay đổi ký hiệu khi đang thực hiện", "serviceSymbolTip": "Sử dụng các ký hiệu do lớp xác định", "exportTip": "Cho phép xuất kết quả", "keepResultsTip": "Lưu kết quả trên bản đồ sau khi đóng tiện ích", "queryRelatedRecords": "Bản ghi liên quan đến truy vấn", "createLayerForTaskTip": "Chỉ định cách tác vụ truy vấn tạo lớp", "oneLayerForTaskTip": "Ghi đè lớp mỗi lần thực hiện truy vấn", "multipleLayerForTaskTip": "Tạo lớp mới mỗi lần thực hiện truy vấn", "makeDefault": "Đặt làm mặc định", "icon": "Biểu tượng", "newTask": "Tác vụ Mới", "addTaskTip": "Thêm một hoặc nhiều quy vấn vào tiện ích và cấu hình các thông số cho mỗi quy vấn.", "webMapPopupTip": "Sử dụng cấu hình pop-up của lớp trong bản đồ web", "customPopupTip": "Định cấu hình nội dung tùy chỉnh", "showResultsSetActions": "Hiện các tác vụ cho kết quả đã đặt", "zoomTo": "Phóng tới", "openAttributeTable": "Mở trong Bảng Thuộc tính", "content": "Nội dung", "displaySQLTip": "Hiển thị biểu thức SQL cho người dùng cuối", "useLayerDefaultSymbol": "Sử dụng ký hiệu mặc định của lớp", "setCustomIcon": "Đặt ký hiệu tùy chỉnh", "layerDefaultSymbolTip": "Sử dụng ký hiệu mặc định của lớp", "uploadImage": "Tải ảnh lên", "attributeCriteira": "Tiêu chí thuộc tính", "specifyFilterAtRuntimeTip": "Người dùng sẽ phải chỉ định tham số cho biểu thức này.", "value": "GIÁ TRỊ", "hideLayersTip": "Tắt lớp kết quả truy vấn khi tiện ích bị đóng." });
cmccullough2/cmv-wab-widgets
wab/2.3/widgets/Query/setting/nls/vi/strings.js
JavaScript
mit
6,905
var gulp = require('gulp'); var inquirer = require('inquirer'); var fs = require('fs'); var getDirectories = require('../util/getDirectories'); var config = require('../config'); gulp.task('set-user-choices', function(done) { var prompts = [{ type: 'confirm', name: 'packageToJPT', message: 'Do you want to package to JPT?', default: false }]; var graphicChoices = getDirectories('graphics'); if (graphicChoices.length > 1) { prompts.unshift({ type: 'list', name: 'graphicName', message: 'Choose a graphic', choices: graphicChoices }); } inquirer.prompt(prompts, function(answers) { var chosenGraphic = answers.graphicName || graphicChoices[0]; var graphicType = JSON.parse(fs.readFileSync('graphics/' + chosenGraphic + '/graphicType.json', {encoding: 'utf8'})).graphicType; if (!answers.packageToJPT && graphicType === 'igraphic') { config.setUserChoice('graphic', chosenGraphic); config.setUserChoice('graphicTemplate', '-' + 'regular'); done(); } else { config.setUserChoice('graphic', chosenGraphic); config.setUserChoice('packageToJpt', answers.packageToJPT); config.setUserChoice('graphicTemplate', ''); done(); } }); });
BostonGlobe/schoolbuses
gulp/tasks/setUserChoices.js
JavaScript
mit
1,237
define([ 'extensions/views/view' ], function (View) { var TabView = View.extend({ initialize: function () { View.prototype.initialize.apply(this, arguments); this.listenTo(this.model, 'change:activeIndex', this.setActiveTab, this); }, events: { 'click nav a': 'onTabClick' }, onTabClick: function (event) { var activeIndex = this.$el.find('a').index(event.currentTarget); this.model.set('activeIndex', activeIndex); event.preventDefault(); }, setActiveTab: function () { var activeIndex = this.model.get('activeIndex'), listItems = this.$el.find('li'), sections = this.$el.find('section'); listItems.removeClass('active'); sections.removeClass('active'); listItems.eq(activeIndex).addClass('active'); sections.eq(activeIndex).addClass('active'); }, render: function () { this.setActiveTab(); } }); return TabView; });
alphagov/spotlight
app/client/views/visualisations/tab.js
JavaScript
mit
968
StartTest(function(t) { t.getHarness([ 'testfiles/601_siesta_ui_failing.t.js' ]); t.diag('Verify no layouts occur due to assertion added to its store'); var before = 0; var getLayoutCount = function () { var count = 0 Ext.each(Ext.ComponentQuery.query('container'), function(c) { count += c.layoutCounter; }); count } t.chain( { waitFor : 'rowsVisible', args : 'testgrid' }, function (next) { t.waitForHarnessEvent('testsuiteend', next) t.doubleClick('testgrid => .x-grid-row', function () {}) }, function (next) { before = getLayoutCount() var testgrid = Ext.ComponentQuery.query('testgrid')[0]; // Adding an assertion should not cause a relayout, same goes for view refresh testgrid.store.tree.getNodeById('testfiles/601_siesta_ui_failing.t.js').get('test').pass("some assertion") // Updating a test record should not cause a relayout, same goes for view refresh testgrid.getRootNode().firstChild.set('title', 'foo'); t.is(getLayoutCount(), before, 'No layouts caused by test') } ); });
arthurakay/AppInspector
app/test/siesta-2.0.5-lite/tests/siesta_ui/605_siesta_ui_nbr_layouts.t.js
JavaScript
mit
1,298
'use strict'; angular.module('copayApp.controllers').controller('preferencesBwsUrlController', function($scope, configService, isMobile, isCordova, go, applicationService ) { this.isSafari = isMobile.Safari(); this.isCordova = isCordova; this.error = null; this.success = null; var config = configService.getSync(); this.bwsurl = config.bws.url; this.save = function() { var opts = { bws: { url: this.bwsurl, } }; configService.set(opts, function(err) { if (err) console.log(err); $scope.$emit('Local/BWSUpdated'); applicationService.restart(true); go.walletHome(); }); }; });
xhad/burse
src/js/controllers/preferencesBwsUrl.js
JavaScript
mit
703
import {Aurelia} from 'aurelia-framework'; import * as LogManager from 'aurelia-logging'; let logger = LogManager.getLogger('aurelia-kendoui-plugin'); import {KendoConfigBuilder} from './config-builder'; import 'jquery'; export function configure(aurelia: Aurelia, configCallback?: (builder: KendoConfigBuilder) => void) { let builder = new KendoConfigBuilder(); if (configCallback !== undefined && typeof(configCallback) === 'function') { configCallback(builder); } // Provide core if nothing was specified if (builder.resources.length === 0) { logger.warn('Nothing specified for kendo configuration - using defaults for Kendo Core'); builder.core(); } // Pull the data off the builder let resources = builder.resources; if (builder.useGlobalResources) { aurelia.globalResources(resources); } }
smccrea/aurelia-kendoui-plugin
src/index.js
JavaScript
mit
841
import forEach from '../util/forEach' class JSONConverter { importDocument(doc, json) { if (!json.nodes) { throw new Error('Invalid JSON format.') } var schema = doc.getSchema() if (json.schema && schema.name !== json.schema.name) { throw new Error('Incompatible schema.') } // the json should just be an array of nodes var nodes = json.nodes // import data in a block with deactivated indexers and listeners // as the data contains cyclic references which // cause problems. doc.import(function(tx) { forEach(nodes, function(node) { // overwrite existing nodes if (tx.get(node.id)) { tx.delete(node.id) } tx.create(node) }) }) return doc } exportDocument(doc) { var schema = doc.getSchema() var json = { schema: { name: schema.name }, nodes: {} } forEach(doc.getNodes(), function(node) { if (node._isDocumentNode) { json.nodes[node.id] = node.toJSON() } }) return json } } export default JSONConverter
andene/substance
model/JSONConverter.js
JavaScript
mit
1,103
/* * angular-ui-bootstrap * http://angular-ui.github.io/bootstrap/ * Version: 0.13.3 - 2015-08-09 * License: MIT */ angular.module("ui.bootstrap", ["ui.bootstrap.tabs","ui.bootstrap.buttons","ui.bootstrap.dropdown","ui.bootstrap.position","ui.bootstrap.modal","ui.bootstrap.tooltip","ui.bootstrap.bindHtml","ui.bootstrap.collapse","ui.bootstrap.transition"]); /** * @ngdoc overview * @name ui.bootstrap.tabs * * @description * AngularJS version of the tabs directive. */ angular.module('ui.bootstrap.tabs', []) .controller('TabsetController', ['$scope', function TabsetCtrl($scope) { var ctrl = this, tabs = ctrl.tabs = $scope.tabs = []; ctrl.select = function(selectedTab) { angular.forEach(tabs, function(tab) { if (tab.active && tab !== selectedTab) { tab.active = false; tab.onDeselect(); } }); selectedTab.active = true; selectedTab.onSelect(); }; ctrl.addTab = function addTab(tab) { tabs.push(tab); // we can't run the select function on the first tab // since that would select it twice if (tabs.length === 1 && tab.active !== false) { tab.active = true; } else if (tab.active) { ctrl.select(tab); } else { tab.active = false; } }; ctrl.removeTab = function removeTab(tab) { var index = tabs.indexOf(tab); //Select a new tab if the tab to be removed is selected and not destroyed if (tab.active && tabs.length > 1 && !destroyed) { //If this is the last tab, select the previous tab. else, the next tab. var newActiveIndex = index == tabs.length - 1 ? index - 1 : index + 1; ctrl.select(tabs[newActiveIndex]); } tabs.splice(index, 1); }; var destroyed; $scope.$on('$destroy', function() { destroyed = true; }); }]) /** * @ngdoc directive * @name ui.bootstrap.tabs.directive:tabset * @restrict EA * * @description * Tabset is the outer container for the tabs directive * * @param {boolean=} vertical Whether or not to use vertical styling for the tabs. * @param {boolean=} justified Whether or not to use justified styling for the tabs. * * @example <example module="ui.bootstrap"> <file name="index.html"> <tabset> <tab heading="Tab 1"><b>First</b> Content!</tab> <tab heading="Tab 2"><i>Second</i> Content!</tab> </tabset> <hr /> <tabset vertical="true"> <tab heading="Vertical Tab 1"><b>First</b> Vertical Content!</tab> <tab heading="Vertical Tab 2"><i>Second</i> Vertical Content!</tab> </tabset> <tabset justified="true"> <tab heading="Justified Tab 1"><b>First</b> Justified Content!</tab> <tab heading="Justified Tab 2"><i>Second</i> Justified Content!</tab> </tabset> </file> </example> */ .directive('tabset', function() { return { restrict: 'EA', transclude: true, replace: true, scope: { type: '@' }, controller: 'TabsetController', templateUrl: 'template/tabs/tabset.html', link: function(scope, element, attrs) { scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false; scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false; } }; }) /** * @ngdoc directive * @name ui.bootstrap.tabs.directive:tab * @restrict EA * * @param {string=} heading The visible heading, or title, of the tab. Set HTML headings with {@link ui.bootstrap.tabs.directive:tabHeading tabHeading}. * @param {string=} select An expression to evaluate when the tab is selected. * @param {boolean=} active A binding, telling whether or not this tab is selected. * @param {boolean=} disabled A binding, telling whether or not this tab is disabled. * * @description * Creates a tab with a heading and content. Must be placed within a {@link ui.bootstrap.tabs.directive:tabset tabset}. * * @example <example module="ui.bootstrap"> <file name="index.html"> <div ng-controller="TabsDemoCtrl"> <button class="btn btn-small" ng-click="items[0].active = true"> Select item 1, using active binding </button> <button class="btn btn-small" ng-click="items[1].disabled = !items[1].disabled"> Enable/disable item 2, using disabled binding </button> <br /> <tabset> <tab heading="Tab 1">First Tab</tab> <tab select="alertMe()"> <tab-heading><i class="icon-bell"></i> Alert me!</tab-heading> Second Tab, with alert callback and html heading! </tab> <tab ng-repeat="item in items" heading="{{item.title}}" disabled="item.disabled" active="item.active"> {{item.content}} </tab> </tabset> </div> </file> <file name="script.js"> function TabsDemoCtrl($scope) { $scope.items = [ { title:"Dynamic Title 1", content:"Dynamic Item 0" }, { title:"Dynamic Title 2", content:"Dynamic Item 1", disabled: true } ]; $scope.alertMe = function() { setTimeout(function() { alert("You've selected the alert tab!"); }); }; }; </file> </example> */ /** * @ngdoc directive * @name ui.bootstrap.tabs.directive:tabHeading * @restrict EA * * @description * Creates an HTML heading for a {@link ui.bootstrap.tabs.directive:tab tab}. Must be placed as a child of a tab element. * * @example <example module="ui.bootstrap"> <file name="index.html"> <tabset> <tab> <tab-heading><b>HTML</b> in my titles?!</tab-heading> And some content, too! </tab> <tab> <tab-heading><i class="icon-heart"></i> Icon heading?!?</tab-heading> That's right. </tab> </tabset> </file> </example> */ .directive('tab', ['$parse', '$log', function($parse, $log) { return { require: '^tabset', restrict: 'EA', replace: true, templateUrl: 'template/tabs/tab.html', transclude: true, scope: { active: '=?', heading: '@', onSelect: '&select', //This callback is called in contentHeadingTransclude //once it inserts the tab's content into the dom onDeselect: '&deselect' }, controller: function() { //Empty controller so other directives can require being 'under' a tab }, link: function(scope, elm, attrs, tabsetCtrl, transclude) { scope.$watch('active', function(active) { if (active) { tabsetCtrl.select(scope); } }); scope.disabled = false; if ( attrs.disable ) { scope.$parent.$watch($parse(attrs.disable), function(value) { scope.disabled = !! value; }); } // Deprecation support of "disabled" parameter // fix(tab): IE9 disabled attr renders grey text on enabled tab #2677 // This code is duplicated from the lines above to make it easy to remove once // the feature has been completely deprecated if ( attrs.disabled ) { $log.warn('Use of "disabled" attribute has been deprecated, please use "disable"'); scope.$parent.$watch($parse(attrs.disabled), function(value) { scope.disabled = !! value; }); } scope.select = function() { if ( !scope.disabled ) { scope.active = true; } }; tabsetCtrl.addTab(scope); scope.$on('$destroy', function() { tabsetCtrl.removeTab(scope); }); //We need to transclude later, once the content container is ready. //when this link happens, we're inside a tab heading. scope.$transcludeFn = transclude; } }; }]) .directive('tabHeadingTransclude', [function() { return { restrict: 'A', require: '^tab', link: function(scope, elm, attrs, tabCtrl) { scope.$watch('headingElement', function updateHeadingElement(heading) { if (heading) { elm.html(''); elm.append(heading); } }); } }; }]) .directive('tabContentTransclude', function() { return { restrict: 'A', require: '^tabset', link: function(scope, elm, attrs) { var tab = scope.$eval(attrs.tabContentTransclude); //Now our tab is ready to be transcluded: both the tab heading area //and the tab content area are loaded. Transclude 'em both. tab.$transcludeFn(tab.$parent, function(contents) { angular.forEach(contents, function(node) { if (isTabHeading(node)) { //Let tabHeadingTransclude know. tab.headingElement = node; } else { elm.append(node); } }); }); } }; function isTabHeading(node) { return node.tagName && ( node.hasAttribute('tab-heading') || node.hasAttribute('data-tab-heading') || node.tagName.toLowerCase() === 'tab-heading' || node.tagName.toLowerCase() === 'data-tab-heading' ); } }) ; angular.module('ui.bootstrap.buttons', []) .constant('buttonConfig', { activeClass: 'active', toggleEvent: 'click' }) .controller('ButtonsController', ['buttonConfig', function(buttonConfig) { this.activeClass = buttonConfig.activeClass || 'active'; this.toggleEvent = buttonConfig.toggleEvent || 'click'; }]) .directive('btnRadio', function () { return { require: ['btnRadio', 'ngModel'], controller: 'ButtonsController', controllerAs: 'buttons', link: function (scope, element, attrs, ctrls) { var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1]; //model -> UI ngModelCtrl.$render = function () { element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.btnRadio))); }; //ui->model element.bind(buttonsCtrl.toggleEvent, function () { if (attrs.disabled) { return; } var isActive = element.hasClass(buttonsCtrl.activeClass); if (!isActive || angular.isDefined(attrs.uncheckable)) { scope.$apply(function () { ngModelCtrl.$setViewValue(isActive ? null : scope.$eval(attrs.btnRadio)); ngModelCtrl.$render(); }); } }); } }; }) .directive('btnCheckbox', function () { return { require: ['btnCheckbox', 'ngModel'], controller: 'ButtonsController', controllerAs: 'button', link: function (scope, element, attrs, ctrls) { var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1]; function getTrueValue() { return getCheckboxValue(attrs.btnCheckboxTrue, true); } function getFalseValue() { return getCheckboxValue(attrs.btnCheckboxFalse, false); } function getCheckboxValue(attributeValue, defaultValue) { var val = scope.$eval(attributeValue); return angular.isDefined(val) ? val : defaultValue; } //model -> UI ngModelCtrl.$render = function () { element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue())); }; //ui->model element.bind(buttonsCtrl.toggleEvent, function () { if (attrs.disabled) { return; } scope.$apply(function () { ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue()); ngModelCtrl.$render(); }); }); } }; }); angular.module('ui.bootstrap.dropdown', ['ui.bootstrap.position']) .constant('dropdownConfig', { openClass: 'open' }) .service('dropdownService', ['$document', '$rootScope', function($document, $rootScope) { var openScope = null; this.open = function( dropdownScope ) { if ( !openScope ) { $document.bind('click', closeDropdown); $document.bind('keydown', keybindFilter); } if ( openScope && openScope !== dropdownScope ) { openScope.isOpen = false; } openScope = dropdownScope; }; this.close = function( dropdownScope ) { if ( openScope === dropdownScope ) { openScope = null; $document.unbind('click', closeDropdown); $document.unbind('keydown', keybindFilter); } }; var closeDropdown = function( evt ) { // This method may still be called during the same mouse event that // unbound this event handler. So check openScope before proceeding. if (!openScope) { return; } if( evt && openScope.getAutoClose() === 'disabled' ) { return ; } var toggleElement = openScope.getToggleElement(); if ( evt && toggleElement && toggleElement[0].contains(evt.target) ) { return; } var dropdownElement = openScope.getDropdownElement(); if (evt && openScope.getAutoClose() === 'outsideClick' && dropdownElement && dropdownElement[0].contains(evt.target)) { return; } openScope.isOpen = false; if (!$rootScope.$$phase) { openScope.$apply(); } }; var keybindFilter = function( evt ) { if ( evt.which === 27 ) { openScope.focusToggleElement(); closeDropdown(); } else if ( openScope.isKeynavEnabled() && /(38|40)/.test(evt.which) && openScope.isOpen ) { evt.preventDefault(); evt.stopPropagation(); openScope.focusDropdownEntry(evt.which); } }; }]) .controller('DropdownController', ['$scope', '$attrs', '$parse', 'dropdownConfig', 'dropdownService', '$animate', '$position', '$document', '$compile', '$templateRequest', function($scope, $attrs, $parse, dropdownConfig, dropdownService, $animate, $position, $document, $compile, $templateRequest) { var self = this, scope = $scope.$new(), // create a child scope so we are not polluting original one templateScope, openClass = dropdownConfig.openClass, getIsOpen, setIsOpen = angular.noop, toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop, appendToBody = false, keynavEnabled =false, selectedOption = null; this.init = function( element ) { self.$element = element; if ( $attrs.isOpen ) { getIsOpen = $parse($attrs.isOpen); setIsOpen = getIsOpen.assign; $scope.$watch(getIsOpen, function(value) { scope.isOpen = !!value; }); } appendToBody = angular.isDefined($attrs.dropdownAppendToBody); keynavEnabled = angular.isDefined($attrs.keyboardNav); if ( appendToBody && self.dropdownMenu ) { $document.find('body').append( self.dropdownMenu ); element.on('$destroy', function handleDestroyEvent() { self.dropdownMenu.remove(); }); } }; this.toggle = function( open ) { return scope.isOpen = arguments.length ? !!open : !scope.isOpen; }; // Allow other directives to watch status this.isOpen = function() { return scope.isOpen; }; scope.getToggleElement = function() { return self.toggleElement; }; scope.getAutoClose = function() { return $attrs.autoClose || 'always'; //or 'outsideClick' or 'disabled' }; scope.getElement = function() { return self.$element; }; scope.isKeynavEnabled = function() { return keynavEnabled; }; scope.focusDropdownEntry = function(keyCode) { var elems = self.dropdownMenu ? //If append to body is used. (angular.element(self.dropdownMenu).find('a')) : (angular.element(self.$element).find('ul').eq(0).find('a')); switch (keyCode) { case (40): { if ( !angular.isNumber(self.selectedOption)) { self.selectedOption = 0; } else { self.selectedOption = (self.selectedOption === elems.length -1 ? self.selectedOption : self.selectedOption + 1); } break; } case (38): { if ( !angular.isNumber(self.selectedOption)) { return; } else { self.selectedOption = (self.selectedOption === 0 ? 0 : self.selectedOption - 1); } break; } } elems[self.selectedOption].focus(); }; scope.getDropdownElement = function() { return self.dropdownMenu; }; scope.focusToggleElement = function() { if ( self.toggleElement ) { self.toggleElement[0].focus(); } }; scope.$watch('isOpen', function( isOpen, wasOpen ) { if (appendToBody && self.dropdownMenu) { var pos = $position.positionElements(self.$element, self.dropdownMenu, 'bottom-left', true); var css = { top: pos.top + 'px', display: isOpen ? 'block' : 'none' }; var rightalign = self.dropdownMenu.hasClass('dropdown-menu-right'); if (!rightalign) { css.left = pos.left + 'px'; css.right = 'auto'; } else { css.left = 'auto'; css.right = (window.innerWidth - (pos.left + self.$element.prop('offsetWidth'))) + 'px'; } self.dropdownMenu.css(css); } $animate[isOpen ? 'addClass' : 'removeClass'](self.$element, openClass).then(function() { if (angular.isDefined(isOpen) && isOpen !== wasOpen) { toggleInvoker($scope, { open: !!isOpen }); } }); if ( isOpen ) { if (self.dropdownMenuTemplateUrl) { $templateRequest(self.dropdownMenuTemplateUrl).then(function(tplContent) { templateScope = scope.$new(); $compile(tplContent.trim())(templateScope, function(dropdownElement) { var newEl = dropdownElement; self.dropdownMenu.replaceWith(newEl); self.dropdownMenu = newEl; }); }); } scope.focusToggleElement(); dropdownService.open( scope ); } else { if (self.dropdownMenuTemplateUrl) { if (templateScope) { templateScope.$destroy(); } var newEl = angular.element('<ul class="dropdown-menu"></ul>'); self.dropdownMenu.replaceWith(newEl); self.dropdownMenu = newEl; } dropdownService.close( scope ); self.selectedOption = null; } if (angular.isFunction(setIsOpen)) { setIsOpen($scope, isOpen); } }); $scope.$on('$locationChangeSuccess', function() { if (scope.getAutoClose() !== 'disabled') { scope.isOpen = false; } }); $scope.$on('$destroy', function() { scope.$destroy(); }); }]) .directive('dropdown', function() { return { controller: 'DropdownController', link: function(scope, element, attrs, dropdownCtrl) { dropdownCtrl.init( element ); element.addClass('dropdown'); } }; }) .directive('dropdownMenu', function() { return { restrict: 'AC', require: '?^dropdown', link: function(scope, element, attrs, dropdownCtrl) { if (!dropdownCtrl) { return; } var tplUrl = attrs.templateUrl; if (tplUrl) { dropdownCtrl.dropdownMenuTemplateUrl = tplUrl; } if (!dropdownCtrl.dropdownMenu) { dropdownCtrl.dropdownMenu = element; } } }; }) .directive('keyboardNav', function() { return { restrict: 'A', require: '?^dropdown', link: function (scope, element, attrs, dropdownCtrl) { element.bind('keydown', function(e) { if ([38, 40].indexOf(e.which) !== -1) { e.preventDefault(); e.stopPropagation(); var elems = dropdownCtrl.dropdownMenu.find('a'); switch (e.which) { case (40): { // Down if ( !angular.isNumber(dropdownCtrl.selectedOption)) { dropdownCtrl.selectedOption = 0; } else { dropdownCtrl.selectedOption = (dropdownCtrl.selectedOption === elems.length -1 ? dropdownCtrl.selectedOption : dropdownCtrl.selectedOption+1); } } break; case (38): { // Up dropdownCtrl.selectedOption = (dropdownCtrl.selectedOption === 0 ? 0 : dropdownCtrl.selectedOption-1); } break; } elems[dropdownCtrl.selectedOption].focus(); } }); } }; }) .directive('dropdownToggle', function() { return { require: '?^dropdown', link: function(scope, element, attrs, dropdownCtrl) { if ( !dropdownCtrl ) { return; } element.addClass('dropdown-toggle'); dropdownCtrl.toggleElement = element; var toggleDropdown = function(event) { event.preventDefault(); if ( !element.hasClass('disabled') && !attrs.disabled ) { scope.$apply(function() { dropdownCtrl.toggle(); }); } }; element.bind('click', toggleDropdown); // WAI-ARIA element.attr({ 'aria-haspopup': true, 'aria-expanded': false }); scope.$watch(dropdownCtrl.isOpen, function( isOpen ) { element.attr('aria-expanded', !!isOpen); }); scope.$on('$destroy', function() { element.unbind('click', toggleDropdown); }); } }; }); angular.module('ui.bootstrap.position', []) /** * A set of utility methods that can be use to retrieve position of DOM elements. * It is meant to be used where we need to absolute-position DOM elements in * relation to other, existing elements (this is the case for tooltips, popovers, * typeahead suggestions etc.). */ .factory('$position', ['$document', '$window', function ($document, $window) { function getStyle(el, cssprop) { if (el.currentStyle) { //IE return el.currentStyle[cssprop]; } else if ($window.getComputedStyle) { return $window.getComputedStyle(el)[cssprop]; } // finally try and get inline style return el.style[cssprop]; } /** * Checks if a given element is statically positioned * @param element - raw DOM element */ function isStaticPositioned(element) { return (getStyle(element, 'position') || 'static' ) === 'static'; } /** * returns the closest, non-statically positioned parentOffset of a given element * @param element */ var parentOffsetEl = function (element) { var docDomEl = $document[0]; var offsetParent = element.offsetParent || docDomEl; while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docDomEl; }; return { /** * Provides read-only equivalent of jQuery's position function: * http://api.jquery.com/position/ */ position: function (element) { var elBCR = this.offset(element); var offsetParentBCR = { top: 0, left: 0 }; var offsetParentEl = parentOffsetEl(element[0]); if (offsetParentEl != $document[0]) { offsetParentBCR = this.offset(angular.element(offsetParentEl)); offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop; offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft; } var boundingClientRect = element[0].getBoundingClientRect(); return { width: boundingClientRect.width || element.prop('offsetWidth'), height: boundingClientRect.height || element.prop('offsetHeight'), top: elBCR.top - offsetParentBCR.top, left: elBCR.left - offsetParentBCR.left }; }, /** * Provides read-only equivalent of jQuery's offset function: * http://api.jquery.com/offset/ */ offset: function (element) { var boundingClientRect = element[0].getBoundingClientRect(); return { width: boundingClientRect.width || element.prop('offsetWidth'), height: boundingClientRect.height || element.prop('offsetHeight'), top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop), left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft) }; }, /** * Provides coordinates for the targetEl in relation to hostEl */ positionElements: function (hostEl, targetEl, positionStr, appendToBody) { var positionStrParts = positionStr.split('-'); var pos0 = positionStrParts[0], pos1 = positionStrParts[1] || 'center'; var hostElPos, targetElWidth, targetElHeight, targetElPos; hostElPos = appendToBody ? this.offset(hostEl) : this.position(hostEl); targetElWidth = targetEl.prop('offsetWidth'); targetElHeight = targetEl.prop('offsetHeight'); var shiftWidth = { center: function () { return hostElPos.left + hostElPos.width / 2 - targetElWidth / 2; }, left: function () { return hostElPos.left; }, right: function () { return hostElPos.left + hostElPos.width; } }; var shiftHeight = { center: function () { return hostElPos.top + hostElPos.height / 2 - targetElHeight / 2; }, top: function () { return hostElPos.top; }, bottom: function () { return hostElPos.top + hostElPos.height; } }; switch (pos0) { case 'right': targetElPos = { top: shiftHeight[pos1](), left: shiftWidth[pos0]() }; break; case 'left': targetElPos = { top: shiftHeight[pos1](), left: hostElPos.left - targetElWidth }; break; case 'bottom': targetElPos = { top: shiftHeight[pos0](), left: shiftWidth[pos1]() }; break; default: targetElPos = { top: hostElPos.top - targetElHeight, left: shiftWidth[pos1]() }; break; } return targetElPos; } }; }]); angular.module('ui.bootstrap.modal', []) /** * A helper, internal data structure that acts as a map but also allows getting / removing * elements in the LIFO order */ .factory('$$stackedMap', function () { return { createNew: function () { var stack = []; return { add: function (key, value) { stack.push({ key: key, value: value }); }, get: function (key) { for (var i = 0; i < stack.length; i++) { if (key == stack[i].key) { return stack[i]; } } }, keys: function() { var keys = []; for (var i = 0; i < stack.length; i++) { keys.push(stack[i].key); } return keys; }, top: function () { return stack[stack.length - 1]; }, remove: function (key) { var idx = -1; for (var i = 0; i < stack.length; i++) { if (key == stack[i].key) { idx = i; break; } } return stack.splice(idx, 1)[0]; }, removeTop: function () { return stack.splice(stack.length - 1, 1)[0]; }, length: function () { return stack.length; } }; } }; }) /** * A helper directive for the $modal service. It creates a backdrop element. */ .directive('modalBackdrop', [ '$animate', '$injector', '$modalStack', function ($animate , $injector, $modalStack) { var $animateCss = null; if ($injector.has('$animateCss')) { $animateCss = $injector.get('$animateCss'); } return { restrict: 'EA', replace: true, templateUrl: 'template/modal/backdrop.html', compile: function (tElement, tAttrs) { tElement.addClass(tAttrs.backdropClass); return linkFn; } }; function linkFn(scope, element, attrs) { if (attrs.modalInClass) { if ($animateCss) { $animateCss(element, { addClass: attrs.modalInClass }).start(); } else { $animate.addClass(element, attrs.modalInClass); } scope.$on($modalStack.NOW_CLOSING_EVENT, function (e, setIsAsync) { var done = setIsAsync(); if ($animateCss) { $animateCss(element, { removeClass: attrs.modalInClass }).start().then(done); } else { $animate.removeClass(element, attrs.modalInClass).then(done); } }); } } }]) .directive('modalWindow', [ '$modalStack', '$q', '$animate', '$injector', function ($modalStack , $q , $animate, $injector) { var $animateCss = null; if ($injector.has('$animateCss')) { $animateCss = $injector.get('$animateCss'); } return { restrict: 'EA', scope: { index: '@' }, replace: true, transclude: true, templateUrl: function(tElement, tAttrs) { return tAttrs.templateUrl || 'template/modal/window.html'; }, link: function (scope, element, attrs) { element.addClass(attrs.windowClass || ''); scope.size = attrs.size; scope.close = function (evt) { var modal = $modalStack.getTop(); if (modal && modal.value.backdrop && modal.value.backdrop != 'static' && (evt.target === evt.currentTarget)) { evt.preventDefault(); evt.stopPropagation(); $modalStack.dismiss(modal.key, 'backdrop click'); } }; // This property is only added to the scope for the purpose of detecting when this directive is rendered. // We can detect that by using this property in the template associated with this directive and then use // {@link Attribute#$observe} on it. For more details please see {@link TableColumnResize}. scope.$isRendered = true; // Deferred object that will be resolved when this modal is render. var modalRenderDeferObj = $q.defer(); // Observe function will be called on next digest cycle after compilation, ensuring that the DOM is ready. // In order to use this way of finding whether DOM is ready, we need to observe a scope property used in modal's template. attrs.$observe('modalRender', function (value) { if (value == 'true') { modalRenderDeferObj.resolve(); } }); modalRenderDeferObj.promise.then(function () { if (attrs.modalInClass) { if ($animateCss) { $animateCss(element, { addClass: attrs.modalInClass }).start(); } else { $animate.addClass(element, attrs.modalInClass); } scope.$on($modalStack.NOW_CLOSING_EVENT, function (e, setIsAsync) { var done = setIsAsync(); if ($animateCss) { $animateCss(element, { removeClass: attrs.modalInClass }).start().then(done); } else { $animate.removeClass(element, attrs.modalInClass).then(done); } }); } var inputsWithAutofocus = element[0].querySelectorAll('[autofocus]'); /** * Auto-focusing of a freshly-opened modal element causes any child elements * with the autofocus attribute to lose focus. This is an issue on touch * based devices which will show and then hide the onscreen keyboard. * Attempts to refocus the autofocus element via JavaScript will not reopen * the onscreen keyboard. Fixed by updated the focusing logic to only autofocus * the modal element if the modal does not contain an autofocus element. */ if (inputsWithAutofocus.length) { inputsWithAutofocus[0].focus(); } else { element[0].focus(); } // Notify {@link $modalStack} that modal is rendered. var modal = $modalStack.getTop(); if (modal) { $modalStack.modalRendered(modal.key); } }); } }; }]) .directive('modalAnimationClass', [ function () { return { compile: function (tElement, tAttrs) { if (tAttrs.modalAnimation) { tElement.addClass(tAttrs.modalAnimationClass); } } }; }]) .directive('modalTransclude', function () { return { link: function($scope, $element, $attrs, controller, $transclude) { $transclude($scope.$parent, function(clone) { $element.empty(); $element.append(clone); }); } }; }) .factory('$modalStack', [ '$animate', '$timeout', '$document', '$compile', '$rootScope', '$q', '$injector', '$$stackedMap', function ($animate , $timeout , $document , $compile , $rootScope , $q, $injector, $$stackedMap) { var $animateCss = null; if ($injector.has('$animateCss')) { $animateCss = $injector.get('$animateCss'); } var OPENED_MODAL_CLASS = 'modal-open'; var backdropDomEl, backdropScope; var openedWindows = $$stackedMap.createNew(); var $modalStack = { NOW_CLOSING_EVENT: 'modal.stack.now-closing' }; //Modal focus behavior var focusableElementList; var focusIndex = 0; var tababbleSelector = 'a[href], area[href], input:not([disabled]), ' + 'button:not([disabled]),select:not([disabled]), textarea:not([disabled]), ' + 'iframe, object, embed, *[tabindex], *[contenteditable=true]'; function backdropIndex() { var topBackdropIndex = -1; var opened = openedWindows.keys(); for (var i = 0; i < opened.length; i++) { if (openedWindows.get(opened[i]).value.backdrop) { topBackdropIndex = i; } } return topBackdropIndex; } $rootScope.$watch(backdropIndex, function(newBackdropIndex) { if (backdropScope) { backdropScope.index = newBackdropIndex; } }); function removeModalWindow(modalInstance, elementToReceiveFocus) { var body = $document.find('body').eq(0); var modalWindow = openedWindows.get(modalInstance).value; //clean up the stack openedWindows.remove(modalInstance); removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, function() { body.toggleClass(modalInstance.openedClass || OPENED_MODAL_CLASS, openedWindows.length() > 0); }); checkRemoveBackdrop(); //move focus to specified element if available, or else to body if (elementToReceiveFocus && elementToReceiveFocus.focus) { elementToReceiveFocus.focus(); } else { body.focus(); } } function checkRemoveBackdrop() { //remove backdrop if no longer needed if (backdropDomEl && backdropIndex() == -1) { var backdropScopeRef = backdropScope; removeAfterAnimate(backdropDomEl, backdropScope, function () { backdropScopeRef = null; }); backdropDomEl = undefined; backdropScope = undefined; } } function removeAfterAnimate(domEl, scope, done) { var asyncDeferred; var asyncPromise = null; var setIsAsync = function () { if (!asyncDeferred) { asyncDeferred = $q.defer(); asyncPromise = asyncDeferred.promise; } return function asyncDone() { asyncDeferred.resolve(); }; }; scope.$broadcast($modalStack.NOW_CLOSING_EVENT, setIsAsync); // Note that it's intentional that asyncPromise might be null. // That's when setIsAsync has not been called during the // NOW_CLOSING_EVENT broadcast. return $q.when(asyncPromise).then(afterAnimating); function afterAnimating() { if (afterAnimating.done) { return; } afterAnimating.done = true; if ($animateCss) { $animateCss(domEl, { event: 'leave' }).start().then(function() { domEl.remove(); }); } else { $animate.leave(domEl); } scope.$destroy(); if (done) { done(); } } } $document.bind('keydown', function (evt) { if (evt.isDefaultPrevented()) { return evt; } var modal = openedWindows.top(); if (modal && modal.value.keyboard) { switch (evt.which){ case 27: { evt.preventDefault(); $rootScope.$apply(function () { $modalStack.dismiss(modal.key, 'escape key press'); }); break; } case 9: { $modalStack.loadFocusElementList(modal); var focusChanged = false; if (evt.shiftKey) { if ($modalStack.isFocusInFirstItem(evt)) { focusChanged = $modalStack.focusLastFocusableElement(); } } else { if ($modalStack.isFocusInLastItem(evt)) { focusChanged = $modalStack.focusFirstFocusableElement(); } } if (focusChanged) { evt.preventDefault(); evt.stopPropagation(); } break; } } } }); $modalStack.open = function (modalInstance, modal) { var modalOpener = $document[0].activeElement; openedWindows.add(modalInstance, { deferred: modal.deferred, renderDeferred: modal.renderDeferred, modalScope: modal.scope, backdrop: modal.backdrop, keyboard: modal.keyboard, openedClass: modal.openedClass }); var body = $document.find('body').eq(0), currBackdropIndex = backdropIndex(); if (currBackdropIndex >= 0 && !backdropDomEl) { backdropScope = $rootScope.$new(true); backdropScope.index = currBackdropIndex; var angularBackgroundDomEl = angular.element('<div modal-backdrop="modal-backdrop"></div>'); angularBackgroundDomEl.attr('backdrop-class', modal.backdropClass); if (modal.animation) { angularBackgroundDomEl.attr('modal-animation', 'true'); } backdropDomEl = $compile(angularBackgroundDomEl)(backdropScope); body.append(backdropDomEl); } var angularDomEl = angular.element('<div modal-window="modal-window"></div>'); angularDomEl.attr({ 'template-url': modal.windowTemplateUrl, 'window-class': modal.windowClass, 'size': modal.size, 'index': openedWindows.length() - 1, 'animate': 'animate' }).html(modal.content); if (modal.animation) { angularDomEl.attr('modal-animation', 'true'); } var modalDomEl = $compile(angularDomEl)(modal.scope); openedWindows.top().value.modalDomEl = modalDomEl; openedWindows.top().value.modalOpener = modalOpener; body.append(modalDomEl); body.addClass(modal.openedClass || OPENED_MODAL_CLASS); $modalStack.clearFocusListCache(); }; function broadcastClosing(modalWindow, resultOrReason, closing) { return !modalWindow.value.modalScope.$broadcast('modal.closing', resultOrReason, closing).defaultPrevented; } $modalStack.close = function (modalInstance, result) { var modalWindow = openedWindows.get(modalInstance); if (modalWindow && broadcastClosing(modalWindow, result, true)) { modalWindow.value.modalScope.$$uibDestructionScheduled = true; modalWindow.value.deferred.resolve(result); removeModalWindow(modalInstance, modalWindow.value.modalOpener); return true; } return !modalWindow; }; $modalStack.dismiss = function (modalInstance, reason) { var modalWindow = openedWindows.get(modalInstance); if (modalWindow && broadcastClosing(modalWindow, reason, false)) { modalWindow.value.modalScope.$$uibDestructionScheduled = true; modalWindow.value.deferred.reject(reason); removeModalWindow(modalInstance, modalWindow.value.modalOpener); return true; } return !modalWindow; }; $modalStack.dismissAll = function (reason) { var topModal = this.getTop(); while (topModal && this.dismiss(topModal.key, reason)) { topModal = this.getTop(); } }; $modalStack.getTop = function () { return openedWindows.top(); }; $modalStack.modalRendered = function (modalInstance) { var modalWindow = openedWindows.get(modalInstance); if (modalWindow) { modalWindow.value.renderDeferred.resolve(); } }; $modalStack.focusFirstFocusableElement = function() { if (focusableElementList.length > 0) { focusableElementList[0].focus(); return true; } return false; }; $modalStack.focusLastFocusableElement = function() { if (focusableElementList.length > 0) { focusableElementList[focusableElementList.length - 1].focus(); return true; } return false; }; $modalStack.isFocusInFirstItem = function(evt) { if (focusableElementList.length > 0) { return (evt.target || evt.srcElement) == focusableElementList[0]; } return false; }; $modalStack.isFocusInLastItem = function(evt) { if (focusableElementList.length > 0) { return (evt.target || evt.srcElement) == focusableElementList[focusableElementList.length - 1]; } return false; }; $modalStack.clearFocusListCache = function() { focusableElementList = []; focusIndex = 0; }; $modalStack.loadFocusElementList = function(modalWindow) { if (focusableElementList === undefined || !focusableElementList.length0) { if (modalWindow) { var modalDomE1 = modalWindow.value.modalDomEl; if (modalDomE1 && modalDomE1.length) { focusableElementList = modalDomE1[0].querySelectorAll(tababbleSelector); } } } }; return $modalStack; }]) .provider('$modal', function () { var $modalProvider = { options: { animation: true, backdrop: true, //can also be false or 'static' keyboard: true }, $get: ['$injector', '$rootScope', '$q', '$templateRequest', '$controller', '$modalStack', function ($injector, $rootScope, $q, $templateRequest, $controller, $modalStack) { var $modal = {}; function getTemplatePromise(options) { return options.template ? $q.when(options.template) : $templateRequest(angular.isFunction(options.templateUrl) ? (options.templateUrl)() : options.templateUrl); } function getResolvePromises(resolves) { var promisesArr = []; angular.forEach(resolves, function (value) { if (angular.isFunction(value) || angular.isArray(value)) { promisesArr.push($q.when($injector.invoke(value))); } else if (angular.isString(value)) { promisesArr.push($q.when($injector.get(value))); } }); return promisesArr; } $modal.open = function (modalOptions) { var modalResultDeferred = $q.defer(); var modalOpenedDeferred = $q.defer(); var modalRenderDeferred = $q.defer(); //prepare an instance of a modal to be injected into controllers and returned to a caller var modalInstance = { result: modalResultDeferred.promise, opened: modalOpenedDeferred.promise, rendered: modalRenderDeferred.promise, close: function (result) { return $modalStack.close(modalInstance, result); }, dismiss: function (reason) { return $modalStack.dismiss(modalInstance, reason); } }; //merge and clean up options modalOptions = angular.extend({}, $modalProvider.options, modalOptions); modalOptions.resolve = modalOptions.resolve || {}; //verify options if (!modalOptions.template && !modalOptions.templateUrl) { throw new Error('One of template or templateUrl options is required.'); } var templateAndResolvePromise = $q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve))); templateAndResolvePromise.then(function resolveSuccess(tplAndVars) { var modalScope = (modalOptions.scope || $rootScope).$new(); modalScope.$close = modalInstance.close; modalScope.$dismiss = modalInstance.dismiss; modalScope.$on('$destroy', function() { if (!modalScope.$$uibDestructionScheduled) { modalScope.$dismiss('$uibUnscheduledDestruction'); } }); var ctrlInstance, ctrlLocals = {}; var resolveIter = 1; //controllers if (modalOptions.controller) { ctrlLocals.$scope = modalScope; ctrlLocals.$modalInstance = modalInstance; angular.forEach(modalOptions.resolve, function (value, key) { ctrlLocals[key] = tplAndVars[resolveIter++]; }); ctrlInstance = $controller(modalOptions.controller, ctrlLocals); if (modalOptions.controllerAs) { if (modalOptions.bindToController) { angular.extend(ctrlInstance, modalScope); } modalScope[modalOptions.controllerAs] = ctrlInstance; } } $modalStack.open(modalInstance, { scope: modalScope, deferred: modalResultDeferred, renderDeferred: modalRenderDeferred, content: tplAndVars[0], animation: modalOptions.animation, backdrop: modalOptions.backdrop, keyboard: modalOptions.keyboard, backdropClass: modalOptions.backdropClass, windowClass: modalOptions.windowClass, windowTemplateUrl: modalOptions.windowTemplateUrl, size: modalOptions.size, openedClass: modalOptions.openedClass }); }, function resolveError(reason) { modalResultDeferred.reject(reason); }); templateAndResolvePromise.then(function () { modalOpenedDeferred.resolve(true); }, function (reason) { modalOpenedDeferred.reject(reason); }); return modalInstance; }; return $modal; }] }; return $modalProvider; }); /** * The following features are still outstanding: animation as a * function, placement as a function, inside, support for more triggers than * just mouse enter/leave, html tooltips, and selector delegation. */ angular.module( 'ui.bootstrap.tooltip', [ 'ui.bootstrap.position', 'ui.bootstrap.bindHtml' ] ) /** * The $tooltip service creates tooltip- and popover-like directives as well as * houses global options for them. */ .provider( '$tooltip', function () { // The default options tooltip and popover. var defaultOptions = { placement: 'top', animation: true, popupDelay: 0, useContentExp: false }; // Default hide triggers for each show trigger var triggerMap = { 'mouseenter': 'mouseleave', 'click': 'click', 'focus': 'blur' }; // The options specified to the provider globally. var globalOptions = {}; /** * `options({})` allows global configuration of all tooltips in the * application. * * var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) { * // place tooltips left instead of top by default * $tooltipProvider.options( { placement: 'left' } ); * }); */ this.options = function( value ) { angular.extend( globalOptions, value ); }; /** * This allows you to extend the set of trigger mappings available. E.g.: * * $tooltipProvider.setTriggers( 'openTrigger': 'closeTrigger' ); */ this.setTriggers = function setTriggers ( triggers ) { angular.extend( triggerMap, triggers ); }; /** * This is a helper function for translating camel-case to snake-case. */ function snake_case(name){ var regexp = /[A-Z]/g; var separator = '-'; return name.replace(regexp, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } /** * Returns the actual instance of the $tooltip service. * TODO support multiple triggers */ this.$get = [ '$window', '$compile', '$timeout', '$document', '$position', '$interpolate', '$rootScope', function ( $window, $compile, $timeout, $document, $position, $interpolate, $rootScope ) { return function $tooltip ( type, prefix, defaultTriggerShow, options ) { options = angular.extend( {}, defaultOptions, globalOptions, options ); /** * Returns an object of show and hide triggers. * * If a trigger is supplied, * it is used to show the tooltip; otherwise, it will use the `trigger` * option passed to the `$tooltipProvider.options` method; else it will * default to the trigger supplied to this directive factory. * * The hide trigger is based on the show trigger. If the `trigger` option * was passed to the `$tooltipProvider.options` method, it will use the * mapped trigger from `triggerMap` or the passed trigger if the map is * undefined; otherwise, it uses the `triggerMap` value of the show * trigger; else it will just use the show trigger. */ function getTriggers ( trigger ) { var show = (trigger || options.trigger || defaultTriggerShow).split(' '); var hide = show.map(function(trigger) { return triggerMap[trigger] || trigger; }); return { show: show, hide: hide }; } var directiveName = snake_case( type ); var startSym = $interpolate.startSymbol(); var endSym = $interpolate.endSymbol(); var template = '<div '+ directiveName +'-popup '+ 'title="'+startSym+'title'+endSym+'" '+ (options.useContentExp ? 'content-exp="contentExp()" ' : 'content="'+startSym+'content'+endSym+'" ') + 'placement="'+startSym+'placement'+endSym+'" '+ 'popup-class="'+startSym+'popupClass'+endSym+'" '+ 'animation="animation" '+ 'is-open="isOpen"'+ 'origin-scope="origScope" '+ '>'+ '</div>'; return { restrict: 'EA', compile: function (tElem, tAttrs) { var tooltipLinker = $compile( template ); return function link ( scope, element, attrs, tooltipCtrl ) { var tooltip; var tooltipLinkedScope; var transitionTimeout; var popupTimeout; var appendToBody = angular.isDefined( options.appendToBody ) ? options.appendToBody : false; var triggers = getTriggers( undefined ); var hasEnableExp = angular.isDefined(attrs[prefix+'Enable']); var ttScope = scope.$new(true); var repositionScheduled = false; var positionTooltip = function () { if (!tooltip) { return; } var ttPosition = $position.positionElements(element, tooltip, ttScope.placement, appendToBody); ttPosition.top += 'px'; ttPosition.left += 'px'; // Now set the calculated positioning. tooltip.css( ttPosition ); }; var positionTooltipAsync = function () { $timeout(positionTooltip, 0, false); }; // Set up the correct scope to allow transclusion later ttScope.origScope = scope; // By default, the tooltip is not open. // TODO add ability to start tooltip opened ttScope.isOpen = false; function toggleTooltipBind () { if ( ! ttScope.isOpen ) { showTooltipBind(); } else { hideTooltipBind(); } } // Show the tooltip with delay if specified, otherwise show it immediately function showTooltipBind() { if(hasEnableExp && !scope.$eval(attrs[prefix+'Enable'])) { return; } prepareTooltip(); if ( ttScope.popupDelay ) { // Do nothing if the tooltip was already scheduled to pop-up. // This happens if show is triggered multiple times before any hide is triggered. if (!popupTimeout) { popupTimeout = $timeout( show, ttScope.popupDelay, false ); popupTimeout.then(function(reposition){reposition();}); } } else { show()(); } } function hideTooltipBind () { hide(); if (!$rootScope.$$phase) { $rootScope.$digest(); } } // Show the tooltip popup element. function show() { popupTimeout = null; // If there is a pending remove transition, we must cancel it, lest the // tooltip be mysteriously removed. if ( transitionTimeout ) { $timeout.cancel( transitionTimeout ); transitionTimeout = null; } // Don't show empty tooltips. if ( !(options.useContentExp ? ttScope.contentExp() : ttScope.content) ) { return angular.noop; } createTooltip(); // Set the initial positioning. tooltip.css({ top: 0, left: 0, display: 'block' }); positionTooltip(); // And show the tooltip. ttScope.isOpen = true; ttScope.$apply(); // digest required as $apply is not called // Return positioning function as promise callback for correct // positioning after draw. return positionTooltip; } // Hide the tooltip popup element. function hide() { // First things first: we don't show it anymore. ttScope.isOpen = false; //if tooltip is going to be shown after delay, we must cancel this $timeout.cancel( popupTimeout ); popupTimeout = null; // And now we remove it from the DOM. However, if we have animation, we // need to wait for it to expire beforehand. // FIXME: this is a placeholder for a port of the transitions library. if ( ttScope.animation ) { if (!transitionTimeout) { transitionTimeout = $timeout(removeTooltip, 500); } } else { removeTooltip(); } } function createTooltip() { // There can only be one tooltip element per directive shown at once. if (tooltip) { removeTooltip(); } tooltipLinkedScope = ttScope.$new(); tooltip = tooltipLinker(tooltipLinkedScope, function (tooltip) { if ( appendToBody ) { $document.find( 'body' ).append( tooltip ); } else { element.after( tooltip ); } }); if (options.useContentExp) { tooltipLinkedScope.$watch('contentExp()', function (val) { if (!val && ttScope.isOpen) { hide(); } }); tooltipLinkedScope.$watch(function() { if (!repositionScheduled) { repositionScheduled = true; tooltipLinkedScope.$$postDigest(function() { repositionScheduled = false; positionTooltipAsync(); }); } }); } } function removeTooltip() { transitionTimeout = null; if (tooltip) { tooltip.remove(); tooltip = null; } if (tooltipLinkedScope) { tooltipLinkedScope.$destroy(); tooltipLinkedScope = null; } } function prepareTooltip() { prepPopupClass(); prepPlacement(); prepPopupDelay(); } ttScope.contentExp = function () { return scope.$eval(attrs[type]); }; /** * Observe the relevant attributes. */ if (!options.useContentExp) { attrs.$observe( type, function ( val ) { ttScope.content = val; if (!val && ttScope.isOpen) { hide(); } else { positionTooltipAsync(); } }); } attrs.$observe( 'disabled', function ( val ) { if (popupTimeout && val) { $timeout.cancel(popupTimeout); } if (val && ttScope.isOpen ) { hide(); } }); attrs.$observe( prefix+'Title', function ( val ) { ttScope.title = val; positionTooltipAsync(); }); attrs.$observe( prefix + 'Placement', function () { if (ttScope.isOpen) { $timeout(function () { prepPlacement(); show()(); }, 0, false); } }); function prepPopupClass() { ttScope.popupClass = attrs[prefix + 'Class']; } function prepPlacement() { var val = attrs[ prefix + 'Placement' ]; ttScope.placement = angular.isDefined( val ) ? val : options.placement; } function prepPopupDelay() { var val = attrs[ prefix + 'PopupDelay' ]; var delay = parseInt( val, 10 ); ttScope.popupDelay = ! isNaN(delay) ? delay : options.popupDelay; } var unregisterTriggers = function () { triggers.show.forEach(function(trigger) { element.unbind(trigger, showTooltipBind); }); triggers.hide.forEach(function(trigger) { element.unbind(trigger, hideTooltipBind); }); }; function prepTriggers() { var val = attrs[ prefix + 'Trigger' ]; unregisterTriggers(); triggers = getTriggers( val ); triggers.show.forEach(function(trigger, idx) { if (trigger === triggers.hide[idx]) { element.bind(trigger, toggleTooltipBind); } else if (trigger) { element.bind(trigger, showTooltipBind); element.bind(triggers.hide[idx], hideTooltipBind); } }); } prepTriggers(); var animation = scope.$eval(attrs[prefix + 'Animation']); ttScope.animation = angular.isDefined(animation) ? !!animation : options.animation; var appendToBodyVal = scope.$eval(attrs[prefix + 'AppendToBody']); appendToBody = angular.isDefined(appendToBodyVal) ? appendToBodyVal : appendToBody; // if a tooltip is attached to <body> we need to remove it on // location change as its parent scope will probably not be destroyed // by the change. if ( appendToBody ) { scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess () { if ( ttScope.isOpen ) { hide(); } }); } // Make sure tooltip is destroyed and removed. scope.$on('$destroy', function onDestroyTooltip() { $timeout.cancel( transitionTimeout ); $timeout.cancel( popupTimeout ); unregisterTriggers(); removeTooltip(); ttScope = null; }); }; } }; }; }]; }) // This is mostly ngInclude code but with a custom scope .directive( 'tooltipTemplateTransclude', [ '$animate', '$sce', '$compile', '$templateRequest', function ($animate , $sce , $compile , $templateRequest) { return { link: function ( scope, elem, attrs ) { var origScope = scope.$eval(attrs.tooltipTemplateTranscludeScope); var changeCounter = 0, currentScope, previousElement, currentElement; var cleanupLastIncludeContent = function() { if (previousElement) { previousElement.remove(); previousElement = null; } if (currentScope) { currentScope.$destroy(); currentScope = null; } if (currentElement) { $animate.leave(currentElement).then(function() { previousElement = null; }); previousElement = currentElement; currentElement = null; } }; scope.$watch($sce.parseAsResourceUrl(attrs.tooltipTemplateTransclude), function (src) { var thisChangeId = ++changeCounter; if (src) { //set the 2nd param to true to ignore the template request error so that the inner //contents and scope can be cleaned up. $templateRequest(src, true).then(function(response) { if (thisChangeId !== changeCounter) { return; } var newScope = origScope.$new(); var template = response; var clone = $compile(template)(newScope, function(clone) { cleanupLastIncludeContent(); $animate.enter(clone, elem); }); currentScope = newScope; currentElement = clone; currentScope.$emit('$includeContentLoaded', src); }, function() { if (thisChangeId === changeCounter) { cleanupLastIncludeContent(); scope.$emit('$includeContentError', src); } }); scope.$emit('$includeContentRequested', src); } else { cleanupLastIncludeContent(); } }); scope.$on('$destroy', cleanupLastIncludeContent); } }; }]) /** * Note that it's intentional that these classes are *not* applied through $animate. * They must not be animated as they're expected to be present on the tooltip on * initialization. */ .directive('tooltipClasses', function () { return { restrict: 'A', link: function (scope, element, attrs) { if (scope.placement) { element.addClass(scope.placement); } if (scope.popupClass) { element.addClass(scope.popupClass); } if (scope.animation()) { element.addClass(attrs.tooltipAnimationClass); } } }; }) .directive( 'tooltipPopup', function () { return { restrict: 'EA', replace: true, scope: { content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, templateUrl: 'template/tooltip/tooltip-popup.html' }; }) .directive( 'tooltip', [ '$tooltip', function ( $tooltip ) { return $tooltip( 'tooltip', 'tooltip', 'mouseenter' ); }]) .directive( 'tooltipTemplatePopup', function () { return { restrict: 'EA', replace: true, scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&', originScope: '&' }, templateUrl: 'template/tooltip/tooltip-template-popup.html' }; }) .directive( 'tooltipTemplate', [ '$tooltip', function ( $tooltip ) { return $tooltip('tooltipTemplate', 'tooltip', 'mouseenter', { useContentExp: true }); }]) .directive( 'tooltipHtmlPopup', function () { return { restrict: 'EA', replace: true, scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, templateUrl: 'template/tooltip/tooltip-html-popup.html' }; }) .directive( 'tooltipHtml', [ '$tooltip', function ( $tooltip ) { return $tooltip('tooltipHtml', 'tooltip', 'mouseenter', { useContentExp: true }); }]) /* Deprecated */ .directive( 'tooltipHtmlUnsafePopup', function () { return { restrict: 'EA', replace: true, scope: { content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, templateUrl: 'template/tooltip/tooltip-html-unsafe-popup.html' }; }) .value('tooltipHtmlUnsafeSuppressDeprecated', false) .directive( 'tooltipHtmlUnsafe', [ '$tooltip', 'tooltipHtmlUnsafeSuppressDeprecated', '$log', function ( $tooltip , tooltipHtmlUnsafeSuppressDeprecated , $log) { if (!tooltipHtmlUnsafeSuppressDeprecated) { $log.warn('tooltip-html-unsafe is now deprecated. Use tooltip-html or tooltip-template instead.'); } return $tooltip( 'tooltipHtmlUnsafe', 'tooltip', 'mouseenter' ); }]); angular.module('ui.bootstrap.bindHtml', []) .value('$bindHtmlUnsafeSuppressDeprecated', false) .directive('bindHtmlUnsafe', ['$log', '$bindHtmlUnsafeSuppressDeprecated', function ($log, $bindHtmlUnsafeSuppressDeprecated) { return function (scope, element, attr) { if (!$bindHtmlUnsafeSuppressDeprecated) { $log.warn('bindHtmlUnsafe is now deprecated. Use ngBindHtml instead'); } element.addClass('ng-binding').data('$binding', attr.bindHtmlUnsafe); scope.$watch(attr.bindHtmlUnsafe, function bindHtmlUnsafeWatchAction(value) { element.html(value || ''); }); }; }]); angular.module('ui.bootstrap.collapse', []) .directive('collapse', ['$animate', function ($animate) { return { link: function (scope, element, attrs) { function expand() { element.removeClass('collapse') .addClass('collapsing') .attr('aria-expanded', true) .attr('aria-hidden', false); $animate.addClass(element, 'in', { to: { height: element[0].scrollHeight + 'px' } }).then(expandDone); } function expandDone() { element.removeClass('collapsing'); element.css({height: 'auto'}); } function collapse() { if(! element.hasClass('collapse') && ! element.hasClass('in')) { return collapseDone(); } element // IMPORTANT: The height must be set before adding "collapsing" class. // Otherwise, the browser attempts to animate from height 0 (in // collapsing class) to the given height here. .css({height: element[0].scrollHeight + 'px'}) // initially all panel collapse have the collapse class, this removal // prevents the animation from jumping to collapsed state .removeClass('collapse') .addClass('collapsing') .attr('aria-expanded', false) .attr('aria-hidden', true); $animate.removeClass(element, 'in', { to: {height: '0'} }).then(collapseDone); } function collapseDone() { element.css({height: '0'}); // Required so that collapse works when animation is disabled element.removeClass('collapsing'); element.addClass('collapse'); } scope.$watch(attrs.collapse, function (shouldCollapse) { if (shouldCollapse) { collapse(); } else { expand(); } }); } }; }]); angular.module('ui.bootstrap.transition', []) .value('$transitionSuppressDeprecated', false) /** * $transition service provides a consistent interface to trigger CSS 3 transitions and to be informed when they complete. * @param {DOMElement} element The DOMElement that will be animated. * @param {string|object|function} trigger The thing that will cause the transition to start: * - As a string, it represents the css class to be added to the element. * - As an object, it represents a hash of style attributes to be applied to the element. * - As a function, it represents a function to be called that will cause the transition to occur. * @return {Promise} A promise that is resolved when the transition finishes. */ .factory('$transition', [ '$q', '$timeout', '$rootScope', '$log', '$transitionSuppressDeprecated', function($q , $timeout , $rootScope , $log , $transitionSuppressDeprecated) { if (!$transitionSuppressDeprecated) { $log.warn('$transition is now deprecated. Use $animate from ngAnimate instead.'); } var $transition = function(element, trigger, options) { options = options || {}; var deferred = $q.defer(); var endEventName = $transition[options.animation ? 'animationEndEventName' : 'transitionEndEventName']; var transitionEndHandler = function(event) { $rootScope.$apply(function() { element.unbind(endEventName, transitionEndHandler); deferred.resolve(element); }); }; if (endEventName) { element.bind(endEventName, transitionEndHandler); } // Wrap in a timeout to allow the browser time to update the DOM before the transition is to occur $timeout(function() { if ( angular.isString(trigger) ) { element.addClass(trigger); } else if ( angular.isFunction(trigger) ) { trigger(element); } else if ( angular.isObject(trigger) ) { element.css(trigger); } //If browser does not support transitions, instantly resolve if ( !endEventName ) { deferred.resolve(element); } }); // Add our custom cancel function to the promise that is returned // We can call this if we are about to run a new transition, which we know will prevent this transition from ending, // i.e. it will therefore never raise a transitionEnd event for that transition deferred.promise.cancel = function() { if ( endEventName ) { element.unbind(endEventName, transitionEndHandler); } deferred.reject('Transition cancelled'); }; return deferred.promise; }; // Work out the name of the transitionEnd event var transElement = document.createElement('trans'); var transitionEndEventNames = { 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'transitionend', 'OTransition': 'oTransitionEnd', 'transition': 'transitionend' }; var animationEndEventNames = { 'WebkitTransition': 'webkitAnimationEnd', 'MozTransition': 'animationend', 'OTransition': 'oAnimationEnd', 'transition': 'animationend' }; function findEndEventName(endEventNames) { for (var name in endEventNames){ if (transElement.style[name] !== undefined) { return endEventNames[name]; } } } $transition.transitionEndEventName = findEndEventName(transitionEndEventNames); $transition.animationEndEventName = findEndEventName(animationEndEventNames); return $transition; }]);
rawrsome/leaddyno_recurly_example
public/ui-bootstrap-custom-build/ui-bootstrap-custom-0.13.3.js
JavaScript
mit
72,502
importScripts('/node_modules/chai/chai.js') importScripts('/node_modules/mocha/mocha.js') mocha.setup('tdd') self.assert = chai.assert importScripts('/node_modules/promise-polyfill/promise.js') importScripts('/test/test.js') importScripts('/fetch.js') function title(test) { return test.fullTitle().replace(/#/g, ''); } function reporter(runner) { runner.on('pending', function(test){ self.postMessage({name: 'pending', title: title(test)}); }); runner.on('pass', function(test){ self.postMessage({name: 'pass', title: title(test)}); }); runner.on('fail', function(test, err){ self.postMessage({ name: 'fail', title: title(test), message: err.message, stack: err.stack }); }); runner.on('end', function(){ self.postMessage({name: 'end'}); }); } mocha.reporter(reporter).run()
benestudio/fetch
test/worker.js
JavaScript
mit
846
/*! jQuery UI - v1.9.2 - 2016-12-18 * http://jqueryui.com * Copyright jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(t){t.datepicker.regional.bs={closeText:"Zatvori",prevText:"&#x3C;",nextText:"&#x3E;",currentText:"Danas",monthNames:["Januar","Februar","Mart","April","Maj","Juni","Juli","August","Septembar","Oktobar","Novembar","Decembar"],monthNamesShort:["Jan","Feb","Mar","Apr","Maj","Jun","Jul","Aug","Sep","Okt","Nov","Dec"],dayNames:["Nedelja","Ponedeljak","Utorak","Srijeda","Četvrtak","Petak","Subota"],dayNamesShort:["Ned","Pon","Uto","Sri","Čet","Pet","Sub"],dayNamesMin:["Ne","Po","Ut","Sr","Če","Pe","Su"],weekHeader:"Wk",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional.bs)});
brakmic/Angular_VRDemo
src/vendor/jquery-ui/development-bundle/ui/minified/i18n/jquery.ui.datepicker-bs.min.js
JavaScript
mit
799
/** * jQuery Accessible combobox v0.1.0 * https://github.com/choi4450/jquery.accessiblecombobox * * Copyright 2015 Gyumin Choi Foundation and other contributors * Released under the MIT license * https://github.com/choi4450/jquery.accessiblecombobox/blob/master/LICENSE.txt */ (function($) { $.fn.accessibleComboboxConfig = { label: 'Select another option', bullet: '', style: null, animate: false, duration: 0, easingOpen: null, easingClose: null }; $.fn.accessibleCombobox = function(defaults) { if (navigator.userAgent.indexOf("MSIE 6") >= 0) return false; var config = $.extend({}, $.fn.accessibleComboboxConfig, defaults), fn = {}, dom = {}; dom.cbo = $(this); config.elemId = dom.cbo.attr('id') || ''; config.elemClass = dom.cbo.attr('class') || ''; config.elemName = dom.cbo.attr('name') || ''; config.elemTitle = dom.cbo.attr('title') || ''; config.elemWidth = dom.cbo.width(); config.selectedOpt = dom.cbo.find('option:selected'); config.selectedOptTxt = config.selectedOpt.text(); config.propDisabled = dom.cbo.prop('disabled'); config.propRequired = dom.cbo.prop('required'); fn.replaceCbo = function() { var attrGroup = {}; attrGroup.boxSelector = 'class="' + config.elemClass + ' accessiblecbo'; attrGroup.boxSelector += config.propDisabled ? ' is-disabled"' : '"'; attrGroup.boxSelector += config.elemId != '' ? ' id="' + config.elemId + '"' : ''; attrGroup.btnTitle = config.elemTitle != '' ? 'title="' + config.elemTitle + '"' : ''; attrGroup.btnLabel = 'aria-label="' + config.label + '"'; attrGroup.optName = config.elemName != '' ? 'name="' + config.elemName + '"' : ''; attrGroup.boxRequired = config.propRequired ? 'aria-required="true"' : ''; attrGroup.optRequired = config.propRequired ? 'required="required"' : ''; attrGroup.btnDisabled = config.propDisabled ? 'aria-disabled="true" tabindex="-1"' : ''; attrGroup.optDisabled = config.propDisabled ? 'disabled="disabled"' : ''; var addOptionHtmlStr = function(element) { var returnHtmlStr = ''; element.each(function(_i) { var $this = $(this), thisAttrVal = $this.val() ? 'value="' + $this.val() + '"' : '', selectedClass = '', selectedAttr = ''; if ($this.prop('selected')) { selectedClass = $this.prop('selected') ? ' is-selected' : ''; selectedAttr = $this.prop('selected') ? 'checked="checked"' : ''; } returnHtmlStr += '<label class="accessiblecbo-opt' + selectedClass + '">' + '<input type="radio" class="accessiblecbo-opt-radio" ' + attrGroup.optName + ' ' + thisAttrVal + ' ' + attrGroup.optDisabled + ' ' + attrGroup.optRequired + ' ' + selectedAttr + '>' + '<span class="accessiblecbo-opt-txt">' + $this.text() + '</span>' + '</label>'; }); return returnHtmlStr; }; var replaceHtmlStr = '<span ' + attrGroup.boxSelector + ' role="menu" aria-live="polite" aria-relevant="all" aria-haspopup="true" aria-expanded="false" style="width: ' + config.elemWidth + 'px;" ' + attrGroup.btnDisabled + ' ' + attrGroup.boxRequired + '>' + '<a href="#" class="accessiblecbo-btn" role="button" aria-live="off" ' + attrGroup.btnTitle + ' ' + attrGroup.btnLabel + ' ' + attrGroup.btnDisabled + '>' + '<span class="accessiblecbo-btn-txt">' + config.selectedOptTxt + '</span>' + '<span class="accessiblecbo-btn-bu" aria-hidden="true">' + config.bullet + '</span>' + '</a>' + '<span class="accessiblecbo-listbox" role="radiogroup" aria-hidden="true" ' + attrGroup.boxRequired + '>' + '<span class="accessiblecbo-listbox-wrap">'; dom.cbo.find('>*').each(function(_i) { var $this = $(this); if ($this.is('optgroup')) { replaceHtmlStr += '<span class="accessiblecbo-optgroup" role="radiogroup">' + '<em class="accessiblecbo-optgroup-tit">Optgroup</em>' + addOptionHtmlStr($this.find('option')) + '</span>'; } else { replaceHtmlStr += addOptionHtmlStr($this); } }); replaceHtmlStr += '</span>' + '</span>' + '</span>'; var replaceHtml = $(replaceHtmlStr); dom.cbo.replaceWith(replaceHtml); dom.cbo = replaceHtml; dom.cboBtn = dom.cbo.find('.accessiblecbo-btn'); dom.cboBtnTxt = dom.cboBtn.find('.accessiblecbo-btn-txt'); dom.cboListbox = dom.cbo.find('.accessiblecbo-listbox'); dom.cboOpt = dom.cboListbox.find('.accessiblecbo-opt'); dom.cboOptRadio = dom.cboOpt.find('.accessiblecbo-opt-radio'); }; fn.toggleExpandCbo = function(action) { if (typeof action == 'undefined') action = 'toggle'; var propExpanded = dom.cbo.attr('aria-expanded'), setOpenExpanded = function() { dom.cbo.attr('aria-expanded', 'true').addClass('is-expanded'); dom.cboListbox.attr('aria-hidden', 'false'); dom.cboOptRadio.filter(':checked').focus(); }, setCloseExpanded = function() { dom.cbo.attr('aria-expanded', 'false').removeClass('is-expanded'); dom.cboListbox.attr('aria-hidden', 'true'); }, returnBoolChkAction = function(chk) { return action == 'toggle' || action == chk; }; if (returnBoolChkAction('open') && propExpanded == 'false') { setOpenExpanded(); setTimeout(function() { $(document).one('click.accessibleCbo-closeExpanded', function(e) { if (dom.cbo.has(e.target).length < 1) setCloseExpanded(); }); }, 0); } else if (returnBoolChkAction('close') && propExpanded == 'true') { setCloseExpanded(); $(document).off('.accessibleCbo-closeExpanded'); } }; fn.activeOpt = function(element, change) { var thisOpt = element, thisOptRadio = thisOpt.find('.accessiblecbo-opt-radio'); if (typeof change == 'undefined') change = true; dom.cboOpt.removeClass('is-selected'); thisOpt.addClass('is-selected'); if (change == true) { thisOptRadio.focus().prop('checked', true); dom.cboBtnTxt.text(thisOptRadio.siblings('.accessiblecbo-opt-txt').text()); } }; fn.replaceCbo(); dom.cboBtn.on('click', function(e) { e.preventDefault(); if (e.type != 'keydown' || e.keyCode === 13 || e.keyCode === 32) { if (!config.propDisabled) { fn.toggleExpandCbo(); } } }); dom.cboOpt.on({ mouseover: function(e) { var $this = $(this); fn.activeOpt($this, false); }, mousedown: function(e) { var $this = $(this); fn.activeOpt($this); fn.toggleExpandCbo('close'); } }); dom.cboOptRadio.on('keydown', function(e) { var $this = $(this); if (e.keyCode === 9 || e.keyCode === 13) { e.preventDefault(); dom.cboBtn.focus(); fn.toggleExpandCbo('close'); } else if (e.keyCode >= 37 && e.keyCode <= 40) { e.preventDefault(); var thisOpt = $this.parent('.accessiblecbo-opt'), thisOptIdx = dom.cboOpt.index(thisOpt), controlsOpt, allOptLen = dom.cboOpt.length, listboxHeight = dom.cboListbox.height(), listboxOffsetTop = dom.cboListbox.offset().top, listboxScrollTop = dom.cboListbox.scrollTop(); if (e.keyCode >= 37 && e.keyCode <= 38) { if (thisOptIdx == 0) controlsOpt = dom.cboOpt.last(); else controlsOpt = dom.cboOpt.eq(thisOptIdx - 1); } else if (e.keyCode >= 39 && e.keyCode <= 40) { if (thisOptIdx == (allOptLen - 1)) controlsOpt = dom.cboOpt.first(); else controlsOpt = dom.cboOpt.eq(thisOptIdx + 1); } var controlsOptHeight = controlsOpt.height(), controlsOptOffsetTop = controlsOpt.offset().top - listboxOffsetTop + listboxScrollTop; setTimeout(function() { fn.activeOpt(controlsOpt); if (controlsOptOffsetTop >= (listboxHeight + listboxScrollTop)) { dom.cboListbox.scrollTop(controlsOptOffsetTop - (listboxHeight - controlsOptHeight)); } else if (controlsOptOffsetTop < listboxScrollTop) { dom.cboListbox.scrollTop(controlsOptOffsetTop); } }, 0); } }); }; $(function() { $('select[data-accessiblecbo]').each(function() { var $this = $(this), argumentStr = $this.attr('data-accessiblecbo'), argumentObj = eval('({' + argumentStr + '})'); $this.accessibleCombobox(argumentObj); }); }); }(jQuery));
choi4450/combobAx
dist/jquery.accessiblecombobox-0.1.0.js
JavaScript
mit
8,150
export { default } from 'ember-paper/components/paper-autocomplete/eps-trigger/component';
bjornharrtell/ember-paper
app/components/paper-autocomplete/eps-trigger.js
JavaScript
mit
91
/** * ReturnTrue */ var returnTrue = function() { return true; };
apiaryio/Amanda
src/utils/returnTrue.js
JavaScript
mit
69
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.autobahn = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; function drainQueue() { if (draining) { return; } draining = true; var currentQueue; var len = queue.length; while(len) { currentQueue = queue; queue = []; var i = -1; while (++i < len) { currentQueue[i](); } len = queue.length; } draining = false; } process.nextTick = function (fun) { queue.push(fun); if (!draining) { setTimeout(drainQueue, 0); } }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],2:[function(require,module,exports){ /////////////////////////////////////////////////////////////////////////////// // // AutobahnJS - http://autobahn.ws, http://wamp.ws // // A JavaScript library for WAMP ("The Web Application Messaging Protocol"). // // Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com // // Licensed under the MIT License. // http://www.opensource.org/licenses/mit-license.php // /////////////////////////////////////////////////////////////////////////////// // require('assert') would be nice .. but it does not // work with Google Closure after Browserify var crypto = require('crypto-js'); // PBKDF2-base key derivation function for salted WAMP-CRA // function derive_key (secret, salt, iterations, keylen) { var iterations = iterations || 1000; var keylen = keylen || 32; var config = { keySize: keylen / 4, iterations: iterations, hasher: crypto.algo.SHA256 } var key = crypto.PBKDF2(secret, salt, config); return key.toString(crypto.enc.Base64); } function sign (key, challenge) { return crypto.HmacSHA256(challenge, key).toString(crypto.enc.Base64); } exports.sign = sign; exports.derive_key = derive_key; },{"crypto-js":28}],3:[function(require,module,exports){ /////////////////////////////////////////////////////////////////////////////// // // AutobahnJS - http://autobahn.ws, http://wamp.ws // // A JavaScript library for WAMP ("The Web Application Messaging Protocol"). // // Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com // // Licensed under the MIT License. // http://www.opensource.org/licenses/mit-license.php // /////////////////////////////////////////////////////////////////////////////// var when = require('when'); var when_fn = require("when/function"); function auth(session, user, extra) { // Persona Issues: // // Chrome: https://github.com/mozilla/persona/issues/4083 // IE11: https://groups.google.com/forum/#!topic/mozilla.dev.identity/keEkVpvfLA8 var d = session.defer(); navigator.id.watch({ loggedInUser: user, onlogin: function (assertion) { // A user has logged in! Here you need to: // 1. Send the assertion to your backend for verification and to create a session. // 2. Update your UI. d.resolve(assertion); }, onlogout: function() { // A user has logged out! Here you need to: // Tear down the user's session by redirecting the user or making a call to your backend. // Also, make sure loggedInUser will get set to null on the next page load. // (That's a literal JavaScript null. Not false, 0, or undefined. null.) session.leave("wamp.close.logout"); } }); if (d.promise.then) { // whenjs has the actual user promise in an attribute return d.promise; } else { return d; } } exports.auth = auth; },{"when":78,"when/function":54}],4:[function(require,module,exports){ (function (global){ /////////////////////////////////////////////////////////////////////////////// // // AutobahnJS - http://autobahn.ws, http://wamp.ws // // A JavaScript library for WAMP ("The Web Application Messaging Protocol"). // // Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com // // Licensed under the MIT License. // http://www.opensource.org/licenses/mit-license.php // /////////////////////////////////////////////////////////////////////////////// // Polyfills for <= IE9 require('./polyfill.js'); var pjson = require('../package.json'); var when = require('when'); //var fn = require("when/function"); if ('AUTOBAHN_DEBUG' in global && AUTOBAHN_DEBUG) { // https://github.com/cujojs/when/blob/master/docs/api.md#whenmonitor require('when/monitor/console'); if ('console' in global) { console.log("AutobahnJS debug enabled"); } } var util = require('./util.js'); var log = require('./log.js'); var session = require('./session.js'); var connection = require('./connection.js'); var configure = require('./configure.js'); var persona = require('./auth/persona.js'); var cra = require('./auth/cra.js'); exports.version = pjson.version; exports.transports = configure.transports; exports.Connection = connection.Connection; exports.Session = session.Session; exports.Invocation = session.Invocation; exports.Event = session.Event; exports.Result = session.Result; exports.Error = session.Error; exports.Subscription = session.Subscription; exports.Registration = session.Registration; exports.Publication = session.Publication; exports.auth_persona = persona.auth; exports.auth_cra = cra; exports.when = when; exports.util = util; exports.log = log; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../package.json":80,"./auth/cra.js":2,"./auth/persona.js":3,"./configure.js":5,"./connection.js":6,"./log.js":7,"./polyfill.js":8,"./session.js":16,"./util.js":19,"when":78,"when/monitor/console":76}],5:[function(require,module,exports){ /////////////////////////////////////////////////////////////////////////////// // // AutobahnJS - http://autobahn.ws, http://wamp.ws // // A JavaScript library for WAMP ("The Web Application Messaging Protocol"). // // Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com // // Licensed under the MIT License. // http://www.opensource.org/licenses/mit-license.php // /////////////////////////////////////////////////////////////////////////////// function Transports() { this._repository = {}; } Transports.prototype.register = function (name, factory) { this._repository[name] = factory; }; Transports.prototype.isRegistered = function (name) { return this._repository[name] ? true : false; }; Transports.prototype.get = function (name) { if (this._repository[name] !== undefined) { return this._repository[name]; } else { throw "no such transport: " + name; } } Transports.prototype.list = function() { var items = []; for (var name in this._repository) { items.push(name); } return items; }; var _transports = new Transports(); // register default transports var websocket = require('./transport/websocket.js'); _transports.register("websocket", websocket.Factory); var longpoll = require('./transport/longpoll.js'); _transports.register("longpoll", longpoll.Factory); exports.transports = _transports; },{"./transport/longpoll.js":17,"./transport/websocket.js":18}],6:[function(require,module,exports){ (function (global){ /////////////////////////////////////////////////////////////////////////////// // // AutobahnJS - http://autobahn.ws, http://wamp.ws // // A JavaScript library for WAMP ("The Web Application Messaging Protocol"). // // Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com // // Licensed under the MIT License. // http://www.opensource.org/licenses/mit-license.php // /////////////////////////////////////////////////////////////////////////////// var when = require('when'); var session = require('./session.js'); var util = require('./util.js'); var log = require('./log.js'); var autobahn = require('./autobahn.js'); var Connection = function (options) { var self = this; self._options = options; // Deferred factory // if (options && options.use_es6_promises) { if ('Promise' in global) { // ES6-based deferred factory // self._defer = function () { var deferred = {}; deferred.promise = new Promise(function (resolve, reject) { deferred.resolve = resolve; deferred.reject = reject; }); return deferred; }; } else { log.debug("Warning: ES6 promises requested, but not found! Falling back to whenjs."); // whenjs-based deferred factory // self._defer = when.defer; } } else if (options && options.use_deferred) { // use explicit deferred factory, e.g. jQuery.Deferred or Q.defer // self._defer = options.use_deferred; } else { // whenjs-based deferred factory // self._defer = when.defer; } // WAMP transport // // backward compatiblity if (!self._options.transports) { self._options.transports = [ { type: 'websocket', url: self._options.url } ]; } self._transport_factories = []; self._init_transport_factories(); // WAMP session // self._session = null; self._session_close_reason = null; self._session_close_message = null; // automatic reconnection configuration // // enable automatic reconnect if host is unreachable if (self._options.retry_if_unreachable !== undefined) { self._retry_if_unreachable = self._options.retry_if_unreachable; } else { self._retry_if_unreachable = true; } // maximum number of reconnection attempts self._max_retries = self._options.max_retries || 15; // initial retry delay in seconds self._initial_retry_delay = self._options.initial_retry_delay || 1.5; // maximum seconds between reconnection attempts self._max_retry_delay = self._options.max_retry_delay || 300; // the growth factor applied to the retry delay on each retry cycle self._retry_delay_growth = self._options.retry_delay_growth || 1.5; // the SD of a Gaussian to jitter the delay on each retry cycle // as a fraction of the mean self._retry_delay_jitter = self._options.retry_delay_jitter || 0.1; // reconnection tracking // // total number of successful connections self._connect_successes = 0; // controls if we should try to reconnect self._retry = false; // current number of reconnect cycles we went through self._retry_count = 0; // the current retry delay self._retry_delay = self._initial_retry_delay; // flag indicating if we are currently in a reconnect cycle self._is_retrying = false; // when retrying, this is the timer object returned from window.setTimeout() self._retry_timer = null; }; Connection.prototype._create_transport = function () { for (var i = 0; i < this._transport_factories.length; ++i) { var transport_factory = this._transport_factories[i]; log.debug("trying to create WAMP transport of type: " + transport_factory.type); try { var transport = transport_factory.create(); if (transport) { log.debug("using WAMP transport type: " + transport_factory.type); return transport; } } catch (e) { // ignore log.debug("could not create WAMP transport '" + transport_factory.type + "': " + e); } } // could not create any WAMP transport return null; }; Connection.prototype._init_transport_factories = function () { // WAMP transport // var transports, transport_options, transport_factory, transport_factory_klass; util.assert(this._options.transports, "No transport.factory specified"); transports = this._options.transports; //if(typeof transports === "object") { // this._options.transports = [transports]; //} for(var i = 0; i < this._options.transports.length; ++i) { // cascading transports until we find one which works transport_options = this._options.transports[i]; if (!transport_options.url) { // defaulting to options.url if none is provided transport_options.url = this._options.url; } if (!transport_options.protocols) { transport_options.protocols = this._options.protocols; } util.assert(transport_options.type, "No transport.type specified"); util.assert(typeof transport_options.type === "string", "transport.type must be a string"); try { transport_factory_klass = autobahn.transports.get(transport_options.type); if (transport_factory_klass) { transport_factory = new transport_factory_klass(transport_options); this._transport_factories.push(transport_factory); } } catch (exc) { console.error(exc); } } }; Connection.prototype._autoreconnect_reset_timer = function () { var self = this; if (self._retry_timer) { clearTimeout(self._retry_timer); } self._retry_timer = null; } Connection.prototype._autoreconnect_reset = function () { var self = this; self._autoreconnect_reset_timer(); self._retry_count = 0; self._retry_delay = self._initial_retry_delay; self._is_retrying = false; } Connection.prototype._autoreconnect_advance = function () { var self = this; // jitter retry delay if (self._retry_delay_jitter) { self._retry_delay = util.rand_normal(self._retry_delay, self._retry_delay * self._retry_delay_jitter); } // cap the retry delay if (self._retry_delay > self._max_retry_delay) { self._retry_delay = self._max_retry_delay; } // count number of retries self._retry_count += 1; var res; if (self._retry && self._retry_count <= self._max_retries) { res = { count: self._retry_count, delay: self._retry_delay, will_retry: true }; } else { res = { count: null, delay: null, will_retry: false } } // retry delay growth for next retry cycle if (self._retry_delay_growth) { self._retry_delay = self._retry_delay * self._retry_delay_growth; } return res; } Connection.prototype.open = function () { var self = this; if (self._transport) { throw "connection already open (or opening)"; } self._autoreconnect_reset(); self._retry = true; function retry () { // create a WAMP transport self._transport = self._create_transport(); if (!self._transport) { // failed to create a WAMP transport self._retry = false; if (self.onclose) { var details = { reason: null, message: null, retry_delay: null, retry_count: null, will_retry: false }; self.onclose("unsupported", details); } return; } // create a new WAMP session using the WebSocket connection as transport self._session = new session.Session(self._transport, self._defer, self._options.onchallenge); self._session_close_reason = null; self._session_close_message = null; self._transport.onopen = function () { // reset auto-reconnect timer and tracking self._autoreconnect_reset(); // log successful connections self._connect_successes += 1; // start WAMP session self._session.join(self._options.realm, self._options.authmethods, self._options.authid); }; self._session.onjoin = function (details) { if (self.onopen) { try { self.onopen(self._session, details); } catch (e) { log.debug("Exception raised from app code while firing Connection.onopen()", e); } } }; // // ... WAMP session is now attached to realm. // self._session.onleave = function (reason, details) { self._session_close_reason = reason; self._session_close_message = details.message || ""; self._retry = false; self._transport.close(1000); }; self._transport.onclose = function (evt) { // remove any pending reconnect timer self._autoreconnect_reset_timer(); self._transport = null; var reason = null; if (self._connect_successes === 0) { reason = "unreachable"; if (!self._retry_if_unreachable) { self._retry = false; } } else if (!evt.wasClean) { reason = "lost"; } else { reason = "closed"; } var next_retry = self._autoreconnect_advance(); // fire app code handler // if (self.onclose) { var details = { reason: self._session_close_reason, message: self._session_close_message, retry_delay: next_retry.delay, retry_count: next_retry.count, will_retry: next_retry.will_retry }; try { // Connection.onclose() allows to cancel any subsequent retry attempt var stop_retrying = self.onclose(reason, details); } catch (e) { log.debug("Exception raised from app code while firing Connection.onclose()", e); } } // reset session info // if (self._session) { self._session._id = null; self._session = null; self._session_close_reason = null; self._session_close_message = null; } // automatic reconnection // if (self._retry && !stop_retrying) { if (next_retry.will_retry) { self._is_retrying = true; log.debug("retrying in " + next_retry.delay + " s"); self._retry_timer = setTimeout(retry, next_retry.delay * 1000); } else { log.debug("giving up trying to reconnect"); } } } } retry(); }; Connection.prototype.close = function (reason, message) { var self = this; if (!self._transport && !self._is_retrying) { throw "connection already closed"; } // the app wants to close .. don't retry self._retry = false; if (self._session && self._session.isOpen) { // if there is an open session, close that first. self._session.leave(reason, message); } else if (self._transport) { // no session active: just close the transport self._transport.close(1000); } }; Object.defineProperty(Connection.prototype, "defer", { get: function () { return this._defer; } }); Object.defineProperty(Connection.prototype, "session", { get: function () { return this._session; } }); Object.defineProperty(Connection.prototype, "isOpen", { get: function () { if (this._session && this._session.isOpen) { return true; } else { return false; } } }); Object.defineProperty(Connection.prototype, "isConnected", { get: function () { if (this._transport) { return true; } else { return false; } } }); Object.defineProperty(Connection.prototype, "transport", { get: function () { if (this._transport) { return this._transport; } else { return {info: {type: 'none', url: null, protocol: null}}; } } }); Object.defineProperty(Connection.prototype, "isRetrying", { get: function () { return this._is_retrying; } }); exports.Connection = Connection; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./autobahn.js":4,"./log.js":7,"./session.js":16,"./util.js":19,"when":78}],7:[function(require,module,exports){ (function (global){ /////////////////////////////////////////////////////////////////////////////// // // AutobahnJS - http://autobahn.ws, http://wamp.ws // // A JavaScript library for WAMP ("The Web Application Messaging Protocol"). // // Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com // // Licensed under the MIT License. // http://www.opensource.org/licenses/mit-license.php // /////////////////////////////////////////////////////////////////////////////// var debug = function () {}; if ('AUTOBAHN_DEBUG' in global && AUTOBAHN_DEBUG && 'console' in global) { debug = function () { console.log.apply(console, arguments); } } exports.debug = debug; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],8:[function(require,module,exports){ require('./polyfill/object'); require('./polyfill/array'); require('./polyfill/string'); require('./polyfill/function'); require('./polyfill/console'); require('./polyfill/typedarray'); require('./polyfill/json'); },{"./polyfill/array":9,"./polyfill/console":10,"./polyfill/function":11,"./polyfill/json":12,"./polyfill/object":13,"./polyfill/string":14,"./polyfill/typedarray":15}],9:[function(require,module,exports){ if ( 'function' !== typeof Array.prototype.reduce ) { Array.prototype.reduce = function( callback /*, initialValue*/ ) { 'use strict'; var len, t, value, k; if ( null === this || 'undefined' === typeof this ) { throw new TypeError( 'Array.prototype.reduce called on null or undefined' ); } if ( 'function' !== typeof callback ) { throw new TypeError( callback + ' is not a function' ); } t = Object( this ); len = t.length >>> 0; k = 0; if ( arguments.length >= 2 ) { value = arguments[1]; } else { while ( k < len && ! k in t ) k++; if ( k >= len ) throw new TypeError('Reduce of empty array with no initial value'); value = t[ k++ ]; } for ( ; k < len ; k++ ) { if ( k in t ) { value = callback( value, t[k], k, t ); } } return value; }; } // Add ECMA262-5 Array methods if not supported natively // if (!('indexOf' in Array.prototype)) { Array.prototype.indexOf= function(find, i /*opt*/) { if (i===undefined) i= 0; if (i<0) i+= this.length; if (i<0) i= 0; for (var n= this.length; i<n; i++) if (i in this && this[i]===find) return i; return -1; }; } if (!('lastIndexOf' in Array.prototype)) { Array.prototype.lastIndexOf= function(find, i /*opt*/) { if (i===undefined) i= this.length-1; if (i<0) i+= this.length; if (i>this.length-1) i= this.length-1; for (i++; i-->0;) /* i++ because from-argument is sadly inclusive */ if (i in this && this[i]===find) return i; return -1; }; } if (!('forEach' in Array.prototype)) { Array.prototype.forEach= function(action, that /*opt*/) { for (var i= 0, n= this.length; i<n; i++) if (i in this) action.call(that, this[i], i, this); }; } if (!('map' in Array.prototype)) { Array.prototype.map= function(mapper, that /*opt*/) { var other= new Array(this.length); for (var i= 0, n= this.length; i<n; i++) if (i in this) other[i]= mapper.call(that, this[i], i, this); return other; }; } if (!('filter' in Array.prototype)) { Array.prototype.filter= function(filter, that /*opt*/) { var other= [], v; for (var i=0, n= this.length; i<n; i++) if (i in this && filter.call(that, v= this[i], i, this)) other.push(v); return other; }; } if (!('every' in Array.prototype)) { Array.prototype.every= function(tester, that /*opt*/) { for (var i= 0, n= this.length; i<n; i++) if (i in this && !tester.call(that, this[i], i, this)) return false; return true; }; } if (!('some' in Array.prototype)) { Array.prototype.some= function(tester, that /*opt*/) { for (var i= 0, n= this.length; i<n; i++) if (i in this && tester.call(that, this[i], i, this)) return true; return false; }; } if ( 'function' !== typeof Array.prototype.reduceRight ) { Array.prototype.reduceRight = function( callback /*, initialValue*/ ) { 'use strict'; if ( null === this || 'undefined' === typeof this ) { throw new TypeError( 'Array.prototype.reduce called on null or undefined' ); } if ( 'function' !== typeof callback ) { throw new TypeError( callback + ' is not a function' ); } var t = Object( this ), len = t.length >>> 0, k = len - 1, value; if ( arguments.length >= 2 ) { value = arguments[1]; } else { while ( k >= 0 && ! k in t ) k--; if ( k < 0 ) throw new TypeError('Reduce of empty array with no initial value'); value = t[ k-- ]; } for ( ; k >= 0 ; k-- ) { if ( k in t ) { value = callback( value, t[k], k, t ); } } return value; }; } },{}],10:[function(require,module,exports){ (function (global){ (function(console) { /********************************************************************************************* * Make sure console exists because IE blows up if it's not open and you attempt to access it * Create some dummy functions if we need to, so we don't have to if/else everything *********************************************************************************************/ console||(console = window.console = { // all this "a, b, c, d, e" garbage is to make the IDEs happy, since they can't do variable argument lists /** * @param a * @param [b] * @param [c] * @param [d] * @param [e] */ log: function(a, b, c, d, e) {}, /** * @param a * @param [b] * @param [c] * @param [d] * @param [e] */ info: function(a, b, c, d, e) {}, /** * @param a * @param [b] * @param [c] * @param [d] * @param [e] */ warn: function(a, b, c, d, e) {}, /** * @param a * @param [b] * @param [c] * @param [d] * @param [e] */ error: function(a, b, c, d, e) {}, assert: function(test, message) {} }); // IE 9 won't allow us to call console.log.apply (WTF IE!) It also reports typeof(console.log) as 'object' (UNH!) // but together, those two errors can be useful in allowing us to fix stuff so it works right if( typeof(console.log) === 'object' ) { // Array.forEach doesn't work in IE 8 so don't try that :( console.log = Function.prototype.call.bind(console.log, console); console.info = Function.prototype.call.bind(console.info, console); console.warn = Function.prototype.call.bind(console.warn, console); console.error = Function.prototype.call.bind(console.error, console); console.debug = Function.prototype.call.bind(console.info, console); } /** * Support group and groupEnd functions */ ('group' in console) || (console.group = function(msg) { console.info("\n--- "+msg+" ---\n"); }); ('groupEnd' in console) || (console.groupEnd = function() { console.log("\n"); }); ('assert' in console) || (console.assert = function(test, message) { if (!test) { try { // attempt to preserve the stack throw new Error("assertion failed: " + message); } catch(error) { setTimeout(function(){ throw error; }, 0); } } }); /** * Support time and timeEnd functions */ ('time' in console) || (function() { var trackedTimes = {}; console.time = function(msg) { trackedTimes[msg] = new Date().getTime(); }; console.timeEnd = function(msg) { var end = new Date().getTime(), time = (msg in trackedTimes)? end - trackedTimes[msg] : 0; console.info(msg+': '+time+'ms') }; }()); })(global.console); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],11:[function(require,module,exports){ if (!Function.prototype.bind) { //credits: taken from bind_even_never in this discussion: https://prototype.lighthouseapp.com/projects/8886/tickets/215-optimize-bind-bindaseventlistener#ticket-215-9 Function.prototype.bind = function(context) { var fn = this, args = Array.prototype.slice.call(arguments, 1); return function(){ return fn.apply(context, Array.prototype.concat.apply(args, arguments)); }; }; } },{}],12:[function(require,module,exports){ /* json2.js 2014-02-04 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, regexp: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. if (typeof JSON !== 'object') { JSON = {}; } (function () { 'use strict'; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function () { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function () { return this.valueOf(); }; } var cx, escapable, gap, indent, meta, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }; JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }()); exports.JSON = JSON; },{}],13:[function(require,module,exports){ if (!Object.create) { Object.create = (function(){ function F(){} return function(o){ if (arguments.length != 1) { throw new Error('Object.create implementation only accepts one parameter.'); } F.prototype = o; return new F() } })() } // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys if (!Object.keys) { Object.keys = (function () { 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'), dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ], dontEnumsLength = dontEnums.length; return function (obj) { if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { throw new TypeError('Object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (i = 0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; }()); } },{}],14:[function(require,module,exports){ // Add ECMA262-5 string trim if not supported natively // if (!('trim' in String.prototype)) { String.prototype.trim= function() { return this.replace(/^\s+/, '').replace(/\s+$/, ''); }; } },{}],15:[function(require,module,exports){ (function (global){ /* Copyright (c) 2010, Linden Research, Inc. Copyright (c) 2014, Joshua Bell 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. $/LicenseInfo$ */ // Original can be found at: // https://bitbucket.org/lindenlab/llsd // Modifications by Joshua Bell [email protected] // https://github.com/inexorabletash/polyfill // ES3/ES5 implementation of the Krhonos Typed Array Specification // Ref: http://www.khronos.org/registry/typedarray/specs/latest/ // Date: 2011-02-01 // // Variations: // * Allows typed_array.get/set() as alias for subscripts (typed_array[]) // * Gradually migrating structure from Khronos spec to ES6 spec if (typeof global["Uint8Array"] === "undefined") { (function (global, win) { 'use strict'; var undefined = (void 0); // Paranoia // Beyond this value, index getters/setters (i.e. array[0], array[1]) are so slow to // create, and consume so much memory, that the browser appears frozen. var MAX_ARRAY_LENGTH = 1e5; // Approximations of internal ECMAScript conversion functions function Type(v) { switch (typeof v) { case 'undefined': return 'undefined'; case 'boolean': return 'boolean'; case 'number': return 'number'; case 'string': return 'string'; default: return v === null ? 'null' : 'object'; } } // Class returns internal [[Class]] property, used to avoid cross-frame instanceof issues: function Class(v) { return Object.prototype.toString.call(v).replace(/^\[object *|\]$/g, ''); } function IsCallable(o) { return typeof o === 'function'; } function ToObject(v) { if (v === null || v === undefined) throw TypeError(); return Object(v); } function ToInt32(v) { return v >> 0; } function ToUint32(v) { return v >>> 0; } // Snapshot intrinsics var LN2 = Math.LN2, abs = Math.abs, floor = Math.floor, log = Math.log, max = Math.max, min = Math.min, pow = Math.pow, round = Math.round; // emulate ES5 getter/setter API using legacy APIs // http://blogs.msdn.com/b/ie/archive/2010/09/07/transitioning-existing-code-to-the-es5-getter-setter-apis.aspx // (second clause tests for Object.defineProperty() in IE<9 that only supports extending DOM prototypes, but // note that IE<9 does not support __defineGetter__ or __defineSetter__ so it just renders the method harmless) (function () { var orig = Object.defineProperty; var dom_only = !(function () { try { return Object.defineProperty({}, 'x', {}); } catch (_) { return false; } }()); if (!orig || dom_only) { Object.defineProperty = function (o, prop, desc) { // In IE8 try built-in implementation for defining properties on DOM prototypes. if (orig) { try { return orig(o, prop, desc); } catch (_) { } } if (o !== Object(o)) throw TypeError('Object.defineProperty called on non-object'); if (Object.prototype.__defineGetter__ && ('get' in desc)) Object.prototype.__defineGetter__.call(o, prop, desc.get); if (Object.prototype.__defineSetter__ && ('set' in desc)) Object.prototype.__defineSetter__.call(o, prop, desc.set); if ('value' in desc) o[prop] = desc.value; return o; }; } }()); // ES5: Make obj[index] an alias for obj._getter(index)/obj._setter(index, value) // for index in 0 ... obj.length function makeArrayAccessors(obj) { if (obj.length > MAX_ARRAY_LENGTH) throw RangeError('Array too large for polyfill'); function makeArrayAccessor(index) { Object.defineProperty(obj, index, { 'get': function () { return obj._getter(index); }, 'set': function (v) { obj._setter(index, v); }, enumerable: true, configurable: false }); } var i; for (i = 0; i < obj.length; i += 1) { makeArrayAccessor(i); } } // Internal conversion functions: // pack<Type>() - take a number (interpreted as Type), output a byte array // unpack<Type>() - take a byte array, output a Type-like number function as_signed(value, bits) { var s = 32 - bits; return (value << s) >> s; } function as_unsigned(value, bits) { var s = 32 - bits; return (value << s) >>> s; } function packI8(n) { return [n & 0xff]; } function unpackI8(bytes) { return as_signed(bytes[0], 8); } function packU8(n) { return [n & 0xff]; } function unpackU8(bytes) { return as_unsigned(bytes[0], 8); } function packU8Clamped(n) { n = round(Number(n)); return [n < 0 ? 0 : n > 0xff ? 0xff : n & 0xff]; } function packI16(n) { return [(n >> 8) & 0xff, n & 0xff]; } function unpackI16(bytes) { return as_signed(bytes[0] << 8 | bytes[1], 16); } function packU16(n) { return [(n >> 8) & 0xff, n & 0xff]; } function unpackU16(bytes) { return as_unsigned(bytes[0] << 8 | bytes[1], 16); } function packI32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; } function unpackI32(bytes) { return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); } function packU32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; } function unpackU32(bytes) { return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); } function packIEEE754(v, ebits, fbits) { var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str, bytes; function roundToEven(n) { var w = floor(n), f = n - w; if (f < 0.5) return w; if (f > 0.5) return w + 1; return w % 2 ? w + 1 : w; } // Compute sign, exponent, fraction if (v !== v) { // NaN // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping e = (1 << ebits) - 1; f = pow(2, fbits - 1); s = 0; } else if (v === Infinity || v === -Infinity) { e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0; } else if (v === 0) { e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0; } else { s = v < 0; v = abs(v); if (v >= pow(2, 1 - bias)) { e = min(floor(log(v) / LN2), 1023); f = roundToEven(v / pow(2, e) * pow(2, fbits)); if (f / pow(2, fbits) >= 2) { e = e + 1; f = 1; } if (e > bias) { // Overflow e = (1 << ebits) - 1; f = 0; } else { // Normalized e = e + bias; f = f - pow(2, fbits); } } else { // Denormalized e = 0; f = roundToEven(v / pow(2, 1 - bias - fbits)); } } // Pack sign, exponent, fraction bits = []; for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = floor(f / 2); } for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = floor(e / 2); } bits.push(s ? 1 : 0); bits.reverse(); str = bits.join(''); // Bits to bytes bytes = []; while (str.length) { bytes.push(parseInt(str.substring(0, 8), 2)); str = str.substring(8); } return bytes; } function unpackIEEE754(bytes, ebits, fbits) { // Bytes to bits var bits = [], i, j, b, str, bias, s, e, f; for (i = bytes.length; i; i -= 1) { b = bytes[i - 1]; for (j = 8; j; j -= 1) { bits.push(b % 2 ? 1 : 0); b = b >> 1; } } bits.reverse(); str = bits.join(''); // Unpack sign, exponent, fraction bias = (1 << (ebits - 1)) - 1; s = parseInt(str.substring(0, 1), 2) ? -1 : 1; e = parseInt(str.substring(1, 1 + ebits), 2); f = parseInt(str.substring(1 + ebits), 2); // Produce number if (e === (1 << ebits) - 1) { return f !== 0 ? NaN : s * Infinity; } else if (e > 0) { // Normalized return s * pow(2, e - bias) * (1 + f / pow(2, fbits)); } else if (f !== 0) { // Denormalized return s * pow(2, -(bias - 1)) * (f / pow(2, fbits)); } else { return s < 0 ? -0 : 0; } } function unpackF64(b) { return unpackIEEE754(b, 11, 52); } function packF64(v) { return packIEEE754(v, 11, 52); } function unpackF32(b) { return unpackIEEE754(b, 8, 23); } function packF32(v) { return packIEEE754(v, 8, 23); } // // 3 The ArrayBuffer Type // (function () { function ArrayBuffer(length) { length = ToInt32(length); if (length < 0) throw RangeError('ArrayBuffer size is not a small enough positive integer.'); Object.defineProperty(this, 'byteLength', {value: length}); Object.defineProperty(this, '_bytes', {value: Array(length)}); for (var i = 0; i < length; i += 1) this._bytes[i] = 0; } global.ArrayBuffer = global.ArrayBuffer || ArrayBuffer; // // 5 The Typed Array View Types // function $TypedArray$() { // %TypedArray% ( length ) if (!arguments.length || typeof arguments[0] !== 'object') { return (function (length) { length = ToInt32(length); if (length < 0) throw RangeError('length is not a small enough positive integer.'); Object.defineProperty(this, 'length', {value: length}); Object.defineProperty(this, 'byteLength', {value: length * this.BYTES_PER_ELEMENT}); Object.defineProperty(this, 'buffer', {value: new ArrayBuffer(this.byteLength)}); Object.defineProperty(this, 'byteOffset', {value: 0}); }).apply(this, arguments); } // %TypedArray% ( typedArray ) if (arguments.length >= 1 && Type(arguments[0]) === 'object' && arguments[0] instanceof $TypedArray$) { return (function (typedArray) { if (this.constructor !== typedArray.constructor) throw TypeError(); var byteLength = typedArray.length * this.BYTES_PER_ELEMENT; Object.defineProperty(this, 'buffer', {value: new ArrayBuffer(byteLength)}); Object.defineProperty(this, 'byteLength', {value: byteLength}); Object.defineProperty(this, 'byteOffset', {value: 0}); Object.defineProperty(this, 'length', {value: typedArray.length}); for (var i = 0; i < this.length; i += 1) this._setter(i, typedArray._getter(i)); }).apply(this, arguments); } // %TypedArray% ( array ) if (arguments.length >= 1 && Type(arguments[0]) === 'object' && !(arguments[0] instanceof $TypedArray$) && !(arguments[0] instanceof ArrayBuffer || Class(arguments[0]) === 'ArrayBuffer')) { return (function (array) { var byteLength = array.length * this.BYTES_PER_ELEMENT; Object.defineProperty(this, 'buffer', {value: new ArrayBuffer(byteLength)}); Object.defineProperty(this, 'byteLength', {value: byteLength}); Object.defineProperty(this, 'byteOffset', {value: 0}); Object.defineProperty(this, 'length', {value: array.length}); for (var i = 0; i < this.length; i += 1) { var s = array[i]; this._setter(i, Number(s)); } }).apply(this, arguments); } // %TypedArray% ( buffer, byteOffset=0, length=undefined ) if (arguments.length >= 1 && Type(arguments[0]) === 'object' && (arguments[0] instanceof ArrayBuffer || Class(arguments[0]) === 'ArrayBuffer')) { return (function (buffer, byteOffset, length) { byteOffset = ToUint32(byteOffset); if (byteOffset > buffer.byteLength) throw RangeError('byteOffset out of range'); // The given byteOffset must be a multiple of the element // size of the specific type, otherwise an exception is raised. if (byteOffset % this.BYTES_PER_ELEMENT) throw RangeError('buffer length minus the byteOffset is not a multiple of the element size.'); if (length === undefined) { var byteLength = buffer.byteLength - byteOffset; if (byteLength % this.BYTES_PER_ELEMENT) throw RangeError('length of buffer minus byteOffset not a multiple of the element size'); length = byteLength / this.BYTES_PER_ELEMENT; } else { length = ToUint32(length); byteLength = length * this.BYTES_PER_ELEMENT; } if ((byteOffset + byteLength) > buffer.byteLength) throw RangeError('byteOffset and length reference an area beyond the end of the buffer'); Object.defineProperty(this, 'buffer', {value: buffer}); Object.defineProperty(this, 'byteLength', {value: byteLength}); Object.defineProperty(this, 'byteOffset', {value: byteOffset}); Object.defineProperty(this, 'length', {value: length}); }).apply(this, arguments); } // %TypedArray% ( all other argument combinations ) throw TypeError(); } // Properties of the %TypedArray Instrinsic Object // %TypedArray%.from ( source , mapfn=undefined, thisArg=undefined ) Object.defineProperty($TypedArray$, 'from', {value: function (iterable) { return new this(iterable); }}); // %TypedArray%.of ( ...items ) Object.defineProperty($TypedArray$, 'of', {value: function (/*...items*/) { return new this(arguments); }}); // %TypedArray%.prototype var $TypedArrayPrototype$ = {}; $TypedArray$.prototype = $TypedArrayPrototype$; // WebIDL: getter type (unsigned long index); Object.defineProperty($TypedArray$.prototype, '_getter', {value: function (index) { if (arguments.length < 1) throw SyntaxError('Not enough arguments'); index = ToUint32(index); if (index >= this.length) return undefined; var bytes = [], i, o; for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; i < this.BYTES_PER_ELEMENT; i += 1, o += 1) { bytes.push(this.buffer._bytes[o]); } return this._unpack(bytes); }}); // NONSTANDARD: convenience alias for getter: type get(unsigned long index); Object.defineProperty($TypedArray$.prototype, 'get', {value: $TypedArray$.prototype._getter}); // WebIDL: setter void (unsigned long index, type value); Object.defineProperty($TypedArray$.prototype, '_setter', {value: function (index, value) { if (arguments.length < 2) throw SyntaxError('Not enough arguments'); index = ToUint32(index); if (index >= this.length) return; var bytes = this._pack(value), i, o; for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; i < this.BYTES_PER_ELEMENT; i += 1, o += 1) { this.buffer._bytes[o] = bytes[i]; } }}); // get %TypedArray%.prototype.buffer // get %TypedArray%.prototype.byteLength // get %TypedArray%.prototype.byteOffset // -- applied directly to the object in the constructor // %TypedArray%.prototype.constructor Object.defineProperty($TypedArray$.prototype, 'constructor', {value: $TypedArray$}); // %TypedArray%.prototype.copyWithin (target, start, end = this.length ) Object.defineProperty($TypedArray$.prototype, 'copyWithin', {value: function (m_target, m_start) { var m_end = arguments[2]; var m_o = ToObject(this); var lenVal = m_o.length; var m_len = ToUint32(lenVal); m_len = max(m_len, 0); var relativeTarget = ToInt32(m_target); var m_to; if (relativeTarget < 0) { m_to = max(m_len + relativeTarget, 0); } else { m_to = min(relativeTarget, m_len); } var relativeStart = ToInt32(m_start); var m_from; if (relativeStart < 0) { m_from = max(m_len + relativeStart, 0); } else { m_from = min(relativeStart, m_len); } var relativeEnd; if (m_end === undefined) { relativeEnd = m_len; } else { relativeEnd = ToInt32(m_end); } var m_final; if (relativeEnd < 0) { m_final = max(m_len + relativeEnd, 0); } else { m_final = min(relativeEnd, m_len); } var m_count = min(m_final - m_from, m_len - m_to); var direction; if (from < m_to && m_to < m_from + m_count) { direction = -1; m_from = m_from + m_count - 1; m_to = m_to + m_count - 1; } else { direction = 1; } while (count > 0) { m_o._setter(m_to, m_o._getter(m_from)); m_from = m_from + direction; m_to = m_to + direction; m_count = m_count - 1; } return m_o; }}); // %TypedArray%.prototype.entries ( ) // -- defined in es6.js to shim browsers w/ native TypedArrays // %TypedArray%.prototype.every ( callbackfn, thisArg = undefined ) Object.defineProperty($TypedArray$.prototype, 'every', {value: function (callbackfn) { if (this === undefined || this === null) throw TypeError(); var t = Object(this); var len = ToUint32(t.length); if (!IsCallable(callbackfn)) throw TypeError(); var thisArg = arguments[1]; for (var i = 0; i < len; i++) { if (!callbackfn.call(thisArg, t._getter(i), i, t)) return false; } return true; }}); // %TypedArray%.prototype.fill (value, start = 0, end = this.length ) Object.defineProperty($TypedArray$.prototype, 'fill', {value: function (value) { var m_start = arguments[1], m_end = arguments[2]; var m_o = ToObject(this); var lenVal = m_o.length; var m_len = ToUint32(lenVal); m_len = max(m_len, 0); var relativeStart = ToInt32(m_start); var m_k; if (relativeStart < 0) { m_k = max((m_len + relativeStart), 0); } else { m_k = min(relativeStart, m_len); } var relativeEnd; if (m_end === undefined) { relativeEnd = m_len; } else { relativeEnd = ToInt32(m_end); } var m_final; if (relativeEnd < 0) { m_final = max((m_len + relativeEnd), 0); } else { m_final = min(relativeEnd, m_len); } while (m_k < m_final) { m_o._setter(m_k, value); m_k += 1; } return m_o; }}); // %TypedArray%.prototype.filter ( callbackfn, thisArg = undefined ) Object.defineProperty($TypedArray$.prototype, 'filter', {value: function (callbackfn) { if (this === undefined || this === null) throw TypeError(); var t = Object(this); var len = ToUint32(t.length); if (!IsCallable(callbackfn)) throw TypeError(); var res = []; var thisp = arguments[1]; for (var i = 0; i < len; i++) { var val = t._getter(i); // in case fun mutates this if (callbackfn.call(thisp, val, i, t)) res.push(val); } return new this.constructor(res); }}); // %TypedArray%.prototype.find (predicate, thisArg = undefined) Object.defineProperty($TypedArray$.prototype, 'find', {value: function (predicate) { var o = ToObject(this); var lenValue = o.length; var len = ToUint32(lenValue); if (!IsCallable(predicate)) throw TypeError(); var t = arguments.length > 1 ? arguments[1] : undefined; var k = 0; while (k < len) { var kValue = o._getter(k); var testResult = predicate.call(t, kValue, k, o); if (Boolean(testResult)) return kValue; ++k; } return undefined; }}); // %TypedArray%.prototype.findIndex ( predicate, thisArg = undefined ) Object.defineProperty($TypedArray$.prototype, 'findIndex', {value: function (predicate) { var o = ToObject(this); var lenValue = o.length; var len = ToUint32(lenValue); if (!IsCallable(predicate)) throw TypeError(); var t = arguments.length > 1 ? arguments[1] : undefined; var k = 0; while (k < len) { var kValue = o._getter(k); var testResult = predicate.call(t, kValue, k, o); if (Boolean(testResult)) return k; ++k; } return -1; }}); // %TypedArray%.prototype.forEach ( callbackfn, thisArg = undefined ) Object.defineProperty($TypedArray$.prototype, 'forEach', {value: function (callbackfn) { if (this === undefined || this === null) throw TypeError(); var t = Object(this); var len = ToUint32(t.length); if (!IsCallable(callbackfn)) throw TypeError(); var thisp = arguments[1]; for (var i = 0; i < len; i++) callbackfn.call(thisp, t._getter(i), i, t); }}); // %TypedArray%.prototype.indexOf (searchElement, fromIndex = 0 ) Object.defineProperty($TypedArray$.prototype, 'indexOf', {value: function (searchElement) { if (this === undefined || this === null) throw TypeError(); var t = Object(this); var len = ToUint32(t.length); if (len === 0) return -1; var no = 0; var na; if (arguments.length > 0) { na = Number(arguments[1]); if (na !== no) { no = 0; } else if (na !== 0 && na !== (1 / 0) && na !== -(1 / 0)) { no = (na > 0 || -1) * floor(abs(na)); } } if (no >= len) return -1; var k = no >= 0 ? no : max(len - abs(no), 0); for (; k < len; k++) { if (t._getter(k) === searchElement) { return k; } } return -1; }}); // %TypedArray%.prototype.join ( separator ) Object.defineProperty($TypedArray$.prototype, 'join', {value: function (separator) { if (this === undefined || this === null) throw TypeError(); var t = Object(this); var len = ToUint32(t.length); var tmp = Array(len); for (var i = 0; i < len; ++i) tmp[i] = t._getter(i); return tmp.join(separator === undefined ? ',' : separator); // Hack for IE7 }}); // %TypedArray%.prototype.keys ( ) // -- defined in es6.js to shim browsers w/ native TypedArrays // %TypedArray%.prototype.lastIndexOf ( searchElement, fromIndex = this.length-1 ) Object.defineProperty($TypedArray$.prototype, 'lastIndexOf', {value: function (searchElement) { if (this === undefined || this === null) throw TypeError(); var t = Object(this); var len = ToUint32(t.length); if (len === 0) return -1; var n = len; if (arguments.length > 1) { n = Number(arguments[1]); if (n !== n) { n = 0; } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) { n = (n > 0 || -1) * floor(abs(n)); } } var k = n >= 0 ? min(n, len - 1) : len - abs(n); for (; k >= 0; k--) { if (t._getter(k) === searchElement) return k; } return -1; }}); // get %TypedArray%.prototype.length // -- applied directly to the object in the constructor // %TypedArray%.prototype.map ( callbackfn, thisArg = undefined ) Object.defineProperty($TypedArray$.prototype, 'map', {value: function (callbackfn) { if (this === undefined || this === null) throw TypeError(); var t = Object(this); var len = ToUint32(t.length); if (!IsCallable(callbackfn)) throw TypeError(); var res = []; res.length = len; var thisp = arguments[1]; for (var i = 0; i < len; i++) res[i] = callbackfn.call(thisp, t._getter(i), i, t); return new this.constructor(res); }}); // %TypedArray%.prototype.reduce ( callbackfn [, initialValue] ) Object.defineProperty($TypedArray$.prototype, 'reduce', {value: function (callbackfn) { if (this === undefined || this === null) throw TypeError(); var t = Object(this); var len = ToUint32(t.length); if (!IsCallable(callbackfn)) throw TypeError(); // no value to return if no initial value and an empty array if (len === 0 && arguments.length === 1) throw TypeError(); var k = 0; var accumulator; if (arguments.length >= 2) { accumulator = arguments[1]; } else { accumulator = t._getter(k++); } while (k < len) { accumulator = callbackfn.call(undefined, accumulator, t._getter(k), k, t); k++; } return accumulator; }}); // %TypedArray%.prototype.reduceRight ( callbackfn [, initialValue] ) Object.defineProperty($TypedArray$.prototype, 'reduceRight', {value: function (callbackfn) { if (this === undefined || this === null) throw TypeError(); var t = Object(this); var len = ToUint32(t.length); if (!IsCallable(callbackfn)) throw TypeError(); // no value to return if no initial value, empty array if (len === 0 && arguments.length === 1) throw TypeError(); var k = len - 1; var accumulator; if (arguments.length >= 2) { accumulator = arguments[1]; } else { accumulator = t._getter(k--); } while (k >= 0) { accumulator = callbackfn.call(undefined, accumulator, t._getter(k), k, t); k--; } return accumulator; }}); // %TypedArray%.prototype.reverse ( ) Object.defineProperty($TypedArray$.prototype, 'reverse', {value: function () { if (this === undefined || this === null) throw TypeError(); var t = Object(this); var len = ToUint32(t.length); var half = floor(len / 2); for (var i = 0, j = len - 1; i < half; ++i, --j) { var tmp = t._getter(i); t._setter(i, t._getter(j)); t._setter(j, tmp); } return t; }}); // %TypedArray%.prototype.set(array, offset = 0 ) // %TypedArray%.prototype.set(typedArray, offset = 0 ) // WebIDL: void set(TypedArray array, optional unsigned long offset); // WebIDL: void set(sequence<type> array, optional unsigned long offset); Object.defineProperty($TypedArray$.prototype, 'set', {value: function (index, value) { if (arguments.length < 1) throw SyntaxError('Not enough arguments'); var array, sequence, offset, len, i, s, d, byteOffset, byteLength, tmp; if (typeof arguments[0] === 'object' && arguments[0].constructor === this.constructor) { // void set(TypedArray array, optional unsigned long offset); array = arguments[0]; offset = ToUint32(arguments[1]); if (offset + array.length > this.length) { throw RangeError('Offset plus length of array is out of range'); } byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT; byteLength = array.length * this.BYTES_PER_ELEMENT; if (array.buffer === this.buffer) { tmp = []; for (i = 0, s = array.byteOffset; i < byteLength; i += 1, s += 1) { tmp[i] = array.buffer._bytes[s]; } for (i = 0, d = byteOffset; i < byteLength; i += 1, d += 1) { this.buffer._bytes[d] = tmp[i]; } } else { for (i = 0, s = array.byteOffset, d = byteOffset; i < byteLength; i += 1, s += 1, d += 1) { this.buffer._bytes[d] = array.buffer._bytes[s]; } } } else if (typeof arguments[0] === 'object' && typeof arguments[0].length !== 'undefined') { // void set(sequence<type> array, optional unsigned long offset); sequence = arguments[0]; len = ToUint32(sequence.length); offset = ToUint32(arguments[1]); if (offset + len > this.length) { throw RangeError('Offset plus length of array is out of range'); } for (i = 0; i < len; i += 1) { s = sequence[i]; this._setter(offset + i, Number(s)); } } else { throw TypeError('Unexpected argument type(s)'); } }}); // %TypedArray%.prototype.slice ( start, end ) Object.defineProperty($TypedArray$.prototype, 'slice', {value: function (m_start, m_end) { var m_o = ToObject(this); var lenVal = m_o.length; var m_len = ToUint32(lenVal); var relativeStart = ToInt32(m_start); var m_k = (relativeStart < 0) ? max(m_len + relativeStart, 0) : min(relativeStart, m_len); var relativeEnd = (m_end === undefined) ? m_len : ToInt32(m_end); var m_final = (relativeEnd < 0) ? max(m_len + relativeEnd, 0) : min(relativeEnd, m_len); var m_count = m_final - m_k; var m_c = m_o.constructor; var m_a = new m_c(m_count); var m_n = 0; while (m_k < m_final) { var kValue = m_o._getter(m_k); m_a._setter(m_n, kValue); ++m_k; ++m_n; } return m_a; }}); // %TypedArray%.prototype.some ( callbackfn, thisArg = undefined ) Object.defineProperty($TypedArray$.prototype, 'some', {value: function (callbackfn) { if (this === undefined || this === null) throw TypeError(); var t = Object(this); var len = ToUint32(t.length); if (!IsCallable(callbackfn)) throw TypeError(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (callbackfn.call(thisp, t._getter(i), i, t)) { return true; } } return false; }}); // %TypedArray%.prototype.sort ( comparefn ) Object.defineProperty($TypedArray$.prototype, 'sort', {value: function (comparefn) { if (this === undefined || this === null) throw TypeError(); var t = Object(this); var len = ToUint32(t.length); var tmp = Array(len); for (var i = 0; i < len; ++i) tmp[i] = t._getter(i); if (comparefn) tmp.sort(comparefn); else tmp.sort(); // Hack for IE8/9 for (i = 0; i < len; ++i) t._setter(i, tmp[i]); return t; }}); // %TypedArray%.prototype.subarray(begin = 0, end = this.length ) // WebIDL: TypedArray subarray(long begin, optional long end); Object.defineProperty($TypedArray$.prototype, 'subarray', {value: function (start, end) { function clamp(v, min, max) { return v < min ? min : v > max ? max : v; } start = ToInt32(start); end = ToInt32(end); if (arguments.length < 1) { start = 0; } if (arguments.length < 2) { end = this.length; } if (start < 0) { start = this.length + start; } if (end < 0) { end = this.length + end; } start = clamp(start, 0, this.length); end = clamp(end, 0, this.length); var len = end - start; if (len < 0) { len = 0; } return new this.constructor( this.buffer, this.byteOffset + start * this.BYTES_PER_ELEMENT, len); }}); // %TypedArray%.prototype.toLocaleString ( ) // %TypedArray%.prototype.toString ( ) // %TypedArray%.prototype.values ( ) // %TypedArray%.prototype [ @@iterator ] ( ) // get %TypedArray%.prototype [ @@toStringTag ] // -- defined in es6.js to shim browsers w/ native TypedArrays function makeTypedArray(elementSize, pack, unpack) { // Each TypedArray type requires a distinct constructor instance with // identical logic, which this produces. var TypedArray = function () { Object.defineProperty(this, 'constructor', {value: TypedArray}); $TypedArray$.apply(this, arguments); makeArrayAccessors(this); }; if ('__proto__' in TypedArray) { TypedArray.__proto__ = $TypedArray$; } else { TypedArray.from = $TypedArray$.from; TypedArray.of = $TypedArray$.of; } TypedArray.BYTES_PER_ELEMENT = elementSize; var TypedArrayPrototype = function () { }; TypedArrayPrototype.prototype = $TypedArrayPrototype$; TypedArray.prototype = new TypedArrayPrototype(); Object.defineProperty(TypedArray.prototype, 'BYTES_PER_ELEMENT', {value: elementSize}); Object.defineProperty(TypedArray.prototype, '_pack', {value: pack}); Object.defineProperty(TypedArray.prototype, '_unpack', {value: unpack}); return TypedArray; } var Int8Array = makeTypedArray(1, packI8, unpackI8); var Uint8Array = makeTypedArray(1, packU8, unpackU8); var Uint8ClampedArray = makeTypedArray(1, packU8Clamped, unpackU8); var Int16Array = makeTypedArray(2, packI16, unpackI16); var Uint16Array = makeTypedArray(2, packU16, unpackU16); var Int32Array = makeTypedArray(4, packI32, unpackI32); var Uint32Array = makeTypedArray(4, packU32, unpackU32); var Float32Array = makeTypedArray(4, packF32, unpackF32); var Float64Array = makeTypedArray(8, packF64, unpackF64); global.Int8Array = win.Int8Array = global.Int8Array || Int8Array; global.Uint8Array = win.Uint8Array = global.Uint8Array || Uint8Array; global.Uint8ClampedArray = win.Uint8ClampedArray = global.Uint8ClampedArray || Uint8ClampedArray; global.Int16Array = win.Int16Array = global.Int16Array || Int16Array; global.Uint16Array = win.Uint16Array = global.Uint16Array || Uint16Array; global.Int32Array = win.Int32Array = global.Int32Array || Int32Array; global.Uint32Array = win.Uint32Array = global.Uint32Array || Uint32Array; global.Float32Array = win.Float32Array = global.Float32Array || Float32Array; global.Float64Array = win.Float64Array = global.Float64Array || Float64Array; }()); // // 6 The DataView View Type // (function () { function r(array, index) { return IsCallable(array.get) ? array.get(index) : array[index]; } var IS_BIG_ENDIAN = (function () { var u16array = new global.Uint16Array([0x1234]), u8array = new global.Uint8Array(u16array.buffer); return r(u8array, 0) === 0x12; }()); // DataView(buffer, byteOffset=0, byteLength=undefined) // WebIDL: Constructor(ArrayBuffer buffer, // optional unsigned long byteOffset, // optional unsigned long byteLength) function DataView(buffer, byteOffset, byteLength) { if (!(buffer instanceof ArrayBuffer || Class(buffer) === 'ArrayBuffer')) throw TypeError(); byteOffset = ToUint32(byteOffset); if (byteOffset > buffer.byteLength) throw RangeError('byteOffset out of range'); if (byteLength === undefined) byteLength = buffer.byteLength - byteOffset; else byteLength = ToUint32(byteLength); if ((byteOffset + byteLength) > buffer.byteLength) throw RangeError('byteOffset and length reference an area beyond the end of the buffer'); Object.defineProperty(this, 'buffer', {value: buffer}); Object.defineProperty(this, 'byteLength', {value: byteLength}); Object.defineProperty(this, 'byteOffset', {value: byteOffset}); }; // get DataView.prototype.buffer // get DataView.prototype.byteLength // get DataView.prototype.byteOffset // -- applied directly to instances by the constructor function makeGetter(arrayType) { return function GetViewValue(byteOffset, littleEndian) { byteOffset = ToUint32(byteOffset); if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) throw RangeError('Array index out of range'); byteOffset += this.byteOffset; var uint8Array = new global.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT), bytes = []; for (var i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) bytes.push(r(uint8Array, i)); if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) bytes.reverse(); return r(new arrayType(new global.Uint8Array(bytes).buffer), 0); }; } Object.defineProperty(DataView.prototype, 'getUint8', {value: makeGetter(global.Uint8Array)}); Object.defineProperty(DataView.prototype, 'getInt8', {value: makeGetter(global.Int8Array)}); Object.defineProperty(DataView.prototype, 'getUint16', {value: makeGetter(global.Uint16Array)}); Object.defineProperty(DataView.prototype, 'getInt16', {value: makeGetter(global.Int16Array)}); Object.defineProperty(DataView.prototype, 'getUint32', {value: makeGetter(global.Uint32Array)}); Object.defineProperty(DataView.prototype, 'getInt32', {value: makeGetter(global.Int32Array)}); Object.defineProperty(DataView.prototype, 'getFloat32', {value: makeGetter(global.Float32Array)}); Object.defineProperty(DataView.prototype, 'getFloat64', {value: makeGetter(global.Float64Array)}); function makeSetter(arrayType) { return function SetViewValue(byteOffset, value, littleEndian) { byteOffset = ToUint32(byteOffset); if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) throw RangeError('Array index out of range'); // Get bytes var typeArray = new arrayType([value]), byteArray = new global.Uint8Array(typeArray.buffer), bytes = [], i, byteView; for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) bytes.push(r(byteArray, i)); // Flip if necessary if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) bytes.reverse(); // Write them byteView = new Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT); byteView.set(bytes); }; } Object.defineProperty(DataView.prototype, 'setUint8', {value: makeSetter(global.Uint8Array)}); Object.defineProperty(DataView.prototype, 'setInt8', {value: makeSetter(global.Int8Array)}); Object.defineProperty(DataView.prototype, 'setUint16', {value: makeSetter(global.Uint16Array)}); Object.defineProperty(DataView.prototype, 'setInt16', {value: makeSetter(global.Int16Array)}); Object.defineProperty(DataView.prototype, 'setUint32', {value: makeSetter(global.Uint32Array)}); Object.defineProperty(DataView.prototype, 'setInt32', {value: makeSetter(global.Int32Array)}); Object.defineProperty(DataView.prototype, 'setFloat32', {value: makeSetter(global.Float32Array)}); Object.defineProperty(DataView.prototype, 'setFloat64', {value: makeSetter(global.Float64Array)}); global.DataView = global.DataView || DataView; }()); }(exports, window) ); } // workaround for crypto-js on IE11 // http://code.google.com/p/crypto-js/issues/detail?id=81 if ('window' in global) { if (!('Uint8ClampedArray' in window)) { window.Uint8ClampedArray = global.Uint8Array; } } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],16:[function(require,module,exports){ (function (global){ /////////////////////////////////////////////////////////////////////////////// // // AutobahnJS - http://autobahn.ws, http://wamp.ws // // A JavaScript library for WAMP ("The Web Application Messaging Protocol"). // // Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com // // Licensed under the MIT License. // http://www.opensource.org/licenses/mit-license.php // /////////////////////////////////////////////////////////////////////////////// // require('assert') would be nice .. but it does not // work with Google Closure after Browserify var when = require('when'); var when_fn = require("when/function"); var log = require('./log.js'); var util = require('./util.js'); // IE fallback (http://afuchs.tumblr.com/post/23550124774/date-now-in-ie8) Date.now = Date.now || function() { return +new Date; }; // WAMP "Advanced Profile" support in AutobahnJS per role // WAMP_FEATURES = { caller: { features: { caller_identification: true, progressive_call_results: true } }, callee: { features: { caller_identification: true, pattern_based_registration: true, shared_registration: true, progressive_call_results: true, registration_revocation: true } }, publisher: { features: { publisher_identification: true, subscriber_blackwhite_listing: true, publisher_exclusion: true } }, subscriber: { features: { publisher_identification: true, pattern_based_subscription: true, subscription_revocation: true } } }; // generate a WAMP ID // function newid () { return Math.floor(Math.random() * 9007199254740992); } var Invocation = function (caller, progress, procedure) { var self = this; self.caller = caller; self.progress = progress; self.procedure = procedure; }; var Event = function (publication, publisher, topic) { var self = this; self.publication = publication; self.publisher = publisher; self.topic = topic; }; var Result = function (args, kwargs) { var self = this; self.args = args || []; self.kwargs = kwargs || {}; }; var Error = function (error, args, kwargs) { var self = this; self.error = error; self.args = args || []; self.kwargs = kwargs || {}; }; var Subscription = function (topic, handler, options, session, id) { var self = this; self.topic = topic; self.handler = handler; self.options = options || {}; self.session = session; self.id = id; self.active = true; // this will fire when the handler is unsubscribed self._on_unsubscribe = session._defer(); if (self._on_unsubscribe.promise.then) { // whenjs has the actual user promise in an attribute self.on_unsubscribe = self._on_unsubscribe.promise; } else { self.on_unsubscribe = self._on_unsubscribe; } }; Subscription.prototype.unsubscribe = function () { var self = this; return self.session.unsubscribe(self); }; var Registration = function (procedure, endpoint, options, session, id) { var self = this; self.procedure = procedure; self.endpoint = endpoint; self.options = options || {}; self.session = session; self.id = id; self.active = true; // this will fire when the endpoint is unregistered self._on_unregister = session._defer(); if (self._on_unregister.promise.then) { // whenjs has the actual user promise in an attribute self.on_unregister = self._on_unregister.promise; } else { self.on_unregister = self._on_unregister; } }; Registration.prototype.unregister = function () { var self = this; return self.session.unregister(self); }; var Publication = function (id) { var self = this; self.id = id; }; var MSG_TYPE = { HELLO: 1, WELCOME: 2, ABORT: 3, CHALLENGE: 4, AUTHENTICATE: 5, GOODBYE: 6, HEARTBEAT: 7, ERROR: 8, PUBLISH: 16, PUBLISHED: 17, SUBSCRIBE: 32, SUBSCRIBED: 33, UNSUBSCRIBE: 34, UNSUBSCRIBED: 35, EVENT: 36, CALL: 48, CANCEL: 49, RESULT: 50, REGISTER: 64, REGISTERED: 65, UNREGISTER: 66, UNREGISTERED: 67, INVOCATION: 68, INTERRUPT: 69, YIELD: 70 }; var Session = function (socket, defer, onchallenge) { var self = this; // the transport connection (WebSocket object) self._socket = socket; // the Deferred factory to use self._defer = defer; // the WAMP authentication challenge handler self._onchallenge = onchallenge; // the WAMP session ID self._id = null; // the WAMP realm joined self._realm = null; // the WAMP features in use self._features = null; // closing state self._goodbye_sent = false; self._transport_is_closing = false; // outstanding requests; self._publish_reqs = {}; self._subscribe_reqs = {}; self._unsubscribe_reqs = {}; self._call_reqs = {}; self._register_reqs = {}; self._unregister_reqs = {}; // subscriptions in place; self._subscriptions = {}; // registrations in place; self._registrations = {}; // incoming invocations; self._invocations = {}; // prefix shortcuts for URIs self._prefixes = {}; // the defaults for 'disclose_me' self._caller_disclose_me = false; self._publisher_disclose_me = false; self._send_wamp = function (msg) { // forward WAMP message to be sent to WAMP transport self._socket.send(msg); }; self._protocol_violation = function (reason) { log.debug("failing transport due to protocol violation: " + reason); self._socket.close(1002, "protocol violation: " + reason); }; self._MESSAGE_MAP = {}; self._MESSAGE_MAP[MSG_TYPE.ERROR] = {}; self._process_SUBSCRIBED = function (msg) { // // process SUBSCRIBED reply to SUBSCRIBE // var request = msg[1]; var subscription = msg[2]; if (request in self._subscribe_reqs) { var r = self._subscribe_reqs[request]; var d = r[0]; var topic = r[1]; var handler = r[2]; var options = r[3]; if (!(subscription in self._subscriptions)) { self._subscriptions[subscription] = []; } var sub = new Subscription(topic, handler, options, self, subscription); self._subscriptions[subscription].push(sub); d.resolve(sub); delete self._subscribe_reqs[request]; } else { self._protocol_violation("SUBSCRIBED received for non-pending request ID " + request); } }; self._MESSAGE_MAP[MSG_TYPE.SUBSCRIBED] = self._process_SUBSCRIBED; self._process_SUBSCRIBE_ERROR = function (msg) { // // process ERROR reply to SUBSCRIBE // var request = msg[2]; if (request in self._subscribe_reqs) { var details = msg[3]; var error = new Error(msg[4], msg[5], msg[6]); var r = self._subscribe_reqs[request]; var d = r[0]; d.reject(error); delete self._subscribe_reqs[request]; } else { self._protocol_violation("SUBSCRIBE-ERROR received for non-pending request ID " + request); } }; self._MESSAGE_MAP[MSG_TYPE.ERROR][MSG_TYPE.SUBSCRIBE] = self._process_SUBSCRIBE_ERROR; self._process_UNSUBSCRIBED = function (msg) { // // process UNSUBSCRIBED reply to UNSUBSCRIBE // var request = msg[1]; if (request in self._unsubscribe_reqs) { var r = self._unsubscribe_reqs[request]; var d = r[0]; var subscription = r[1]; if (subscription.id in self._subscriptions) { var subs = self._subscriptions[subscription.id]; // the following should actually be NOP, since UNSUBSCRIBE was // only sent when subs got empty for (var i = 0; i < subs.length; ++i) { subs[i].active = false; subs[i].on_unsubscribe.resolve(); } delete self._subscriptions[subscription]; } d.resolve(true); delete self._unsubscribe_reqs[request]; } else { if (request === 0) { // router actively revoked our subscription // var details = msg[2]; var subscription_id = details.subscription; var reason = details.reason; if (subscription_id in self._subscriptions) { var subs = self._subscriptions[subscription_id]; for (var i = 0; i < subs.length; ++i) { subs[i].active = false; subs[i]._on_unsubscribe.resolve(reason); } delete self._subscriptions[subscription_id]; } else { self._protocol_violation("non-voluntary UNSUBSCRIBED received for non-existing subscription ID " + subscription_id); } } else { self._protocol_violation("UNSUBSCRIBED received for non-pending request ID " + request); } } }; self._MESSAGE_MAP[MSG_TYPE.UNSUBSCRIBED] = self._process_UNSUBSCRIBED; self._process_UNSUBSCRIBE_ERROR = function (msg) { // // process ERROR reply to UNSUBSCRIBE // var request = msg[2]; if (request in self._unsubscribe_reqs) { var details = msg[3]; var error = new Error(msg[4], msg[5], msg[6]); var r = self._unsubscribe_reqs[request]; var d = r[0]; var subscription = r[1]; d.reject(error); delete self._unsubscribe_reqs[request]; } else { self._protocol_violation("UNSUBSCRIBE-ERROR received for non-pending request ID " + request); } }; self._MESSAGE_MAP[MSG_TYPE.ERROR][MSG_TYPE.UNSUBSCRIBE] = self._process_UNSUBSCRIBE_ERROR; self._process_PUBLISHED = function (msg) { // // process PUBLISHED reply to PUBLISH // var request = msg[1]; var publication = msg[2]; if (request in self._publish_reqs) { var r = self._publish_reqs[request]; var d = r[0]; var options = r[1]; var pub = new Publication(publication); d.resolve(pub); delete self._publish_reqs[request]; } else { self._protocol_violation("PUBLISHED received for non-pending request ID " + request); } }; self._MESSAGE_MAP[MSG_TYPE.PUBLISHED] = self._process_PUBLISHED; self._process_PUBLISH_ERROR = function (msg) { // // process ERROR reply to PUBLISH // var request = msg[2]; if (request in self._publish_reqs) { var details = msg[3]; var error = new Error(msg[4], msg[5], msg[6]); var r = self._publish_reqs[request]; var d = r[0]; var options = r[1]; d.reject(error); delete self._publish_reqs[request]; } else { self._protocol_violation("PUBLISH-ERROR received for non-pending request ID " + request); } }; self._MESSAGE_MAP[MSG_TYPE.ERROR][MSG_TYPE.PUBLISH] = self._process_PUBLISH_ERROR; self._process_EVENT = function (msg) { // // process EVENT message // // [EVENT, SUBSCRIBED.Subscription|id, PUBLISHED.Publication|id, Details|dict, PUBLISH.Arguments|list, PUBLISH.ArgumentsKw|dict] var subscription = msg[1]; if (subscription in self._subscriptions) { var publication = msg[2]; var details = msg[3]; var args = msg[4] || []; var kwargs = msg[5] || {}; var ed = new Event(publication, details.publisher, details.topic); var subs = self._subscriptions[subscription]; for (var i = 0; i < subs.length; ++i) { try { subs[i].handler(args, kwargs, ed); } catch (e) { log.debug("Exception raised in event handler", e); } } } else { self._protocol_violation("EVENT received for non-subscribed subscription ID " + subscription); } }; self._MESSAGE_MAP[MSG_TYPE.EVENT] = self._process_EVENT; self._process_REGISTERED = function (msg) { // // process REGISTERED reply to REGISTER // var request = msg[1]; var registration = msg[2]; if (request in self._register_reqs) { var r = self._register_reqs[request]; var d = r[0]; var procedure = r[1]; var endpoint = r[2]; var options = r[3]; var reg = new Registration(procedure, endpoint, options, self, registration); self._registrations[registration] = reg; d.resolve(reg); delete self._register_reqs[request]; } else { self._protocol_violation("REGISTERED received for non-pending request ID " + request); } }; self._MESSAGE_MAP[MSG_TYPE.REGISTERED] = self._process_REGISTERED; self._process_REGISTER_ERROR = function (msg) { // // process ERROR reply to REGISTER // var request = msg[2]; if (request in self._register_reqs) { var details = msg[3]; var error = new Error(msg[4], msg[5], msg[6]); var r = self._register_reqs[request]; var d = r[0]; d.reject(error); delete self._register_reqs[request]; } else { self._protocol_violation("REGISTER-ERROR received for non-pending request ID " + request); } }; self._MESSAGE_MAP[MSG_TYPE.ERROR][MSG_TYPE.REGISTER] = self._process_REGISTER_ERROR; self._process_UNREGISTERED = function (msg) { // // process UNREGISTERED reply to UNREGISTER // var request = msg[1]; if (request in self._unregister_reqs) { var r = self._unregister_reqs[request]; var d = r[0]; var registration = r[1]; if (registration.id in self._registrations) { delete self._registrations[registration.id]; } registration.active = false; d.resolve(); delete self._unregister_reqs[request]; } else { if (request === 0) { // the router actively revoked our registration // var details = msg[2]; var registration_id = details.registration; var reason = details.reason; if (registration_id in self._registrations) { var registration = self._registrations[registration_id]; registration.active = false; registration._on_unregister.resolve(reason); delete self._registrations[registration_id]; } else { self._protocol_violation("non-voluntary UNREGISTERED received for non-existing registration ID " + registration_id); } } else { self._protocol_violation("UNREGISTERED received for non-pending request ID " + request); } } }; self._MESSAGE_MAP[MSG_TYPE.UNREGISTERED] = self._process_UNREGISTERED; self._process_UNREGISTER_ERROR = function (msg) { // // process ERROR reply to UNREGISTER // var request = msg[2]; if (request in self._unregister_reqs) { var details = msg[3]; var error = new Error(msg[4], msg[5], msg[6]); var r = self._unregister_reqs[request]; var d = r[0]; var registration = r[1]; d.reject(error); delete self._unregister_reqs[request]; } else { self._protocol_violation("UNREGISTER-ERROR received for non-pending request ID " + request); } }; self._MESSAGE_MAP[MSG_TYPE.ERROR][MSG_TYPE.UNREGISTER] = self._process_UNREGISTER_ERROR; self._process_RESULT = function (msg) { // // process RESULT reply to CALL // var request = msg[1]; if (request in self._call_reqs) { var details = msg[2]; var args = msg[3] || []; var kwargs = msg[4] || {}; // maybe wrap complex result: var result = null; if (args.length > 1 || Object.keys(kwargs).length > 0) { // wrap complex result is more than 1 positional result OR // non-empty keyword result result = new Result(args, kwargs); } else if (args.length > 0) { // single positional result result = args[0]; } var r = self._call_reqs[request]; var d = r[0]; var options = r[1]; if (details.progress) { if (options && options.receive_progress) { d.notify(result); } } else { d.resolve(result); delete self._call_reqs[request]; } } else { self._protocol_violation("CALL-RESULT received for non-pending request ID " + request); } }; self._MESSAGE_MAP[MSG_TYPE.RESULT] = self._process_RESULT; self._process_CALL_ERROR = function (msg) { // // process ERROR reply to CALL // var request = msg[2]; if (request in self._call_reqs) { var details = msg[3]; var error = new Error(msg[4], msg[5], msg[6]); var r = self._call_reqs[request]; var d = r[0]; var options = r[1]; d.reject(error); delete self._call_reqs[request]; } else { self._protocol_violation("CALL-ERROR received for non-pending request ID " + request); } }; self._MESSAGE_MAP[MSG_TYPE.ERROR][MSG_TYPE.CALL] = self._process_CALL_ERROR; self._process_INVOCATION = function (msg) { // // process INVOCATION message // // [INVOCATION, Request|id, REGISTERED.Registration|id, Details|dict, CALL.Arguments|list, CALL.ArgumentsKw|dict] // var request = msg[1]; var registration = msg[2]; var details = msg[3]; // receive_progress // timeout // caller if (registration in self._registrations) { var endpoint = self._registrations[registration].endpoint; var args = msg[4] || []; var kwargs = msg[5] || {}; // create progress function for invocation // var progress = null; if (details.receive_progress) { progress = function (args, kwargs) { var progress_msg = [MSG_TYPE.YIELD, request, {progress: true}]; args = args || []; kwargs = kwargs || {}; var kwargs_len = Object.keys(kwargs).length; if (args.length || kwargs_len) { progress_msg.push(args); if (kwargs_len) { progress_msg.push(kwargs); } } self._send_wamp(progress_msg); } }; var cd = new Invocation(details.caller, progress, details.procedure); // We use the following whenjs call wrapper, which automatically // wraps a plain, non-promise value in a (immediately resolved) promise // // See: https://github.com/cujojs/when/blob/master/docs/api.md#fncall // when_fn.call(endpoint, args, kwargs, cd).then( function (res) { // construct YIELD message // FIXME: Options // var reply = [MSG_TYPE.YIELD, request, {}]; if (res instanceof Result) { var kwargs_len = Object.keys(res.kwargs).length; if (res.args.length || kwargs_len) { reply.push(res.args); if (kwargs_len) { reply.push(res.kwargs); } } } else { reply.push([res]); } // send WAMP message // self._send_wamp(reply); }, function (err) { // construct ERROR message // [ERROR, REQUEST.Type|int, REQUEST.Request|id, Details|dict, Error|uri, Arguments|list, ArgumentsKw|dict] var reply = [MSG_TYPE.ERROR, MSG_TYPE.INVOCATION, request, {}]; if (err instanceof Error) { reply.push(err.error); var kwargs_len = Object.keys(err.kwargs).length; if (err.args.length || kwargs_len) { reply.push(err.args); if (kwargs_len) { reply.push(err.kwargs); } } } else { reply.push('wamp.error.runtime_error'); reply.push([err]); } // send WAMP message // self._send_wamp(reply); } ); } else { self._protocol_violation("INVOCATION received for non-registered registration ID " + request); } }; self._MESSAGE_MAP[MSG_TYPE.INVOCATION] = self._process_INVOCATION; // callback fired by WAMP transport on receiving a WAMP message // self._socket.onmessage = function (msg) { var msg_type = msg[0]; // WAMP session not yet open // if (!self._id) { // the first message must be WELCOME, ABORT or CHALLENGE .. // if (msg_type === MSG_TYPE.WELCOME) { self._id = msg[1]; // determine actual set of advanced features that can be used // var rf = msg[2]; self._features = {}; if (rf.roles.broker) { // "Basic Profile" is mandatory self._features.subscriber = {}; self._features.publisher = {}; // fill in features that both peers support if (rf.roles.broker.features) { for (var att in WAMP_FEATURES.publisher.features) { self._features.publisher[att] = WAMP_FEATURES.publisher.features[att] && rf.roles.broker.features[att]; } for (var att in WAMP_FEATURES.subscriber.features) { self._features.subscriber[att] = WAMP_FEATURES.subscriber.features[att] && rf.roles.broker.features[att]; } } } if (rf.roles.dealer) { // "Basic Profile" is mandatory self._features.caller = {}; self._features.callee = {}; // fill in features that both peers support if (rf.roles.dealer.features) { for (var att in WAMP_FEATURES.caller.features) { self._features.caller[att] = WAMP_FEATURES.caller.features[att] && rf.roles.dealer.features[att]; } for (var att in WAMP_FEATURES.callee.features) { self._features.callee[att] = WAMP_FEATURES.callee.features[att] && rf.roles.dealer.features[att]; } } } if (self.onjoin) { self.onjoin(msg[2]); } } else if (msg_type === MSG_TYPE.ABORT) { var details = msg[1]; var reason = msg[2]; if (self.onleave) { self.onleave(reason, details); } } else if (msg_type === MSG_TYPE.CHALLENGE) { if (self._onchallenge) { var method = msg[1]; var extra = msg[2]; when_fn.call(self._onchallenge, self, method, extra).then( function (signature) { var msg = [MSG_TYPE.AUTHENTICATE, signature, {}]; self._send_wamp(msg); }, function (err) { log.debug("onchallenge() raised:", err); var msg = [MSG_TYPE.ABORT, {message: "sorry, I cannot authenticate (onchallenge handler raised an exception)"}, "wamp.error.cannot_authenticate"]; self._send_wamp(msg); self._socket.close(1000); } ); } else { log.debug("received WAMP challenge, but no onchallenge() handler set"); var msg = [MSG_TYPE.ABORT, {message: "sorry, I cannot authenticate (no onchallenge handler set)"}, "wamp.error.cannot_authenticate"]; self._send_wamp(msg); self._socket.close(1000); } } else { self._protocol_violation("unexpected message type " + msg_type); } // WAMP session is open // } else { if (msg_type === MSG_TYPE.GOODBYE) { if (!self._goodbye_sent) { var reply = [MSG_TYPE.GOODBYE, {}, "wamp.error.goodbye_and_out"]; self._send_wamp(reply); } self._id = null; self._realm = null; self._features = null; var details = msg[1]; var reason = msg[2]; if (self.onleave) { self.onleave(reason, details); } } else { if (msg_type === MSG_TYPE.ERROR) { var request_type = msg[1]; if (request_type in self._MESSAGE_MAP[MSG_TYPE.ERROR]) { self._MESSAGE_MAP[msg_type][request_type](msg); } else { self._protocol_violation("unexpected ERROR message with request_type " + request_type); } } else { if (msg_type in self._MESSAGE_MAP) { self._MESSAGE_MAP[msg_type](msg); } else { self._protocol_violation("unexpected message type " + msg_type); } } } } }; // session object constructed .. track creation time // if ('performance' in global && 'now' in performance) { self._created = performance.now(); } else { self._created = Date.now(); } }; Object.defineProperty(Session.prototype, "defer", { get: function () { return this._defer; } }); Object.defineProperty(Session.prototype, "id", { get: function () { return this._id; } }); Object.defineProperty(Session.prototype, "realm", { get: function () { return this._realm; } }); Object.defineProperty(Session.prototype, "isOpen", { get: function () { return this.id !== null; } }); Object.defineProperty(Session.prototype, "features", { get: function () { return this._features; } }); Object.defineProperty(Session.prototype, "caller_disclose_me", { get: function () { return this._caller_disclose_me; }, set: function (newValue) { this._caller_disclose_me = newValue; } }); Object.defineProperty(Session.prototype, "publisher_disclose_me", { get: function () { return this._publisher_disclose_me; }, set: function (newValue) { this._publisher_disclose_me = newValue; } }); Object.defineProperty(Session.prototype, "subscriptions", { get: function () { var keys = Object.keys(this._subscriptions); var vals = []; for (var i = 0; i < keys.length; ++i) { vals.push(this._subscriptions[keys[i]]); } return vals; } }); Object.defineProperty(Session.prototype, "registrations", { get: function () { var keys = Object.keys(this._registrations); var vals = []; for (var i = 0; i < keys.length; ++i) { vals.push(this._registrations[keys[i]]); } return vals; } }); Session.prototype.log = function () { var self = this; if ('console' in global) { var header = null; if (self._id && self._created) { var now = null; if ('performance' in global && 'now' in performance) { now = performance.now() - self._created; } else { now = Date.now() - self._created; } header = "WAMP session " + self._id + " on '" + self._realm + "' at " + Math.round(now * 1000) / 1000 + " ms"; } else { header = "WAMP session"; } if ('group' in console) { console.group(header); for (var i = 0; i < arguments.length; i += 1) { console.log(arguments[i]); } console.groupEnd(); } else { var items = [header + ": "]; for (var i = 0; i < arguments.length; i += 1) { items.push(arguments[i]); } console.log.apply(console, items); } } }; Session.prototype.join = function (realm, authmethods, authid) { util.assert(typeof realm === 'string', "Session.join: <realm> must be a string"); util.assert(!authmethods || Array.isArray(authmethods), "Session.join: <authmethods> must be an array []"); util.assert(!authid || typeof authid === 'string', "Session.join: <authid> must be a string"); var self = this; if (self.isOpen) { throw "session already open"; } self._goodbye_sent = false; self._realm = realm; var details = {}; details.roles = WAMP_FEATURES; if (authmethods) { details.authmethods = authmethods; } if (authid) { details.authid = authid; } var msg = [MSG_TYPE.HELLO, realm, details]; self._send_wamp(msg); }; Session.prototype.leave = function (reason, message) { util.assert(!reason || typeof reason === 'string', "Session.leave: <reason> must be a string"); util.assert(!message || typeof message === 'string', "Session.leave: <message> must be a string"); var self = this; if (!self.isOpen) { throw "session not open"; } if (!reason) { reason = "wamp.close.normal"; } var details = {}; if (message) { details.message = message; } var msg = [MSG_TYPE.GOODBYE, details, reason]; self._send_wamp(msg); self._goodbye_sent = true; }; Session.prototype.call = function (procedure, args, kwargs, options) { util.assert(typeof procedure === 'string', "Session.call: <procedure> must be a string"); util.assert(!args || Array.isArray(args), "Session.call: <args> must be an array []"); util.assert(!kwargs || kwargs instanceof Object, "Session.call: <kwargs> must be an object {}"); util.assert(!options || options instanceof Object, "Session.call: <options> must be an object {}"); var self = this; if (!self.isOpen) { throw "session not open"; } options = options || {}; // only set option if user hasn't set a value and global option is "on" if (options.disclose_me === undefined && self._caller_disclose_me) { options.disclose_me = true; } // create and remember new CALL request // var d = self._defer(); var request = newid(); self._call_reqs[request] = [d, options]; // construct CALL message // var msg = [MSG_TYPE.CALL, request, options, self.resolve(procedure)]; if (args) { msg.push(args); if (kwargs) { msg.push(kwargs); } } else if (kwargs) { msg.push([]); msg.push(kwargs); } // send WAMP message // self._send_wamp(msg); if (d.promise.then) { // whenjs has the actual user promise in an attribute return d.promise; } else { return d; } }; Session.prototype.publish = function (topic, args, kwargs, options) { util.assert(typeof topic === 'string', "Session.publish: <topic> must be a string"); util.assert(!args || Array.isArray(args), "Session.publish: <args> must be an array []"); util.assert(!kwargs || kwargs instanceof Object, "Session.publish: <kwargs> must be an object {}"); util.assert(!options || options instanceof Object, "Session.publish: <options> must be an object {}"); var self = this; if (!self.isOpen) { throw "session not open"; } options = options || {}; // only set option if user hasn't set a value and global option is "on" if (options.disclose_me === undefined && self._publisher_disclose_me) { options.disclose_me = true; } // create and remember new PUBLISH request // var d = null; var request = newid(); if (options.acknowledge) { d = self._defer(); self._publish_reqs[request] = [d, options]; } // construct PUBLISH message // var msg = [MSG_TYPE.PUBLISH, request, options, self.resolve(topic)]; if (args) { msg.push(args); if (kwargs) { msg.push(kwargs); } } else if (kwargs) { msg.push([]); msg.push(kwargs); } // send WAMP message // self._send_wamp(msg); if (d) { if (d.promise.then) { // whenjs has the actual user promise in an attribute return d.promise; } else { return d; } } }; Session.prototype.subscribe = function (topic, handler, options) { util.assert(typeof topic === 'string', "Session.subscribe: <topic> must be a string"); util.assert(typeof handler === 'function', "Session.subscribe: <handler> must be a function"); util.assert(!options || options instanceof Object, "Session.subscribe: <options> must be an object {}"); var self = this; if (!self.isOpen) { throw "session not open"; } // create an remember new SUBSCRIBE request // var request = newid(); var d = self._defer(); self._subscribe_reqs[request] = [d, topic, handler, options]; // construct SUBSCRIBE message // var msg = [MSG_TYPE.SUBSCRIBE, request]; if (options) { msg.push(options); } else { msg.push({}); } msg.push(self.resolve(topic)); // send WAMP message // self._send_wamp(msg); if (d.promise.then) { // whenjs has the actual user promise in an attribute return d.promise; } else { return d; } }; Session.prototype.register = function (procedure, endpoint, options) { util.assert(typeof procedure === 'string', "Session.register: <procedure> must be a string"); util.assert(typeof endpoint === 'function', "Session.register: <endpoint> must be a function"); util.assert(!options || options instanceof Object, "Session.register: <options> must be an object {}"); var self = this; if (!self.isOpen) { throw "session not open"; } // create an remember new REGISTER request // var request = newid(); var d = self._defer(); self._register_reqs[request] = [d, procedure, endpoint, options]; // construct REGISTER message // var msg = [MSG_TYPE.REGISTER, request]; if (options) { msg.push(options); } else { msg.push({}); } msg.push(self.resolve(procedure)); // send WAMP message // self._send_wamp(msg); if (d.promise.then) { // whenjs has the actual user promise in an attribute return d.promise; } else { return d; } }; Session.prototype.unsubscribe = function (subscription) { util.assert(subscription instanceof Subscription, "Session.unsubscribe: <subscription> must be an instance of class autobahn.Subscription"); var self = this; if (!self.isOpen) { throw "session not open"; } if (!subscription.active || !(subscription.id in self._subscriptions)) { throw "subscription not active"; } var subs = self._subscriptions[subscription.id]; var i = subs.indexOf(subscription); if (i === -1) { throw "subscription not active"; } // remove handler subscription subs.splice(i, 1); subscription.active = false; var d = self._defer(); if (subs.length) { // there are still handlers on the subscription .. d.resolve(false); } else { // no handlers left .. // create and remember new UNSUBSCRIBE request // var request = newid(); self._unsubscribe_reqs[request] = [d, subscription.id]; // construct UNSUBSCRIBE message // var msg = [MSG_TYPE.UNSUBSCRIBE, request, subscription.id]; // send WAMP message // self._send_wamp(msg); } if (d.promise.then) { // whenjs has the actual user promise in an attribute return d.promise; } else { return d; } }; Session.prototype.unregister = function (registration) { util.assert(registration instanceof Registration, "Session.unregister: <registration> must be an instance of class autobahn.Registration"); var self = this; if (!self.isOpen) { throw "session not open"; } if (!registration.active || !(registration.id in self._registrations)) { throw "registration not active"; } // create and remember new UNREGISTER request // var request = newid(); var d = self._defer(); self._unregister_reqs[request] = [d, registration]; // construct UNREGISTER message // var msg = [MSG_TYPE.UNREGISTER, request, registration.id]; // send WAMP message // self._send_wamp(msg); if (d.promise.then) { // whenjs has the actual user promise in an attribute return d.promise; } else { return d; } }; Session.prototype.prefix = function (prefix, uri) { util.assert(typeof prefix === 'string', "Session.prefix: <prefix> must be a string"); util.assert(!uri || typeof uri === 'string', "Session.prefix: <uri> must be a string or falsy"); var self = this; if (uri) { self._prefixes[prefix] = uri; } else { if (prefix in self._prefixes) { delete self._prefixes[prefix]; } } }; Session.prototype.resolve = function (curie) { util.assert(typeof curie === 'string', "Session.resolve: <curie> must be a string"); var self = this; // skip if not a CURIE var i = curie.indexOf(":"); if (i >= 0) { var prefix = curie.substring(0, i); if (prefix in self._prefixes) { return self._prefixes[prefix] + '.' + curie.substring(i + 1); } else { throw "cannot resolve CURIE prefix '" + prefix + "'"; } } else { return curie; } }; exports.Session = Session; exports.Invocation = Invocation; exports.Event = Event; exports.Result = Result; exports.Error = Error; exports.Subscription = Subscription; exports.Registration = Registration; exports.Publication = Publication; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./log.js":7,"./util.js":19,"when":78,"when/function":54}],17:[function(require,module,exports){ /////////////////////////////////////////////////////////////////////////////// // // AutobahnJS - http://autobahn.ws, http://wamp.ws // // A JavaScript library for WAMP ("The Web Application Messaging Protocol"). // // Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com // // Licensed under the MIT License. // http://www.opensource.org/licenses/mit-license.php // /////////////////////////////////////////////////////////////////////////////// var util = require('../util.js'); var log = require('../log.js'); var when = require('when'); function Factory (options) { var self = this; util.assert(options.url !== undefined, "options.url missing"); util.assert(typeof options.url === "string", "options.url must be a string"); self._options = options; }; Factory.prototype.type = "longpoll"; Factory.prototype.create = function () { var self = this; log.debug("longpoll.Factory.create"); // the WAMP transport we create var transport = {}; // these will get defined further below transport.protocol = undefined; transport.send = undefined; transport.close = undefined; // these will get overridden by the WAMP session using this transport transport.onmessage = function () {}; transport.onopen = function () {}; transport.onclose = function () {}; transport.info = { type: 'longpoll', url: null, protocol: 'wamp.2.json' }; transport._run = function () { var session_info = null; var send_buffer = []; var is_closing = false; var txseq = 0; var rxseq = 0; var options = {'protocols': ['wamp.2.json']}; var request_timeout = self._options.request_timeout || 2000; util.http_post(self._options.url + '/open', JSON.stringify(options), request_timeout).then( function (payload) { session_info = JSON.parse(payload); var base_url = self._options.url + '/' + session_info.transport; transport.info.url = base_url; log.debug("longpoll.Transport: open", session_info); transport.close = function (code, reason) { if (is_closing) { throw "transport is already closing"; } is_closing = true; util.http_post(base_url + '/close', null, request_timeout).then( function () { log.debug("longpoll.Transport: transport closed"); var details = { code: 1000, reason: "transport closed", wasClean: true } transport.onclose(details); }, function (err) { log.debug("longpoll.Transport: could not close transport", err.code, err.text); } ); } transport.send = function (msg) { if (is_closing) { throw "transport is closing or closed already"; } txseq += 1; log.debug("longpoll.Transport: sending message ...", msg); var payload = JSON.stringify(msg); util.http_post(base_url + '/send', payload, request_timeout).then( function () { // ok, message sent log.debug("longpoll.Transport: message sent"); }, function (err) { log.debug("longpoll.Transport: could not send message", err.code, err.text); is_closing = true; var details = { code: 1001, reason: "transport send failure (HTTP/POST status " + err.code + " - '" + err.text + "')", wasClean: false } transport.onclose(details); } ); }; function receive() { rxseq += 1; log.debug("longpoll.Transport: polling for message ..."); util.http_post(base_url + '/receive', null, request_timeout).then( function (payload) { if (payload) { var msg = JSON.parse(payload); log.debug("longpoll.Transport: message received", msg); transport.onmessage(msg); } if (!is_closing) { receive(); } }, function (err) { log.debug("longpoll.Transport: could not receive message", err.code, err.text); is_closing = true; var details = { code: 1001, reason: "transport receive failure (HTTP/POST status " + err.code + " - '" + err.text + "')", wasClean: false } transport.onclose(details); } ); } receive(); transport.onopen(); }, function (err) { log.debug("longpoll.Transport: could not open transport", err.code, err.text); is_closing = true; var details = { code: 1001, reason: "transport open failure (HTTP/POST status " + err.code + " - '" + err.text + "')", wasClean: false } transport.onclose(details); } ); } transport._run(); return transport; }; exports.Factory = Factory; },{"../log.js":7,"../util.js":19,"when":78}],18:[function(require,module,exports){ (function (global){ /////////////////////////////////////////////////////////////////////////////// // // AutobahnJS - http://autobahn.ws, http://wamp.ws // // A JavaScript library for WAMP ("The Web Application Messaging Protocol"). // // Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com // // Licensed under the MIT License. // http://www.opensource.org/licenses/mit-license.php // /////////////////////////////////////////////////////////////////////////////// var util = require('../util.js'); var log = require('../log.js'); function Factory (options) { var self = this; util.assert(options.url !== undefined, "options.url missing"); util.assert(typeof options.url === "string", "options.url must be a string"); if (!options.protocols) { options.protocols = ['wamp.2.json']; } else { util.assert(Array.isArray(options.protocols), "options.protocols must be an array"); } self._options = options; } Factory.prototype.type = "websocket"; Factory.prototype.create = function () { var self = this; // the WAMP transport we create var transport = {}; // these will get defined further below transport.protocol = undefined; transport.send = undefined; transport.close = undefined; // these will get overridden by the WAMP session using this transport transport.onmessage = function () {}; transport.onopen = function () {}; transport.onclose = function () {}; transport.info = { type: 'websocket', url: null, protocol: 'wamp.2.json' }; // // running in Node.js // if (global.process && global.process.versions.node) { (function () { var WebSocket = require('ws'); // https://github.com/einaros/ws var websocket; var protocols; if (self._options.protocols) { protocols = self._options.protocols; if (Array.isArray(protocols)) { protocols = protocols.join(','); } websocket = new WebSocket(self._options.url, {protocol: protocols}); } else { websocket = new WebSocket(self._options.url); } transport.send = function (msg) { var payload = JSON.stringify(msg); websocket.send(payload, {binary: false}); }; transport.close = function (code, reason) { websocket.close(); }; websocket.on('open', function () { transport.onopen(); }); websocket.on('message', function (data, flags) { if (flags.binary) { // FIXME! } else { var msg = JSON.parse(data); transport.onmessage(msg); } }); // FIXME: improve mapping to WS API for the following // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Close_codes // websocket.on('close', function (code, message) { var details = { code: code, reason: message, wasClean: code === 1000 } transport.onclose(details); }); websocket.on('error', function (error) { var details = { code: 1006, reason: '', wasClean: false } transport.onclose(details); }); })(); // // running in the browser // } else { (function () { var websocket; // Chrome, MSIE, newer Firefox if ("WebSocket" in global) { if (self._options.protocols) { websocket = new global.WebSocket(self._options.url, self._options.protocols); } else { websocket = new global.WebSocket(self._options.url); } // older versions of Firefox prefix the WebSocket object } else if ("MozWebSocket" in global) { if (self._options.protocols) { websocket = new global.MozWebSocket(self._options.url, self._options.protocols); } else { websocket = new global.MozWebSocket(self._options.url); } } else { throw "browser does not support WebSocket"; } websocket.onmessage = function (evt) { log.debug("WebSocket transport receive", evt.data); var msg = JSON.parse(evt.data); transport.onmessage(msg); } websocket.onopen = function () { transport.info.url = self._options.url; transport.onopen(); } websocket.onclose = function (evt) { var details = { code: evt.code, reason: evt.message, wasClean: evt.wasClean } transport.onclose(details); } // do NOT do the following, since that will make // transport.onclose() fire twice (browsers already fire // websocket.onclose() for errors also) //websocket.onerror = websocket.onclose; transport.send = function (msg) { var payload = JSON.stringify(msg); log.debug("WebSocket transport send", payload); websocket.send(payload); } transport.close = function (code, reason) { websocket.close(code, reason); }; })(); } return transport; }; exports.Factory = Factory; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../log.js":7,"../util.js":19,"ws":79}],19:[function(require,module,exports){ (function (global){ /////////////////////////////////////////////////////////////////////////////// // // AutobahnJS - http://autobahn.ws, http://wamp.ws // // A JavaScript library for WAMP ("The Web Application Messaging Protocol"). // // Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com // // Licensed under the MIT License. // http://www.opensource.org/licenses/mit-license.php // /////////////////////////////////////////////////////////////////////////////// var log = require('./log.js'); var when = require('when'); var rand_normal = function (mean, sd) { // Derive a Gaussian from Uniform random variables // http://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform var x1, x2, rad; do { x1 = 2 * Math.random() - 1; x2 = 2 * Math.random() - 1; rad = x1 * x1 + x2 * x2; } while (rad >= 1 || rad == 0); var c = Math.sqrt(-2 * Math.log(rad) / rad); return (mean || 0) + (x1 * c) * (sd || 1); }; var assert = function (cond, text) { if (cond) { return; } if (assert.useDebugger || ('AUTOBAHN_DEBUG' in global && AUTOBAHN_DEBUG)) { debugger; } throw new Error(text || "Assertion failed!"); }; // Helper to do HTTP/POST requests returning deferreds. This function is // supposed to work on IE8, IE9 and old Android WebKit browsers. We don't care // if it works with other browsers. // var http_post = function (url, data, timeout) { log.debug("new http_post request", url, data, timeout); var d = when.defer(); var req = new XMLHttpRequest(); req.onreadystatechange = function () { if (req.readyState === 4) { // Normalize IE's response to HTTP 204 when Win error 1223. // http://stackoverflow.com/a/10047236/884770 // var status = (req.status === 1223) ? 204 : req.status; if (status === 200) { // response with content // d.resolve(req.responseText); } if (status === 204) { // empty response // d.resolve(); } else { // anything else is a fail // var statusText = null; try { statusText = req.statusText; } catch (e) { // IE8 fucks up on this } d.reject({code: status, text: statusText}); } } } req.open("POST", url, true); req.setRequestHeader("Content-type", "application/json; charset=utf-8"); if (timeout > 0) { req.timeout = timeout; // request timeout in ms req.ontimeout = function () { d.reject({code: 501, text: "request timeout"}); } } if (data) { req.send(data); } else { req.send(); } if (d.promise.then) { // whenjs has the actual user promise in an attribute return d.promise; } else { return d; } }; exports.rand_normal = rand_normal; exports.assert = assert; exports.http_post = http_post; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./log.js":7,"when":78}],20:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Lookup tables var SBOX = []; var INV_SBOX = []; var SUB_MIX_0 = []; var SUB_MIX_1 = []; var SUB_MIX_2 = []; var SUB_MIX_3 = []; var INV_SUB_MIX_0 = []; var INV_SUB_MIX_1 = []; var INV_SUB_MIX_2 = []; var INV_SUB_MIX_3 = []; // Compute lookup tables (function () { // Compute double table var d = []; for (var i = 0; i < 256; i++) { if (i < 128) { d[i] = i << 1; } else { d[i] = (i << 1) ^ 0x11b; } } // Walk GF(2^8) var x = 0; var xi = 0; for (var i = 0; i < 256; i++) { // Compute sbox var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; SBOX[x] = sx; INV_SBOX[sx] = x; // Compute multiplication var x2 = d[x]; var x4 = d[x2]; var x8 = d[x4]; // Compute sub bytes, mix columns tables var t = (d[sx] * 0x101) ^ (sx * 0x1010100); SUB_MIX_0[x] = (t << 24) | (t >>> 8); SUB_MIX_1[x] = (t << 16) | (t >>> 16); SUB_MIX_2[x] = (t << 8) | (t >>> 24); SUB_MIX_3[x] = t; // Compute inv sub bytes, inv mix columns tables var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); INV_SUB_MIX_3[sx] = t; // Compute next counter if (!x) { x = xi = 1; } else { x = x2 ^ d[d[d[x8 ^ x2]]]; xi ^= d[d[xi]]; } } }()); // Precomputed Rcon lookup var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; /** * AES block cipher algorithm. */ var AES = C_algo.AES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySize = key.sigBytes / 4; // Compute number of rounds var nRounds = this._nRounds = keySize + 6 // Compute number of key schedule rows var ksRows = (nRounds + 1) * 4; // Compute key schedule var keySchedule = this._keySchedule = []; for (var ksRow = 0; ksRow < ksRows; ksRow++) { if (ksRow < keySize) { keySchedule[ksRow] = keyWords[ksRow]; } else { var t = keySchedule[ksRow - 1]; if (!(ksRow % keySize)) { // Rot word t = (t << 8) | (t >>> 24); // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; // Mix Rcon t ^= RCON[(ksRow / keySize) | 0] << 24; } else if (keySize > 6 && ksRow % keySize == 4) { // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; } keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; } } // Compute inv key schedule var invKeySchedule = this._invKeySchedule = []; for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { var ksRow = ksRows - invKsRow; if (invKsRow % 4) { var t = keySchedule[ksRow]; } else { var t = keySchedule[ksRow - 4]; } if (invKsRow < 4 || ksRow <= 4) { invKeySchedule[invKsRow] = t; } else { invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; } } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); }, decryptBlock: function (M, offset) { // Swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); // Inv swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; }, _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { // Shortcut var nRounds = this._nRounds; // Get input, add round key var s0 = M[offset] ^ keySchedule[0]; var s1 = M[offset + 1] ^ keySchedule[1]; var s2 = M[offset + 2] ^ keySchedule[2]; var s3 = M[offset + 3] ^ keySchedule[3]; // Key schedule row counter var ksRow = 4; // Rounds for (var round = 1; round < nRounds; round++) { // Shift rows, sub bytes, mix columns, add round key var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; // Update state s0 = t0; s1 = t1; s2 = t2; s3 = t3; } // Shift rows, sub bytes, add round key var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; // Set output M[offset] = t0; M[offset + 1] = t1; M[offset + 2] = t2; M[offset + 3] = t3; }, keySize: 256/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); */ C.AES = BlockCipher._createHelper(AES); }()); return CryptoJS.AES; })); },{"./cipher-core":21,"./core":22,"./enc-base64":23,"./evpkdf":25,"./md5":30}],21:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher core components. */ CryptoJS.lib.Cipher || (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var Base64 = C_enc.Base64; var C_algo = C.algo; var EvpKDF = C_algo.EvpKDF; /** * Abstract base cipher template. * * @property {number} keySize This cipher's key size. Default: 4 (128 bits) * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. */ var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ /** * Configuration options. * * @property {WordArray} iv The IV to use for this operation. */ cfg: Base.extend(), /** * Creates this cipher in encryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); */ createEncryptor: function (key, cfg) { return this.create(this._ENC_XFORM_MODE, key, cfg); }, /** * Creates this cipher in decryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); */ createDecryptor: function (key, cfg) { return this.create(this._DEC_XFORM_MODE, key, cfg); }, /** * Initializes a newly created cipher. * * @param {number} xformMode Either the encryption or decryption transormation mode constant. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @example * * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); */ init: function (xformMode, key, cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Store transform mode and key this._xformMode = xformMode; this._key = key; // Set initial values this.reset(); }, /** * Resets this cipher to its initial state. * * @example * * cipher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-cipher logic this._doReset(); }, /** * Adds data to be encrypted or decrypted. * * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. * * @return {WordArray} The data after processing. * * @example * * var encrypted = cipher.process('data'); * var encrypted = cipher.process(wordArray); */ process: function (dataUpdate) { // Append this._append(dataUpdate); // Process available blocks return this._process(); }, /** * Finalizes the encryption or decryption process. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. * * @return {WordArray} The data after final processing. * * @example * * var encrypted = cipher.finalize(); * var encrypted = cipher.finalize('data'); * var encrypted = cipher.finalize(wordArray); */ finalize: function (dataUpdate) { // Final data update if (dataUpdate) { this._append(dataUpdate); } // Perform concrete-cipher logic var finalProcessedData = this._doFinalize(); return finalProcessedData; }, keySize: 128/32, ivSize: 128/32, _ENC_XFORM_MODE: 1, _DEC_XFORM_MODE: 2, /** * Creates shortcut functions to a cipher's object interface. * * @param {Cipher} cipher The cipher to create a helper for. * * @return {Object} An object with encrypt and decrypt shortcut functions. * * @static * * @example * * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); */ _createHelper: (function () { function selectCipherStrategy(key) { if (typeof key == 'string') { return PasswordBasedCipher; } else { return SerializableCipher; } } return function (cipher) { return { encrypt: function (message, key, cfg) { return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); }, decrypt: function (ciphertext, key, cfg) { return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); } }; }; }()) }); /** * Abstract base stream cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) */ var StreamCipher = C_lib.StreamCipher = Cipher.extend({ _doFinalize: function () { // Process partial blocks var finalProcessedBlocks = this._process(!!'flush'); return finalProcessedBlocks; }, blockSize: 1 }); /** * Mode namespace. */ var C_mode = C.mode = {}; /** * Abstract base block cipher mode template. */ var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ /** * Creates this mode for encryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); */ createEncryptor: function (cipher, iv) { return this.Encryptor.create(cipher, iv); }, /** * Creates this mode for decryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); */ createDecryptor: function (cipher, iv) { return this.Decryptor.create(cipher, iv); }, /** * Initializes a newly created mode. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @example * * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); */ init: function (cipher, iv) { this._cipher = cipher; this._iv = iv; } }); /** * Cipher Block Chaining mode. */ var CBC = C_mode.CBC = (function () { /** * Abstract base CBC mode. */ var CBC = BlockCipherMode.extend(); /** * CBC encryptor. */ CBC.Encryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // XOR and encrypt xorBlock.call(this, words, offset, blockSize); cipher.encryptBlock(words, offset); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); /** * CBC decryptor. */ CBC.Decryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); // Decrypt and XOR cipher.decryptBlock(words, offset); xorBlock.call(this, words, offset, blockSize); // This block becomes the previous block this._prevBlock = thisBlock; } }); function xorBlock(words, offset, blockSize) { // Shortcut var iv = this._iv; // Choose mixing block if (iv) { var block = iv; // Remove IV for subsequent blocks this._iv = undefined; } else { var block = this._prevBlock; } // XOR blocks for (var i = 0; i < blockSize; i++) { words[offset + i] ^= block[i]; } } return CBC; }()); /** * Padding namespace. */ var C_pad = C.pad = {}; /** * PKCS #5/7 padding strategy. */ var Pkcs7 = C_pad.Pkcs7 = { /** * Pads data using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to pad. * @param {number} blockSize The multiple that the data should be padded to. * * @static * * @example * * CryptoJS.pad.Pkcs7.pad(wordArray, 4); */ pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Create padding word var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; // Create padding var paddingWords = []; for (var i = 0; i < nPaddingBytes; i += 4) { paddingWords.push(paddingWord); } var padding = WordArray.create(paddingWords, nPaddingBytes); // Add padding data.concat(padding); }, /** * Unpads data that had been padded using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to unpad. * * @static * * @example * * CryptoJS.pad.Pkcs7.unpad(wordArray); */ unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; /** * Abstract base block cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) */ var BlockCipher = C_lib.BlockCipher = Cipher.extend({ /** * Configuration options. * * @property {Mode} mode The block mode to use. Default: CBC * @property {Padding} padding The padding strategy to use. Default: Pkcs7 */ cfg: Cipher.cfg.extend({ mode: CBC, padding: Pkcs7 }), reset: function () { // Reset cipher Cipher.reset.call(this); // Shortcuts var cfg = this.cfg; var iv = cfg.iv; var mode = cfg.mode; // Reset block mode if (this._xformMode == this._ENC_XFORM_MODE) { var modeCreator = mode.createEncryptor; } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { var modeCreator = mode.createDecryptor; // Keep at least one block in the buffer for unpadding this._minBufferSize = 1; } this._mode = modeCreator.call(mode, this, iv && iv.words); }, _doProcessBlock: function (words, offset) { this._mode.processBlock(words, offset); }, _doFinalize: function () { // Shortcut var padding = this.cfg.padding; // Finalize if (this._xformMode == this._ENC_XFORM_MODE) { // Pad data padding.pad(this._data, this.blockSize); // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); // Unpad data padding.unpad(finalProcessedBlocks); } return finalProcessedBlocks; }, blockSize: 128/32 }); /** * A collection of cipher parameters. * * @property {WordArray} ciphertext The raw ciphertext. * @property {WordArray} key The key to this ciphertext. * @property {WordArray} iv The IV used in the ciphering operation. * @property {WordArray} salt The salt used with a key derivation function. * @property {Cipher} algorithm The cipher algorithm. * @property {Mode} mode The block mode used in the ciphering operation. * @property {Padding} padding The padding scheme used in the ciphering operation. * @property {number} blockSize The block size of the cipher. * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. */ var CipherParams = C_lib.CipherParams = Base.extend({ /** * Initializes a newly created cipher params object. * * @param {Object} cipherParams An object with any of the possible cipher parameters. * * @example * * var cipherParams = CryptoJS.lib.CipherParams.create({ * ciphertext: ciphertextWordArray, * key: keyWordArray, * iv: ivWordArray, * salt: saltWordArray, * algorithm: CryptoJS.algo.AES, * mode: CryptoJS.mode.CBC, * padding: CryptoJS.pad.PKCS7, * blockSize: 4, * formatter: CryptoJS.format.OpenSSL * }); */ init: function (cipherParams) { this.mixIn(cipherParams); }, /** * Converts this cipher params object to a string. * * @param {Format} formatter (Optional) The formatting strategy to use. * * @return {string} The stringified cipher params. * * @throws Error If neither the formatter nor the default formatter is set. * * @example * * var string = cipherParams + ''; * var string = cipherParams.toString(); * var string = cipherParams.toString(CryptoJS.format.OpenSSL); */ toString: function (formatter) { return (formatter || this.formatter).stringify(this); } }); /** * Format namespace. */ var C_format = C.format = {}; /** * OpenSSL formatting strategy. */ var OpenSSLFormatter = C_format.OpenSSL = { /** * Converts a cipher params object to an OpenSSL-compatible string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The OpenSSL-compatible string. * * @static * * @example * * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); */ stringify: function (cipherParams) { // Shortcuts var ciphertext = cipherParams.ciphertext; var salt = cipherParams.salt; // Format if (salt) { var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); } else { var wordArray = ciphertext; } return wordArray.toString(Base64); }, /** * Converts an OpenSSL-compatible string to a cipher params object. * * @param {string} openSSLStr The OpenSSL-compatible string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); */ parse: function (openSSLStr) { // Parse base64 var ciphertext = Base64.parse(openSSLStr); // Shortcut var ciphertextWords = ciphertext.words; // Test for salt if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { // Extract salt var salt = WordArray.create(ciphertextWords.slice(2, 4)); // Remove salt from ciphertext ciphertextWords.splice(0, 4); ciphertext.sigBytes -= 16; } return CipherParams.create({ ciphertext: ciphertext, salt: salt }); } }; /** * A cipher wrapper that returns ciphertext as a serializable cipher params object. */ var SerializableCipher = C_lib.SerializableCipher = Base.extend({ /** * Configuration options. * * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL */ cfg: Base.extend({ format: OpenSSLFormatter }), /** * Encrypts a message. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Encrypt var encryptor = cipher.createEncryptor(key, cfg); var ciphertext = encryptor.finalize(message); // Shortcut var cipherCfg = encryptor.cfg; // Create and return serializable cipher params return CipherParams.create({ ciphertext: ciphertext, key: key, iv: cipherCfg.iv, algorithm: cipher, mode: cipherCfg.mode, padding: cipherCfg.padding, blockSize: cipher.blockSize, formatter: cfg.format }); }, /** * Decrypts serialized ciphertext. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Decrypt var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); return plaintext; }, /** * Converts serialized ciphertext to CipherParams, * else assumed CipherParams already and returns ciphertext unchanged. * * @param {CipherParams|string} ciphertext The ciphertext. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. * * @return {CipherParams} The unserialized ciphertext. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); */ _parse: function (ciphertext, format) { if (typeof ciphertext == 'string') { return format.parse(ciphertext, this); } else { return ciphertext; } } }); /** * Key derivation function namespace. */ var C_kdf = C.kdf = {}; /** * OpenSSL key derivation function. */ var OpenSSLKdf = C_kdf.OpenSSL = { /** * Derives a key and IV from a password. * * @param {string} password The password to derive from. * @param {number} keySize The size in words of the key to generate. * @param {number} ivSize The size in words of the IV to generate. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. * * @return {CipherParams} A cipher params object with the key, IV, and salt. * * @static * * @example * * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); */ execute: function (password, keySize, ivSize, salt) { // Generate random salt if (!salt) { salt = WordArray.random(64/8); } // Derive key and IV var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); // Separate key and IV var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); key.sigBytes = keySize * 4; // Return params return CipherParams.create({ key: key, iv: iv, salt: salt }); } }; /** * A serializable cipher wrapper that derives the key from a password, * and returns ciphertext as a serializable cipher params object. */ var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ /** * Configuration options. * * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL */ cfg: SerializableCipher.cfg.extend({ kdf: OpenSSLKdf }), /** * Encrypts a message using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); // Add IV to config cfg.iv = derivedParams.iv; // Encrypt var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); // Mix in derived params ciphertext.mixIn(derivedParams); return ciphertext; }, /** * Decrypts serialized ciphertext using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); // Add IV to config cfg.iv = derivedParams.iv; // Decrypt var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); return plaintext; } }); }()); })); },{"./core":22}],22:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(); } else if (typeof define === "function" && define.amd) { // AMD define([], factory); } else { // Global (browser) root.CryptoJS = factory(); } }(this, function () { /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { function F() {} return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn F.prototype = this; var subtype = new F(); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init')) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else if (thatWords.length > 0xffff) { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } else { // Copy all words at once thisWords.push.apply(thisWords, thatWords); } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; var r = (function (m_w) { var m_w = m_w; var m_z = 0x3ade68b1; var mask = 0xffffffff; return function () { m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; var result = ((m_z << 0x10) + m_w) & mask; result /= 0x100000000; result += 0.5; return result * (Math.random() > .5 ? 1 : -1); } }); for (var i = 0, rcache; i < nBytes; i += 4) { var _r = r((rcache || Math.random()) * 0x100000000); rcache = _r() * 0x3ade67b7; words.push((_r() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); return CryptoJS; })); },{}],23:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * Base64 encoding strategy. */ var Base64 = C_enc.Base64 = { /** * Converts a word array to a Base64 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Base64 string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map = this._map; // Clamp excess bits wordArray.clamp(); // Convert var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); }, /** * Converts a Base64 string to a word array. * * @param {string} base64Str The Base64 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ parse: function (base64Str) { // Shortcuts var base64StrLength = base64Str.length; var map = this._map; // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex != -1) { base64StrLength = paddingIndex; } } // Convert var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; }()); return CryptoJS.enc.Base64; })); },{"./core":22}],24:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * UTF-16 BE encoding strategy. */ var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { /** * Converts a word array to a UTF-16 BE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 BE string. * * @static * * @example * * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 BE string to a word array. * * @param {string} utf16Str The UTF-16 BE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); } return WordArray.create(words, utf16StrLength * 2); } }; /** * UTF-16 LE encoding strategy. */ C_enc.Utf16LE = { /** * Converts a word array to a UTF-16 LE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 LE string. * * @static * * @example * * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 LE string to a word array. * * @param {string} utf16Str The UTF-16 LE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); } return WordArray.create(words, utf16StrLength * 2); } }; function swapEndian(word) { return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); } }()); return CryptoJS.enc.Utf16; })); },{"./core":22}],25:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var MD5 = C_algo.MD5; /** * This key derivation function is meant to conform with EVP_BytesToKey. * www.openssl.org/docs/crypto/EVP_BytesToKey.html */ var EvpKDF = C_algo.EvpKDF = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hash algorithm to use. Default: MD5 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: MD5, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.EvpKDF.create(); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init hasher var hasher = cfg.hasher.create(); // Initial values var derivedKey = WordArray.create(); // Shortcuts var derivedKeyWords = derivedKey.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { if (block) { hasher.update(block); } var block = hasher.update(password).finalize(salt); hasher.reset(); // Iterations for (var i = 1; i < iterations; i++) { block = hasher.finalize(block); hasher.reset(); } derivedKey.concat(block); } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.EvpKDF(password, salt); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); */ C.EvpKDF = function (password, salt, cfg) { return EvpKDF.create(cfg).compute(password, salt); }; }()); return CryptoJS.EvpKDF; })); },{"./core":22,"./hmac":27,"./sha1":46}],26:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var CipherParams = C_lib.CipherParams; var C_enc = C.enc; var Hex = C_enc.Hex; var C_format = C.format; var HexFormatter = C_format.Hex = { /** * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The hexadecimally encoded string. * * @static * * @example * * var hexString = CryptoJS.format.Hex.stringify(cipherParams); */ stringify: function (cipherParams) { return cipherParams.ciphertext.toString(Hex); }, /** * Converts a hexadecimally encoded ciphertext string to a cipher params object. * * @param {string} input The hexadecimally encoded string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.Hex.parse(hexString); */ parse: function (input) { var ciphertext = Hex.parse(input); return CipherParams.create({ ciphertext: ciphertext }); } }; }()); return CryptoJS.format.Hex; })); },{"./cipher-core":21,"./core":22}],27:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var C_algo = C.algo; /** * HMAC algorithm. */ var HMAC = C_algo.HMAC = Base.extend({ /** * Initializes a newly created HMAC. * * @param {Hasher} hasher The hash algorithm to use. * @param {WordArray|string} key The secret key. * * @example * * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); */ init: function (hasher, key) { // Init hasher hasher = this._hasher = new hasher.init(); // Convert string to WordArray, else assume WordArray already if (typeof key == 'string') { key = Utf8.parse(key); } // Shortcuts var hasherBlockSize = hasher.blockSize; var hasherBlockSizeBytes = hasherBlockSize * 4; // Allow arbitrary length keys if (key.sigBytes > hasherBlockSizeBytes) { key = hasher.finalize(key); } // Clamp excess bits key.clamp(); // Clone key for inner and outer pads var oKey = this._oKey = key.clone(); var iKey = this._iKey = key.clone(); // Shortcuts var oKeyWords = oKey.words; var iKeyWords = iKey.words; // XOR keys with pad constants for (var i = 0; i < hasherBlockSize; i++) { oKeyWords[i] ^= 0x5c5c5c5c; iKeyWords[i] ^= 0x36363636; } oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; // Set initial values this.reset(); }, /** * Resets this HMAC to its initial state. * * @example * * hmacHasher.reset(); */ reset: function () { // Shortcut var hasher = this._hasher; // Reset hasher.reset(); hasher.update(this._iKey); }, /** * Updates this HMAC with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {HMAC} This HMAC instance. * * @example * * hmacHasher.update('message'); * hmacHasher.update(wordArray); */ update: function (messageUpdate) { this._hasher.update(messageUpdate); // Chainable return this; }, /** * Finalizes the HMAC computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The HMAC. * * @example * * var hmac = hmacHasher.finalize(); * var hmac = hmacHasher.finalize('message'); * var hmac = hmacHasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Shortcut var hasher = this._hasher; // Compute HMAC var innerHash = hasher.finalize(messageUpdate); hasher.reset(); var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); return hmac; } }); }()); })); },{"./core":22}],28:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./x64-core"), require("./lib-typedarrays"), require("./enc-utf16"), require("./enc-base64"), require("./md5"), require("./sha1"), require("./sha256"), require("./sha224"), require("./sha512"), require("./sha384"), require("./sha3"), require("./ripemd160"), require("./hmac"), require("./pbkdf2"), require("./evpkdf"), require("./cipher-core"), require("./mode-cfb"), require("./mode-ctr"), require("./mode-ctr-gladman"), require("./mode-ofb"), require("./mode-ecb"), require("./pad-ansix923"), require("./pad-iso10126"), require("./pad-iso97971"), require("./pad-zeropadding"), require("./pad-nopadding"), require("./format-hex"), require("./aes"), require("./tripledes"), require("./rc4"), require("./rabbit"), require("./rabbit-legacy")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { return CryptoJS; })); },{"./aes":20,"./cipher-core":21,"./core":22,"./enc-base64":23,"./enc-utf16":24,"./evpkdf":25,"./format-hex":26,"./hmac":27,"./lib-typedarrays":29,"./md5":30,"./mode-cfb":31,"./mode-ctr":33,"./mode-ctr-gladman":32,"./mode-ecb":34,"./mode-ofb":35,"./pad-ansix923":36,"./pad-iso10126":37,"./pad-iso97971":38,"./pad-nopadding":39,"./pad-zeropadding":40,"./pbkdf2":41,"./rabbit":43,"./rabbit-legacy":42,"./rc4":44,"./ripemd160":45,"./sha1":46,"./sha224":47,"./sha256":48,"./sha3":49,"./sha384":50,"./sha512":51,"./tripledes":52,"./x64-core":53}],29:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Check if typed arrays are supported if (typeof ArrayBuffer != 'function') { return; } // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; // Reference original init var superInit = WordArray.init; // Augment WordArray.init to handle typed arrays var subInit = WordArray.init = function (typedArray) { // Convert buffers to uint8 if (typedArray instanceof ArrayBuffer) { typedArray = new Uint8Array(typedArray); } // Convert other array views to uint8 if ( typedArray instanceof Int8Array || typedArray instanceof Uint8ClampedArray || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array ) { typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); } // Handle Uint8Array if (typedArray instanceof Uint8Array) { // Shortcut var typedArrayByteLength = typedArray.byteLength; // Extract bytes var words = []; for (var i = 0; i < typedArrayByteLength; i++) { words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); } // Initialize this word array superInit.call(this, words, typedArrayByteLength); } else { // Else call normal init superInit.apply(this, arguments); } }; subInit.prototype = WordArray; }()); return CryptoJS.lib.WordArray; })); },{"./core":22}],30:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var T = []; // Compute constants (function () { for (var i = 0; i < 64; i++) { T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; } }()); /** * MD5 hash algorithm. */ var MD5 = C_algo.MD5 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 ]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcuts var H = this._hash.words; var M_offset_0 = M[offset + 0]; var M_offset_1 = M[offset + 1]; var M_offset_2 = M[offset + 2]; var M_offset_3 = M[offset + 3]; var M_offset_4 = M[offset + 4]; var M_offset_5 = M[offset + 5]; var M_offset_6 = M[offset + 6]; var M_offset_7 = M[offset + 7]; var M_offset_8 = M[offset + 8]; var M_offset_9 = M[offset + 9]; var M_offset_10 = M[offset + 10]; var M_offset_11 = M[offset + 11]; var M_offset_12 = M[offset + 12]; var M_offset_13 = M[offset + 13]; var M_offset_14 = M[offset + 14]; var M_offset_15 = M[offset + 15]; // Working varialbes var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; // Computation a = FF(a, b, c, d, M_offset_0, 7, T[0]); d = FF(d, a, b, c, M_offset_1, 12, T[1]); c = FF(c, d, a, b, M_offset_2, 17, T[2]); b = FF(b, c, d, a, M_offset_3, 22, T[3]); a = FF(a, b, c, d, M_offset_4, 7, T[4]); d = FF(d, a, b, c, M_offset_5, 12, T[5]); c = FF(c, d, a, b, M_offset_6, 17, T[6]); b = FF(b, c, d, a, M_offset_7, 22, T[7]); a = FF(a, b, c, d, M_offset_8, 7, T[8]); d = FF(d, a, b, c, M_offset_9, 12, T[9]); c = FF(c, d, a, b, M_offset_10, 17, T[10]); b = FF(b, c, d, a, M_offset_11, 22, T[11]); a = FF(a, b, c, d, M_offset_12, 7, T[12]); d = FF(d, a, b, c, M_offset_13, 12, T[13]); c = FF(c, d, a, b, M_offset_14, 17, T[14]); b = FF(b, c, d, a, M_offset_15, 22, T[15]); a = GG(a, b, c, d, M_offset_1, 5, T[16]); d = GG(d, a, b, c, M_offset_6, 9, T[17]); c = GG(c, d, a, b, M_offset_11, 14, T[18]); b = GG(b, c, d, a, M_offset_0, 20, T[19]); a = GG(a, b, c, d, M_offset_5, 5, T[20]); d = GG(d, a, b, c, M_offset_10, 9, T[21]); c = GG(c, d, a, b, M_offset_15, 14, T[22]); b = GG(b, c, d, a, M_offset_4, 20, T[23]); a = GG(a, b, c, d, M_offset_9, 5, T[24]); d = GG(d, a, b, c, M_offset_14, 9, T[25]); c = GG(c, d, a, b, M_offset_3, 14, T[26]); b = GG(b, c, d, a, M_offset_8, 20, T[27]); a = GG(a, b, c, d, M_offset_13, 5, T[28]); d = GG(d, a, b, c, M_offset_2, 9, T[29]); c = GG(c, d, a, b, M_offset_7, 14, T[30]); b = GG(b, c, d, a, M_offset_12, 20, T[31]); a = HH(a, b, c, d, M_offset_5, 4, T[32]); d = HH(d, a, b, c, M_offset_8, 11, T[33]); c = HH(c, d, a, b, M_offset_11, 16, T[34]); b = HH(b, c, d, a, M_offset_14, 23, T[35]); a = HH(a, b, c, d, M_offset_1, 4, T[36]); d = HH(d, a, b, c, M_offset_4, 11, T[37]); c = HH(c, d, a, b, M_offset_7, 16, T[38]); b = HH(b, c, d, a, M_offset_10, 23, T[39]); a = HH(a, b, c, d, M_offset_13, 4, T[40]); d = HH(d, a, b, c, M_offset_0, 11, T[41]); c = HH(c, d, a, b, M_offset_3, 16, T[42]); b = HH(b, c, d, a, M_offset_6, 23, T[43]); a = HH(a, b, c, d, M_offset_9, 4, T[44]); d = HH(d, a, b, c, M_offset_12, 11, T[45]); c = HH(c, d, a, b, M_offset_15, 16, T[46]); b = HH(b, c, d, a, M_offset_2, 23, T[47]); a = II(a, b, c, d, M_offset_0, 6, T[48]); d = II(d, a, b, c, M_offset_7, 10, T[49]); c = II(c, d, a, b, M_offset_14, 15, T[50]); b = II(b, c, d, a, M_offset_5, 21, T[51]); a = II(a, b, c, d, M_offset_12, 6, T[52]); d = II(d, a, b, c, M_offset_3, 10, T[53]); c = II(c, d, a, b, M_offset_10, 15, T[54]); b = II(b, c, d, a, M_offset_1, 21, T[55]); a = II(a, b, c, d, M_offset_8, 6, T[56]); d = II(d, a, b, c, M_offset_15, 10, T[57]); c = II(c, d, a, b, M_offset_6, 15, T[58]); b = II(b, c, d, a, M_offset_13, 21, T[59]); a = II(a, b, c, d, M_offset_4, 6, T[60]); d = II(d, a, b, c, M_offset_11, 10, T[61]); c = II(c, d, a, b, M_offset_2, 15, T[62]); b = II(b, c, d, a, M_offset_9, 21, T[63]); // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); var nBitsTotalL = nBitsTotal; dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) ); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 4; i++) { // Shortcut var H_i = H[i]; H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function FF(a, b, c, d, x, s, t) { var n = a + ((b & c) | (~b & d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function GG(a, b, c, d, x, s, t) { var n = a + ((b & d) | (c & ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function HH(a, b, c, d, x, s, t) { var n = a + (b ^ c ^ d) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function II(a, b, c, d, x, s, t) { var n = a + (c ^ (b | ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.MD5('message'); * var hash = CryptoJS.MD5(wordArray); */ C.MD5 = Hasher._createHelper(MD5); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacMD5(message, key); */ C.HmacMD5 = Hasher._createHmacHelper(MD5); }(Math)); return CryptoJS.MD5; })); },{"./core":22}],31:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher Feedback block mode. */ CryptoJS.mode.CFB = (function () { var CFB = CryptoJS.lib.BlockCipherMode.extend(); CFB.Encryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); CFB.Decryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // This block becomes the previous block this._prevBlock = thisBlock; } }); function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { // Shortcut var iv = this._iv; // Generate keystream if (iv) { var keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } else { var keystream = this._prevBlock; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } return CFB; }()); return CryptoJS.mode.CFB; })); },{"./cipher-core":21,"./core":22}],32:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve * Counter block mode compatible with Dr Brian Gladman fileenc.c * derived from CryptoJS.mode.CTR * Jan Hruby [email protected] */ CryptoJS.mode.CTRGladman = (function () { var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); function incWord(word) { if (((word >> 24) & 0xff) === 0xff) { //overflow var b1 = (word >> 16)&0xff; var b2 = (word >> 8)&0xff; var b3 = word & 0xff; if (b1 === 0xff) // overflow b1 { b1 = 0; if (b2 === 0xff) { b2 = 0; if (b3 === 0xff) { b3 = 0; } else { ++b3; } } else { ++b2; } } else { ++b1; } word = 0; word += (b1 << 16); word += (b2 << 8); word += b3; } else { word += (0x01 << 24); } return word; } function incCounter(counter) { if ((counter[0] = incWord(counter[0])) === 0) { // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 counter[1] = incWord(counter[1]); } return counter; } var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } incCounter(counter); var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTRGladman.Decryptor = Encryptor; return CTRGladman; }()); return CryptoJS.mode.CTRGladman; })); },{"./cipher-core":21,"./core":22}],33:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Counter block mode. */ CryptoJS.mode.CTR = (function () { var CTR = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = CTR.Encryptor = CTR.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Increment counter counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTR.Decryptor = Encryptor; return CTR; }()); return CryptoJS.mode.CTR; })); },{"./cipher-core":21,"./core":22}],34:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Electronic Codebook block mode. */ CryptoJS.mode.ECB = (function () { var ECB = CryptoJS.lib.BlockCipherMode.extend(); ECB.Encryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.encryptBlock(words, offset); } }); ECB.Decryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.decryptBlock(words, offset); } }); return ECB; }()); return CryptoJS.mode.ECB; })); },{"./cipher-core":21,"./core":22}],35:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Output Feedback block mode. */ CryptoJS.mode.OFB = (function () { var OFB = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = OFB.Encryptor = OFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var keystream = this._keystream; // Generate keystream if (iv) { keystream = this._keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); OFB.Decryptor = Encryptor; return OFB; }()); return CryptoJS.mode.OFB; })); },{"./cipher-core":21,"./core":22}],36:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ANSI X.923 padding strategy. */ CryptoJS.pad.AnsiX923 = { pad: function (data, blockSize) { // Shortcuts var dataSigBytes = data.sigBytes; var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; // Compute last byte position var lastBytePos = dataSigBytes + nPaddingBytes - 1; // Pad data.clamp(); data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); data.sigBytes += nPaddingBytes; }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Ansix923; })); },{"./cipher-core":21,"./core":22}],37:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO 10126 padding strategy. */ CryptoJS.pad.Iso10126 = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Pad data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Iso10126; })); },{"./cipher-core":21,"./core":22}],38:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO/IEC 9797-1 Padding Method 2. */ CryptoJS.pad.Iso97971 = { pad: function (data, blockSize) { // Add 0x80 byte data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); // Zero pad the rest CryptoJS.pad.ZeroPadding.pad(data, blockSize); }, unpad: function (data) { // Remove zero padding CryptoJS.pad.ZeroPadding.unpad(data); // Remove one more byte -- the 0x80 byte data.sigBytes--; } }; return CryptoJS.pad.Iso97971; })); },{"./cipher-core":21,"./core":22}],39:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * A noop padding strategy. */ CryptoJS.pad.NoPadding = { pad: function () { }, unpad: function () { } }; return CryptoJS.pad.NoPadding; })); },{"./cipher-core":21,"./core":22}],40:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Zero padding strategy. */ CryptoJS.pad.ZeroPadding = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Pad data.clamp(); data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); }, unpad: function (data) { // Shortcut var dataWords = data.words; // Unpad var i = data.sigBytes - 1; while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { i--; } data.sigBytes = i + 1; } }; return CryptoJS.pad.ZeroPadding; })); },{"./cipher-core":21,"./core":22}],41:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA1 = C_algo.SHA1; var HMAC = C_algo.HMAC; /** * Password-Based Key Derivation Function 2 algorithm. */ var PBKDF2 = C_algo.PBKDF2 = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hasher to use. Default: SHA1 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: SHA1, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.PBKDF2.create(); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init HMAC var hmac = HMAC.create(cfg.hasher, password); // Initial values var derivedKey = WordArray.create(); var blockIndex = WordArray.create([0x00000001]); // Shortcuts var derivedKeyWords = derivedKey.words; var blockIndexWords = blockIndex.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { var block = hmac.update(salt).finalize(blockIndex); hmac.reset(); // Shortcuts var blockWords = block.words; var blockWordsLength = blockWords.length; // Iterations var intermediate = block; for (var i = 1; i < iterations; i++) { intermediate = hmac.finalize(intermediate); hmac.reset(); // Shortcut var intermediateWords = intermediate.words; // XOR intermediate with block for (var j = 0; j < blockWordsLength; j++) { blockWords[j] ^= intermediateWords[j]; } } derivedKey.concat(block); blockIndexWords[0]++; } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.PBKDF2(password, salt); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); */ C.PBKDF2 = function (password, salt, cfg) { return PBKDF2.create(cfg).compute(password, salt); }; }()); return CryptoJS.PBKDF2; })); },{"./core":22,"./hmac":27,"./sha1":46}],42:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm. * * This is a legacy version that neglected to convert the key to little-endian. * This error doesn't affect the cipher's security, * but it does affect its compatibility with other implementations. */ var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); */ C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); }()); return CryptoJS.RabbitLegacy; })); },{"./cipher-core":21,"./core":22,"./enc-base64":23,"./evpkdf":25,"./md5":30}],43:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm */ var Rabbit = C_algo.Rabbit = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Swap endian for (var i = 0; i < 4; i++) { K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); } // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); */ C.Rabbit = StreamCipher._createHelper(Rabbit); }()); return CryptoJS.Rabbit; })); },{"./cipher-core":21,"./core":22,"./enc-base64":23,"./evpkdf":25,"./md5":30}],44:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; /** * RC4 stream cipher algorithm. */ var RC4 = C_algo.RC4 = StreamCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySigBytes = key.sigBytes; // Init sbox var S = this._S = []; for (var i = 0; i < 256; i++) { S[i] = i; } // Key setup for (var i = 0, j = 0; i < 256; i++) { var keyByteIndex = i % keySigBytes; var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; j = (j + S[i] + keyByte) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; } // Counters this._i = this._j = 0; }, _doProcessBlock: function (M, offset) { M[offset] ^= generateKeystreamWord.call(this); }, keySize: 256/32, ivSize: 0 }); function generateKeystreamWord() { // Shortcuts var S = this._S; var i = this._i; var j = this._j; // Generate keystream word var keystreamWord = 0; for (var n = 0; n < 4; n++) { i = (i + 1) % 256; j = (j + S[i]) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); } // Update counters this._i = i; this._j = j; return keystreamWord; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); */ C.RC4 = StreamCipher._createHelper(RC4); /** * Modified RC4 stream cipher algorithm. */ var RC4Drop = C_algo.RC4Drop = RC4.extend({ /** * Configuration options. * * @property {number} drop The number of keystream words to drop. Default 192 */ cfg: RC4.cfg.extend({ drop: 192 }), _doReset: function () { RC4._doReset.call(this); // Drop for (var i = this.cfg.drop; i > 0; i--) { generateKeystreamWord.call(this); } } }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); */ C.RC4Drop = StreamCipher._createHelper(RC4Drop); }()); return CryptoJS.RC4; })); },{"./cipher-core":21,"./core":22,"./enc-base64":23,"./evpkdf":25,"./md5":30}],45:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve (c) 2012 by Cédric Mesnil. 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var _zl = WordArray.create([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]); var _zr = WordArray.create([ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]); var _sl = WordArray.create([ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]); var _sr = WordArray.create([ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]); var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); /** * RIPEMD160 hash algorithm. */ var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ _doReset: function () { this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; // Swap M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcut var H = this._hash.words; var hl = _hl.words; var hr = _hr.words; var zl = _zl.words; var zr = _zr.words; var sl = _sl.words; var sr = _sr.words; // Working variables var al, bl, cl, dl, el; var ar, br, cr, dr, er; ar = al = H[0]; br = bl = H[1]; cr = cl = H[2]; dr = dl = H[3]; er = el = H[4]; // Computation var t; for (var i = 0; i < 80; i += 1) { t = (al + M[offset+zl[i]])|0; if (i<16){ t += f1(bl,cl,dl) + hl[0]; } else if (i<32) { t += f2(bl,cl,dl) + hl[1]; } else if (i<48) { t += f3(bl,cl,dl) + hl[2]; } else if (i<64) { t += f4(bl,cl,dl) + hl[3]; } else {// if (i<80) { t += f5(bl,cl,dl) + hl[4]; } t = t|0; t = rotl(t,sl[i]); t = (t+el)|0; al = el; el = dl; dl = rotl(cl, 10); cl = bl; bl = t; t = (ar + M[offset+zr[i]])|0; if (i<16){ t += f5(br,cr,dr) + hr[0]; } else if (i<32) { t += f4(br,cr,dr) + hr[1]; } else if (i<48) { t += f3(br,cr,dr) + hr[2]; } else if (i<64) { t += f2(br,cr,dr) + hr[3]; } else {// if (i<80) { t += f1(br,cr,dr) + hr[4]; } t = t|0; t = rotl(t,sr[i]) ; t = (t+er)|0; ar = er; er = dr; dr = rotl(cr, 10); cr = br; br = t; } // Intermediate hash value t = (H[1] + cl + dr)|0; H[1] = (H[2] + dl + er)|0; H[2] = (H[3] + el + ar)|0; H[3] = (H[4] + al + br)|0; H[4] = (H[0] + bl + cr)|0; H[0] = t; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 5; i++) { // Shortcut var H_i = H[i]; // Swap H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function f1(x, y, z) { return ((x) ^ (y) ^ (z)); } function f2(x, y, z) { return (((x)&(y)) | ((~x)&(z))); } function f3(x, y, z) { return (((x) | (~(y))) ^ (z)); } function f4(x, y, z) { return (((x) & (z)) | ((y)&(~(z)))); } function f5(x, y, z) { return ((x) ^ ((y) |(~(z)))); } function rotl(x,n) { return (x<<n) | (x>>>(32-n)); } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.RIPEMD160('message'); * var hash = CryptoJS.RIPEMD160(wordArray); */ C.RIPEMD160 = Hasher._createHelper(RIPEMD160); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacRIPEMD160(message, key); */ C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); }(Math)); return CryptoJS.RIPEMD160; })); },{"./core":22}],46:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Reusable object var W = []; /** * SHA-1 hash algorithm. */ var SHA1 = C_algo.SHA1 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; // Computation for (var i = 0; i < 80; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; W[i] = (n << 1) | (n >>> 31); } var t = ((a << 5) | (a >>> 27)) + e + W[i]; if (i < 20) { t += ((b & c) | (~b & d)) + 0x5a827999; } else if (i < 40) { t += (b ^ c ^ d) + 0x6ed9eba1; } else if (i < 60) { t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; } else /* if (i < 80) */ { t += (b ^ c ^ d) - 0x359d3e2a; } e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA1('message'); * var hash = CryptoJS.SHA1(wordArray); */ C.SHA1 = Hasher._createHelper(SHA1); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA1(message, key); */ C.HmacSHA1 = Hasher._createHmacHelper(SHA1); }()); return CryptoJS.SHA1; })); },{"./core":22}],47:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./sha256")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha256"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA256 = C_algo.SHA256; /** * SHA-224 hash algorithm. */ var SHA224 = C_algo.SHA224 = SHA256.extend({ _doReset: function () { this._hash = new WordArray.init([ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]); }, _doFinalize: function () { var hash = SHA256._doFinalize.call(this); hash.sigBytes -= 4; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA224('message'); * var hash = CryptoJS.SHA224(wordArray); */ C.SHA224 = SHA256._createHelper(SHA224); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA224(message, key); */ C.HmacSHA224 = SHA256._createHmacHelper(SHA224); }()); return CryptoJS.SHA224; })); },{"./core":22,"./sha256":48}],48:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Initialization and round constants tables var H = []; var K = []; // Compute constants (function () { function isPrime(n) { var sqrtN = Math.sqrt(n); for (var factor = 2; factor <= sqrtN; factor++) { if (!(n % factor)) { return false; } } return true; } function getFractionalBits(n) { return ((n - (n | 0)) * 0x100000000) | 0; } var n = 2; var nPrime = 0; while (nPrime < 64) { if (isPrime(n)) { if (nPrime < 8) { H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); } K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); nPrime++; } n++; } }()); // Reusable object var W = []; /** * SHA-256 hash algorithm. */ var SHA256 = C_algo.SHA256 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init(H.slice(0)); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; var f = H[5]; var g = H[6]; var h = H[7]; // Computation for (var i = 0; i < 64; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var gamma0x = W[i - 15]; var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ ((gamma0x << 14) | (gamma0x >>> 18)) ^ (gamma0x >>> 3); var gamma1x = W[i - 2]; var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ ((gamma1x << 13) | (gamma1x >>> 19)) ^ (gamma1x >>> 10); W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; } var ch = (e & f) ^ (~e & g); var maj = (a & b) ^ (a & c) ^ (b & c); var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); var t1 = h + sigma1 + ch + K[i] + W[i]; var t2 = sigma0 + maj; h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA256('message'); * var hash = CryptoJS.SHA256(wordArray); */ C.SHA256 = Hasher._createHelper(SHA256); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA256(message, key); */ C.HmacSHA256 = Hasher._createHmacHelper(SHA256); }(Math)); return CryptoJS.SHA256; })); },{"./core":22}],49:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var C_algo = C.algo; // Constants tables var RHO_OFFSETS = []; var PI_INDEXES = []; var ROUND_CONSTANTS = []; // Compute Constants (function () { // Compute rho offset constants var x = 1, y = 0; for (var t = 0; t < 24; t++) { RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; var newX = y % 5; var newY = (2 * x + 3 * y) % 5; x = newX; y = newY; } // Compute pi index constants for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; } } // Compute round constants var LFSR = 0x01; for (var i = 0; i < 24; i++) { var roundConstantMsw = 0; var roundConstantLsw = 0; for (var j = 0; j < 7; j++) { if (LFSR & 0x01) { var bitPosition = (1 << j) - 1; if (bitPosition < 32) { roundConstantLsw ^= 1 << bitPosition; } else /* if (bitPosition >= 32) */ { roundConstantMsw ^= 1 << (bitPosition - 32); } } // Compute next LFSR if (LFSR & 0x80) { // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 LFSR = (LFSR << 1) ^ 0x71; } else { LFSR <<= 1; } } ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); } }()); // Reusable objects for temporary values var T = []; (function () { for (var i = 0; i < 25; i++) { T[i] = X64Word.create(); } }()); /** * SHA-3 hash algorithm. */ var SHA3 = C_algo.SHA3 = Hasher.extend({ /** * Configuration options. * * @property {number} outputLength * The desired number of bits in the output hash. * Only values permitted are: 224, 256, 384, 512. * Default: 512 */ cfg: Hasher.cfg.extend({ outputLength: 512 }), _doReset: function () { var state = this._state = [] for (var i = 0; i < 25; i++) { state[i] = new X64Word.init(); } this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; }, _doProcessBlock: function (M, offset) { // Shortcuts var state = this._state; var nBlockSizeLanes = this.blockSize / 2; // Absorb for (var i = 0; i < nBlockSizeLanes; i++) { // Shortcuts var M2i = M[offset + 2 * i]; var M2i1 = M[offset + 2 * i + 1]; // Swap endian M2i = ( (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) ); M2i1 = ( (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) ); // Absorb message into state var lane = state[i]; lane.high ^= M2i1; lane.low ^= M2i; } // Rounds for (var round = 0; round < 24; round++) { // Theta for (var x = 0; x < 5; x++) { // Mix column lanes var tMsw = 0, tLsw = 0; for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; tMsw ^= lane.high; tLsw ^= lane.low; } // Temporary values var Tx = T[x]; Tx.high = tMsw; Tx.low = tLsw; } for (var x = 0; x < 5; x++) { // Shortcuts var Tx4 = T[(x + 4) % 5]; var Tx1 = T[(x + 1) % 5]; var Tx1Msw = Tx1.high; var Tx1Lsw = Tx1.low; // Mix surrounding columns var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; lane.high ^= tMsw; lane.low ^= tLsw; } } // Rho Pi for (var laneIndex = 1; laneIndex < 25; laneIndex++) { // Shortcuts var lane = state[laneIndex]; var laneMsw = lane.high; var laneLsw = lane.low; var rhoOffset = RHO_OFFSETS[laneIndex]; // Rotate lanes if (rhoOffset < 32) { var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); } else /* if (rhoOffset >= 32) */ { var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); } // Transpose lanes var TPiLane = T[PI_INDEXES[laneIndex]]; TPiLane.high = tMsw; TPiLane.low = tLsw; } // Rho pi at x = y = 0 var T0 = T[0]; var state0 = state[0]; T0.high = state0.high; T0.low = state0.low; // Chi for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { // Shortcuts var laneIndex = x + 5 * y; var lane = state[laneIndex]; var TLane = T[laneIndex]; var Tx1Lane = T[((x + 1) % 5) + 5 * y]; var Tx2Lane = T[((x + 2) % 5) + 5 * y]; // Mix rows lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); } } // Iota var lane = state[0]; var roundConstant = ROUND_CONSTANTS[round]; lane.high ^= roundConstant.high; lane.low ^= roundConstant.low;; } }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; var blockSizeBits = this.blockSize * 32; // Add padding dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Shortcuts var state = this._state; var outputLengthBytes = this.cfg.outputLength / 8; var outputLengthLanes = outputLengthBytes / 8; // Squeeze var hashWords = []; for (var i = 0; i < outputLengthLanes; i++) { // Shortcuts var lane = state[i]; var laneMsw = lane.high; var laneLsw = lane.low; // Swap endian laneMsw = ( (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) ); laneLsw = ( (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) ); // Squeeze state to retrieve hash hashWords.push(laneLsw); hashWords.push(laneMsw); } // Return final computed hash return new WordArray.init(hashWords, outputLengthBytes); }, clone: function () { var clone = Hasher.clone.call(this); var state = clone._state = this._state.slice(0); for (var i = 0; i < 25; i++) { state[i] = state[i].clone(); } return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA3('message'); * var hash = CryptoJS.SHA3(wordArray); */ C.SHA3 = Hasher._createHelper(SHA3); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA3(message, key); */ C.HmacSHA3 = Hasher._createHmacHelper(SHA3); }(Math)); return CryptoJS.SHA3; })); },{"./core":22,"./x64-core":53}],50:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./x64-core"), require("./sha512")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./sha512"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; var SHA512 = C_algo.SHA512; /** * SHA-384 hash algorithm. */ var SHA384 = C_algo.SHA384 = SHA512.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) ]); }, _doFinalize: function () { var hash = SHA512._doFinalize.call(this); hash.sigBytes -= 16; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA384('message'); * var hash = CryptoJS.SHA384(wordArray); */ C.SHA384 = SHA512._createHelper(SHA384); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA384(message, key); */ C.HmacSHA384 = SHA512._createHmacHelper(SHA384); }()); return CryptoJS.SHA384; })); },{"./core":22,"./sha512":51,"./x64-core":53}],51:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; function X64Word_create() { return X64Word.create.apply(X64Word, arguments); } // Constants var K = [ X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) ]; // Reusable objects var W = []; (function () { for (var i = 0; i < 80; i++) { W[i] = X64Word_create(); } }()); /** * SHA-512 hash algorithm. */ var SHA512 = C_algo.SHA512 = Hasher.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) ]); }, _doProcessBlock: function (M, offset) { // Shortcuts var H = this._hash.words; var H0 = H[0]; var H1 = H[1]; var H2 = H[2]; var H3 = H[3]; var H4 = H[4]; var H5 = H[5]; var H6 = H[6]; var H7 = H[7]; var H0h = H0.high; var H0l = H0.low; var H1h = H1.high; var H1l = H1.low; var H2h = H2.high; var H2l = H2.low; var H3h = H3.high; var H3l = H3.low; var H4h = H4.high; var H4l = H4.low; var H5h = H5.high; var H5l = H5.low; var H6h = H6.high; var H6l = H6.low; var H7h = H7.high; var H7l = H7.low; // Working variables var ah = H0h; var al = H0l; var bh = H1h; var bl = H1l; var ch = H2h; var cl = H2l; var dh = H3h; var dl = H3l; var eh = H4h; var el = H4l; var fh = H5h; var fl = H5l; var gh = H6h; var gl = H6l; var hh = H7h; var hl = H7l; // Rounds for (var i = 0; i < 80; i++) { // Shortcut var Wi = W[i]; // Extend message if (i < 16) { var Wih = Wi.high = M[offset + i * 2] | 0; var Wil = Wi.low = M[offset + i * 2 + 1] | 0; } else { // Gamma0 var gamma0x = W[i - 15]; var gamma0xh = gamma0x.high; var gamma0xl = gamma0x.low; var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); // Gamma1 var gamma1x = W[i - 2]; var gamma1xh = gamma1x.high; var gamma1xl = gamma1x.low; var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] var Wi7 = W[i - 7]; var Wi7h = Wi7.high; var Wi7l = Wi7.low; var Wi16 = W[i - 16]; var Wi16h = Wi16.high; var Wi16l = Wi16.low; var Wil = gamma0l + Wi7l; var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); var Wil = Wil + gamma1l; var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); var Wil = Wil + Wi16l; var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); Wi.high = Wih; Wi.low = Wil; } var chh = (eh & fh) ^ (~eh & gh); var chl = (el & fl) ^ (~el & gl); var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); var majl = (al & bl) ^ (al & cl) ^ (bl & cl); var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); // t1 = h + sigma1 + ch + K[i] + W[i] var Ki = K[i]; var Kih = Ki.high; var Kil = Ki.low; var t1l = hl + sigma1l; var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); var t1l = t1l + chl; var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); var t1l = t1l + Kil; var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); var t1l = t1l + Wil; var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); // t2 = sigma0 + maj var t2l = sigma0l + majl; var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); // Update working variables hh = gh; hl = gl; gh = fh; gl = fl; fh = eh; fl = el; el = (dl + t1l) | 0; eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; dh = ch; dl = cl; ch = bh; cl = bl; bh = ah; bl = al; al = (t1l + t2l) | 0; ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; } // Intermediate hash value H0l = H0.low = (H0l + al); H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); H1l = H1.low = (H1l + bl); H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); H2l = H2.low = (H2l + cl); H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); H3l = H3.low = (H3l + dl); H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); H4l = H4.low = (H4l + el); H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); H5l = H5.low = (H5l + fl); H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); H6l = H6.low = (H6l + gl); H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); H7l = H7.low = (H7l + hl); H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Convert hash to 32-bit word array before returning var hash = this._hash.toX32(); // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; }, blockSize: 1024/32 }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA512('message'); * var hash = CryptoJS.SHA512(wordArray); */ C.SHA512 = Hasher._createHelper(SHA512); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA512(message, key); */ C.HmacSHA512 = Hasher._createHmacHelper(SHA512); }()); return CryptoJS.SHA512; })); },{"./core":22,"./x64-core":53}],52:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Permuted Choice 1 constants var PC1 = [ 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 ]; // Permuted Choice 2 constants var PC2 = [ 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 ]; // Cumulative bit shift constants var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; // SBOXes and round permutation constants var SBOX_P = [ { 0x0: 0x808200, 0x10000000: 0x8000, 0x20000000: 0x808002, 0x30000000: 0x2, 0x40000000: 0x200, 0x50000000: 0x808202, 0x60000000: 0x800202, 0x70000000: 0x800000, 0x80000000: 0x202, 0x90000000: 0x800200, 0xa0000000: 0x8200, 0xb0000000: 0x808000, 0xc0000000: 0x8002, 0xd0000000: 0x800002, 0xe0000000: 0x0, 0xf0000000: 0x8202, 0x8000000: 0x0, 0x18000000: 0x808202, 0x28000000: 0x8202, 0x38000000: 0x8000, 0x48000000: 0x808200, 0x58000000: 0x200, 0x68000000: 0x808002, 0x78000000: 0x2, 0x88000000: 0x800200, 0x98000000: 0x8200, 0xa8000000: 0x808000, 0xb8000000: 0x800202, 0xc8000000: 0x800002, 0xd8000000: 0x8002, 0xe8000000: 0x202, 0xf8000000: 0x800000, 0x1: 0x8000, 0x10000001: 0x2, 0x20000001: 0x808200, 0x30000001: 0x800000, 0x40000001: 0x808002, 0x50000001: 0x8200, 0x60000001: 0x200, 0x70000001: 0x800202, 0x80000001: 0x808202, 0x90000001: 0x808000, 0xa0000001: 0x800002, 0xb0000001: 0x8202, 0xc0000001: 0x202, 0xd0000001: 0x800200, 0xe0000001: 0x8002, 0xf0000001: 0x0, 0x8000001: 0x808202, 0x18000001: 0x808000, 0x28000001: 0x800000, 0x38000001: 0x200, 0x48000001: 0x8000, 0x58000001: 0x800002, 0x68000001: 0x2, 0x78000001: 0x8202, 0x88000001: 0x8002, 0x98000001: 0x800202, 0xa8000001: 0x202, 0xb8000001: 0x808200, 0xc8000001: 0x800200, 0xd8000001: 0x0, 0xe8000001: 0x8200, 0xf8000001: 0x808002 }, { 0x0: 0x40084010, 0x1000000: 0x4000, 0x2000000: 0x80000, 0x3000000: 0x40080010, 0x4000000: 0x40000010, 0x5000000: 0x40084000, 0x6000000: 0x40004000, 0x7000000: 0x10, 0x8000000: 0x84000, 0x9000000: 0x40004010, 0xa000000: 0x40000000, 0xb000000: 0x84010, 0xc000000: 0x80010, 0xd000000: 0x0, 0xe000000: 0x4010, 0xf000000: 0x40080000, 0x800000: 0x40004000, 0x1800000: 0x84010, 0x2800000: 0x10, 0x3800000: 0x40004010, 0x4800000: 0x40084010, 0x5800000: 0x40000000, 0x6800000: 0x80000, 0x7800000: 0x40080010, 0x8800000: 0x80010, 0x9800000: 0x0, 0xa800000: 0x4000, 0xb800000: 0x40080000, 0xc800000: 0x40000010, 0xd800000: 0x84000, 0xe800000: 0x40084000, 0xf800000: 0x4010, 0x10000000: 0x0, 0x11000000: 0x40080010, 0x12000000: 0x40004010, 0x13000000: 0x40084000, 0x14000000: 0x40080000, 0x15000000: 0x10, 0x16000000: 0x84010, 0x17000000: 0x4000, 0x18000000: 0x4010, 0x19000000: 0x80000, 0x1a000000: 0x80010, 0x1b000000: 0x40000010, 0x1c000000: 0x84000, 0x1d000000: 0x40004000, 0x1e000000: 0x40000000, 0x1f000000: 0x40084010, 0x10800000: 0x84010, 0x11800000: 0x80000, 0x12800000: 0x40080000, 0x13800000: 0x4000, 0x14800000: 0x40004000, 0x15800000: 0x40084010, 0x16800000: 0x10, 0x17800000: 0x40000000, 0x18800000: 0x40084000, 0x19800000: 0x40000010, 0x1a800000: 0x40004010, 0x1b800000: 0x80010, 0x1c800000: 0x0, 0x1d800000: 0x4010, 0x1e800000: 0x40080010, 0x1f800000: 0x84000 }, { 0x0: 0x104, 0x100000: 0x0, 0x200000: 0x4000100, 0x300000: 0x10104, 0x400000: 0x10004, 0x500000: 0x4000004, 0x600000: 0x4010104, 0x700000: 0x4010000, 0x800000: 0x4000000, 0x900000: 0x4010100, 0xa00000: 0x10100, 0xb00000: 0x4010004, 0xc00000: 0x4000104, 0xd00000: 0x10000, 0xe00000: 0x4, 0xf00000: 0x100, 0x80000: 0x4010100, 0x180000: 0x4010004, 0x280000: 0x0, 0x380000: 0x4000100, 0x480000: 0x4000004, 0x580000: 0x10000, 0x680000: 0x10004, 0x780000: 0x104, 0x880000: 0x4, 0x980000: 0x100, 0xa80000: 0x4010000, 0xb80000: 0x10104, 0xc80000: 0x10100, 0xd80000: 0x4000104, 0xe80000: 0x4010104, 0xf80000: 0x4000000, 0x1000000: 0x4010100, 0x1100000: 0x10004, 0x1200000: 0x10000, 0x1300000: 0x4000100, 0x1400000: 0x100, 0x1500000: 0x4010104, 0x1600000: 0x4000004, 0x1700000: 0x0, 0x1800000: 0x4000104, 0x1900000: 0x4000000, 0x1a00000: 0x4, 0x1b00000: 0x10100, 0x1c00000: 0x4010000, 0x1d00000: 0x104, 0x1e00000: 0x10104, 0x1f00000: 0x4010004, 0x1080000: 0x4000000, 0x1180000: 0x104, 0x1280000: 0x4010100, 0x1380000: 0x0, 0x1480000: 0x10004, 0x1580000: 0x4000100, 0x1680000: 0x100, 0x1780000: 0x4010004, 0x1880000: 0x10000, 0x1980000: 0x4010104, 0x1a80000: 0x10104, 0x1b80000: 0x4000004, 0x1c80000: 0x4000104, 0x1d80000: 0x4010000, 0x1e80000: 0x4, 0x1f80000: 0x10100 }, { 0x0: 0x80401000, 0x10000: 0x80001040, 0x20000: 0x401040, 0x30000: 0x80400000, 0x40000: 0x0, 0x50000: 0x401000, 0x60000: 0x80000040, 0x70000: 0x400040, 0x80000: 0x80000000, 0x90000: 0x400000, 0xa0000: 0x40, 0xb0000: 0x80001000, 0xc0000: 0x80400040, 0xd0000: 0x1040, 0xe0000: 0x1000, 0xf0000: 0x80401040, 0x8000: 0x80001040, 0x18000: 0x40, 0x28000: 0x80400040, 0x38000: 0x80001000, 0x48000: 0x401000, 0x58000: 0x80401040, 0x68000: 0x0, 0x78000: 0x80400000, 0x88000: 0x1000, 0x98000: 0x80401000, 0xa8000: 0x400000, 0xb8000: 0x1040, 0xc8000: 0x80000000, 0xd8000: 0x400040, 0xe8000: 0x401040, 0xf8000: 0x80000040, 0x100000: 0x400040, 0x110000: 0x401000, 0x120000: 0x80000040, 0x130000: 0x0, 0x140000: 0x1040, 0x150000: 0x80400040, 0x160000: 0x80401000, 0x170000: 0x80001040, 0x180000: 0x80401040, 0x190000: 0x80000000, 0x1a0000: 0x80400000, 0x1b0000: 0x401040, 0x1c0000: 0x80001000, 0x1d0000: 0x400000, 0x1e0000: 0x40, 0x1f0000: 0x1000, 0x108000: 0x80400000, 0x118000: 0x80401040, 0x128000: 0x0, 0x138000: 0x401000, 0x148000: 0x400040, 0x158000: 0x80000000, 0x168000: 0x80001040, 0x178000: 0x40, 0x188000: 0x80000040, 0x198000: 0x1000, 0x1a8000: 0x80001000, 0x1b8000: 0x80400040, 0x1c8000: 0x1040, 0x1d8000: 0x80401000, 0x1e8000: 0x400000, 0x1f8000: 0x401040 }, { 0x0: 0x80, 0x1000: 0x1040000, 0x2000: 0x40000, 0x3000: 0x20000000, 0x4000: 0x20040080, 0x5000: 0x1000080, 0x6000: 0x21000080, 0x7000: 0x40080, 0x8000: 0x1000000, 0x9000: 0x20040000, 0xa000: 0x20000080, 0xb000: 0x21040080, 0xc000: 0x21040000, 0xd000: 0x0, 0xe000: 0x1040080, 0xf000: 0x21000000, 0x800: 0x1040080, 0x1800: 0x21000080, 0x2800: 0x80, 0x3800: 0x1040000, 0x4800: 0x40000, 0x5800: 0x20040080, 0x6800: 0x21040000, 0x7800: 0x20000000, 0x8800: 0x20040000, 0x9800: 0x0, 0xa800: 0x21040080, 0xb800: 0x1000080, 0xc800: 0x20000080, 0xd800: 0x21000000, 0xe800: 0x1000000, 0xf800: 0x40080, 0x10000: 0x40000, 0x11000: 0x80, 0x12000: 0x20000000, 0x13000: 0x21000080, 0x14000: 0x1000080, 0x15000: 0x21040000, 0x16000: 0x20040080, 0x17000: 0x1000000, 0x18000: 0x21040080, 0x19000: 0x21000000, 0x1a000: 0x1040000, 0x1b000: 0x20040000, 0x1c000: 0x40080, 0x1d000: 0x20000080, 0x1e000: 0x0, 0x1f000: 0x1040080, 0x10800: 0x21000080, 0x11800: 0x1000000, 0x12800: 0x1040000, 0x13800: 0x20040080, 0x14800: 0x20000000, 0x15800: 0x1040080, 0x16800: 0x80, 0x17800: 0x21040000, 0x18800: 0x40080, 0x19800: 0x21040080, 0x1a800: 0x0, 0x1b800: 0x21000000, 0x1c800: 0x1000080, 0x1d800: 0x40000, 0x1e800: 0x20040000, 0x1f800: 0x20000080 }, { 0x0: 0x10000008, 0x100: 0x2000, 0x200: 0x10200000, 0x300: 0x10202008, 0x400: 0x10002000, 0x500: 0x200000, 0x600: 0x200008, 0x700: 0x10000000, 0x800: 0x0, 0x900: 0x10002008, 0xa00: 0x202000, 0xb00: 0x8, 0xc00: 0x10200008, 0xd00: 0x202008, 0xe00: 0x2008, 0xf00: 0x10202000, 0x80: 0x10200000, 0x180: 0x10202008, 0x280: 0x8, 0x380: 0x200000, 0x480: 0x202008, 0x580: 0x10000008, 0x680: 0x10002000, 0x780: 0x2008, 0x880: 0x200008, 0x980: 0x2000, 0xa80: 0x10002008, 0xb80: 0x10200008, 0xc80: 0x0, 0xd80: 0x10202000, 0xe80: 0x202000, 0xf80: 0x10000000, 0x1000: 0x10002000, 0x1100: 0x10200008, 0x1200: 0x10202008, 0x1300: 0x2008, 0x1400: 0x200000, 0x1500: 0x10000000, 0x1600: 0x10000008, 0x1700: 0x202000, 0x1800: 0x202008, 0x1900: 0x0, 0x1a00: 0x8, 0x1b00: 0x10200000, 0x1c00: 0x2000, 0x1d00: 0x10002008, 0x1e00: 0x10202000, 0x1f00: 0x200008, 0x1080: 0x8, 0x1180: 0x202000, 0x1280: 0x200000, 0x1380: 0x10000008, 0x1480: 0x10002000, 0x1580: 0x2008, 0x1680: 0x10202008, 0x1780: 0x10200000, 0x1880: 0x10202000, 0x1980: 0x10200008, 0x1a80: 0x2000, 0x1b80: 0x202008, 0x1c80: 0x200008, 0x1d80: 0x0, 0x1e80: 0x10000000, 0x1f80: 0x10002008 }, { 0x0: 0x100000, 0x10: 0x2000401, 0x20: 0x400, 0x30: 0x100401, 0x40: 0x2100401, 0x50: 0x0, 0x60: 0x1, 0x70: 0x2100001, 0x80: 0x2000400, 0x90: 0x100001, 0xa0: 0x2000001, 0xb0: 0x2100400, 0xc0: 0x2100000, 0xd0: 0x401, 0xe0: 0x100400, 0xf0: 0x2000000, 0x8: 0x2100001, 0x18: 0x0, 0x28: 0x2000401, 0x38: 0x2100400, 0x48: 0x100000, 0x58: 0x2000001, 0x68: 0x2000000, 0x78: 0x401, 0x88: 0x100401, 0x98: 0x2000400, 0xa8: 0x2100000, 0xb8: 0x100001, 0xc8: 0x400, 0xd8: 0x2100401, 0xe8: 0x1, 0xf8: 0x100400, 0x100: 0x2000000, 0x110: 0x100000, 0x120: 0x2000401, 0x130: 0x2100001, 0x140: 0x100001, 0x150: 0x2000400, 0x160: 0x2100400, 0x170: 0x100401, 0x180: 0x401, 0x190: 0x2100401, 0x1a0: 0x100400, 0x1b0: 0x1, 0x1c0: 0x0, 0x1d0: 0x2100000, 0x1e0: 0x2000001, 0x1f0: 0x400, 0x108: 0x100400, 0x118: 0x2000401, 0x128: 0x2100001, 0x138: 0x1, 0x148: 0x2000000, 0x158: 0x100000, 0x168: 0x401, 0x178: 0x2100400, 0x188: 0x2000001, 0x198: 0x2100000, 0x1a8: 0x0, 0x1b8: 0x2100401, 0x1c8: 0x100401, 0x1d8: 0x400, 0x1e8: 0x2000400, 0x1f8: 0x100001 }, { 0x0: 0x8000820, 0x1: 0x20000, 0x2: 0x8000000, 0x3: 0x20, 0x4: 0x20020, 0x5: 0x8020820, 0x6: 0x8020800, 0x7: 0x800, 0x8: 0x8020000, 0x9: 0x8000800, 0xa: 0x20800, 0xb: 0x8020020, 0xc: 0x820, 0xd: 0x0, 0xe: 0x8000020, 0xf: 0x20820, 0x80000000: 0x800, 0x80000001: 0x8020820, 0x80000002: 0x8000820, 0x80000003: 0x8000000, 0x80000004: 0x8020000, 0x80000005: 0x20800, 0x80000006: 0x20820, 0x80000007: 0x20, 0x80000008: 0x8000020, 0x80000009: 0x820, 0x8000000a: 0x20020, 0x8000000b: 0x8020800, 0x8000000c: 0x0, 0x8000000d: 0x8020020, 0x8000000e: 0x8000800, 0x8000000f: 0x20000, 0x10: 0x20820, 0x11: 0x8020800, 0x12: 0x20, 0x13: 0x800, 0x14: 0x8000800, 0x15: 0x8000020, 0x16: 0x8020020, 0x17: 0x20000, 0x18: 0x0, 0x19: 0x20020, 0x1a: 0x8020000, 0x1b: 0x8000820, 0x1c: 0x8020820, 0x1d: 0x20800, 0x1e: 0x820, 0x1f: 0x8000000, 0x80000010: 0x20000, 0x80000011: 0x800, 0x80000012: 0x8020020, 0x80000013: 0x20820, 0x80000014: 0x20, 0x80000015: 0x8020000, 0x80000016: 0x8000000, 0x80000017: 0x8000820, 0x80000018: 0x8020820, 0x80000019: 0x8000020, 0x8000001a: 0x8000800, 0x8000001b: 0x0, 0x8000001c: 0x20800, 0x8000001d: 0x820, 0x8000001e: 0x20020, 0x8000001f: 0x8020800 } ]; // Masks that select the SBOX input var SBOX_MASK = [ 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f ]; /** * DES block cipher algorithm. */ var DES = C_algo.DES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Select 56 bits according to PC1 var keyBits = []; for (var i = 0; i < 56; i++) { var keyBitPos = PC1[i] - 1; keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; } // Assemble 16 subkeys var subKeys = this._subKeys = []; for (var nSubKey = 0; nSubKey < 16; nSubKey++) { // Create subkey var subKey = subKeys[nSubKey] = []; // Shortcut var bitShift = BIT_SHIFTS[nSubKey]; // Select 48 bits according to PC2 for (var i = 0; i < 24; i++) { // Select from the left 28 key bits subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); // Select from the right 28 key bits subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); } // Since each subkey is applied to an expanded 32-bit input, // the subkey can be broken into 8 values scaled to 32-bits, // which allows the key to be used without expansion subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); for (var i = 1; i < 7; i++) { subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); } subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); } // Compute inverse subkeys var invSubKeys = this._invSubKeys = []; for (var i = 0; i < 16; i++) { invSubKeys[i] = subKeys[15 - i]; } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._subKeys); }, decryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._invSubKeys); }, _doCryptBlock: function (M, offset, subKeys) { // Get input this._lBlock = M[offset]; this._rBlock = M[offset + 1]; // Initial permutation exchangeLR.call(this, 4, 0x0f0f0f0f); exchangeLR.call(this, 16, 0x0000ffff); exchangeRL.call(this, 2, 0x33333333); exchangeRL.call(this, 8, 0x00ff00ff); exchangeLR.call(this, 1, 0x55555555); // Rounds for (var round = 0; round < 16; round++) { // Shortcuts var subKey = subKeys[round]; var lBlock = this._lBlock; var rBlock = this._rBlock; // Feistel function var f = 0; for (var i = 0; i < 8; i++) { f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; } this._lBlock = rBlock; this._rBlock = lBlock ^ f; } // Undo swap from last round var t = this._lBlock; this._lBlock = this._rBlock; this._rBlock = t; // Final permutation exchangeLR.call(this, 1, 0x55555555); exchangeRL.call(this, 8, 0x00ff00ff); exchangeRL.call(this, 2, 0x33333333); exchangeLR.call(this, 16, 0x0000ffff); exchangeLR.call(this, 4, 0x0f0f0f0f); // Set output M[offset] = this._lBlock; M[offset + 1] = this._rBlock; }, keySize: 64/32, ivSize: 64/32, blockSize: 64/32 }); // Swap bits across the left and right words function exchangeLR(offset, mask) { var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; this._rBlock ^= t; this._lBlock ^= t << offset; } function exchangeRL(offset, mask) { var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; this._lBlock ^= t; this._rBlock ^= t << offset; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); */ C.DES = BlockCipher._createHelper(DES); /** * Triple-DES block cipher algorithm. */ var TripleDES = C_algo.TripleDES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Create DES instances this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2))); this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4))); this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6))); }, encryptBlock: function (M, offset) { this._des1.encryptBlock(M, offset); this._des2.decryptBlock(M, offset); this._des3.encryptBlock(M, offset); }, decryptBlock: function (M, offset) { this._des3.decryptBlock(M, offset); this._des2.encryptBlock(M, offset); this._des1.decryptBlock(M, offset); }, keySize: 192/32, ivSize: 64/32, blockSize: 64/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); */ C.TripleDES = BlockCipher._createHelper(TripleDES); }()); return CryptoJS.TripleDES; })); },{"./cipher-core":21,"./core":22,"./enc-base64":23,"./evpkdf":25,"./md5":30}],53:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var X32WordArray = C_lib.WordArray; /** * x64 namespace. */ var C_x64 = C.x64 = {}; /** * A 64-bit word. */ var X64Word = C_x64.Word = Base.extend({ /** * Initializes a newly created 64-bit word. * * @param {number} high The high 32 bits. * @param {number} low The low 32 bits. * * @example * * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); */ init: function (high, low) { this.high = high; this.low = low; } /** * Bitwise NOTs this word. * * @return {X64Word} A new x64-Word object after negating. * * @example * * var negated = x64Word.not(); */ // not: function () { // var high = ~this.high; // var low = ~this.low; // return X64Word.create(high, low); // }, /** * Bitwise ANDs this word with the passed word. * * @param {X64Word} word The x64-Word to AND with this word. * * @return {X64Word} A new x64-Word object after ANDing. * * @example * * var anded = x64Word.and(anotherX64Word); */ // and: function (word) { // var high = this.high & word.high; // var low = this.low & word.low; // return X64Word.create(high, low); // }, /** * Bitwise ORs this word with the passed word. * * @param {X64Word} word The x64-Word to OR with this word. * * @return {X64Word} A new x64-Word object after ORing. * * @example * * var ored = x64Word.or(anotherX64Word); */ // or: function (word) { // var high = this.high | word.high; // var low = this.low | word.low; // return X64Word.create(high, low); // }, /** * Bitwise XORs this word with the passed word. * * @param {X64Word} word The x64-Word to XOR with this word. * * @return {X64Word} A new x64-Word object after XORing. * * @example * * var xored = x64Word.xor(anotherX64Word); */ // xor: function (word) { // var high = this.high ^ word.high; // var low = this.low ^ word.low; // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the left. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftL(25); */ // shiftL: function (n) { // if (n < 32) { // var high = (this.high << n) | (this.low >>> (32 - n)); // var low = this.low << n; // } else { // var high = this.low << (n - 32); // var low = 0; // } // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the right. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftR(7); */ // shiftR: function (n) { // if (n < 32) { // var low = (this.low >>> n) | (this.high << (32 - n)); // var high = this.high >>> n; // } else { // var low = this.high >>> (n - 32); // var high = 0; // } // return X64Word.create(high, low); // }, /** * Rotates this word n bits to the left. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotL(25); */ // rotL: function (n) { // return this.shiftL(n).or(this.shiftR(64 - n)); // }, /** * Rotates this word n bits to the right. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotR(7); */ // rotR: function (n) { // return this.shiftR(n).or(this.shiftL(64 - n)); // }, /** * Adds this word with the passed word. * * @param {X64Word} word The x64-Word to add with this word. * * @return {X64Word} A new x64-Word object after adding. * * @example * * var added = x64Word.add(anotherX64Word); */ // add: function (word) { // var low = (this.low + word.low) | 0; // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; // var high = (this.high + word.high + carry) | 0; // return X64Word.create(high, low); // } }); /** * An array of 64-bit words. * * @property {Array} words The array of CryptoJS.x64.Word objects. * @property {number} sigBytes The number of significant bytes in this word array. */ var X64WordArray = C_x64.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.x64.WordArray.create(); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ]); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ], 10); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 8; } }, /** * Converts this 64-bit word array to a 32-bit word array. * * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. * * @example * * var x32WordArray = x64WordArray.toX32(); */ toX32: function () { // Shortcuts var x64Words = this.words; var x64WordsLength = x64Words.length; // Convert var x32Words = []; for (var i = 0; i < x64WordsLength; i++) { var x64Word = x64Words[i]; x32Words.push(x64Word.high); x32Words.push(x64Word.low); } return X32WordArray.create(x32Words, this.sigBytes); }, /** * Creates a copy of this word array. * * @return {X64WordArray} The clone. * * @example * * var clone = x64WordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); // Clone "words" array var words = clone.words = this.words.slice(0); // Clone each X64Word object var wordsLength = words.length; for (var i = 0; i < wordsLength; i++) { words[i] = words[i].clone(); } return clone; } }); }()); return CryptoJS; })); },{"./core":22}],54:[function(require,module,exports){ /** @license MIT License (c) copyright 2013-2014 original author or authors */ /** * Collection of helper functions for wrapping and executing 'traditional' * synchronous functions in a promise interface. * * @author Brian Cavalier * @contributor Renato Zannon */ (function(define) { define(function(require) { var when = require('./when'); var attempt = when['try']; var _liftAll = require('./lib/liftAll'); var _apply = require('./lib/apply')(when.Promise); var slice = Array.prototype.slice; return { lift: lift, liftAll: liftAll, call: attempt, apply: apply, compose: compose }; /** * Takes a function and an optional array of arguments (that might be promises), * and calls the function. The return value is a promise whose resolution * depends on the value returned by the function. * @param {function} f function to be called * @param {Array} [args] array of arguments to func * @returns {Promise} promise for the return value of func */ function apply(f, args) { // slice args just in case the caller passed an Arguments instance return _apply(f, this, args == null ? [] : slice.call(args)); } /** * Takes a 'regular' function and returns a version of that function that * returns a promise instead of a plain value, and handles thrown errors by * returning a rejected promise. Also accepts a list of arguments to be * prepended to the new function, as does Function.prototype.bind. * * The resulting function is promise-aware, in the sense that it accepts * promise arguments, and waits for their resolution. * @param {Function} f function to be bound * @param {...*} [args] arguments to be prepended for the new function @deprecated * @returns {Function} a promise-returning function */ function lift(f /*, args... */) { var args = arguments.length > 1 ? slice.call(arguments, 1) : []; return function() { return _apply(f, this, args.concat(slice.call(arguments))); }; } /** * Lift all the functions/methods on src * @param {object|function} src source whose functions will be lifted * @param {function?} combine optional function for customizing the lifting * process. It is passed dst, the lifted function, and the property name of * the original function on src. * @param {(object|function)?} dst option destination host onto which to place lifted * functions. If not provided, liftAll returns a new object. * @returns {*} If dst is provided, returns dst with lifted functions as * properties. If dst not provided, returns a new object with lifted functions. */ function liftAll(src, combine, dst) { return _liftAll(lift, combine, dst, src); } /** * Composes multiple functions by piping their return values. It is * transparent to whether the functions return 'regular' values or promises: * the piped argument is always a resolved value. If one of the functions * throws or returns a rejected promise, the composed promise will be also * rejected. * * The arguments (or promises to arguments) given to the returned function (if * any), are passed directly to the first function on the 'pipeline'. * @param {Function} f the function to which the arguments will be passed * @param {...Function} [funcs] functions that will be composed, in order * @returns {Function} a promise-returning composition of the functions */ function compose(f /*, funcs... */) { var funcs = slice.call(arguments, 1); return function() { var thisArg = this; var args = slice.call(arguments); var firstPromise = attempt.apply(thisArg, [f].concat(args)); return when.reduce(funcs, function(arg, func) { return func.call(thisArg, arg); }, firstPromise); }; } }); })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); }); },{"./lib/apply":58,"./lib/liftAll":70,"./when":78}],55:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function (require) { var makePromise = require('./makePromise'); var Scheduler = require('./Scheduler'); var async = require('./env').asap; return makePromise({ scheduler: new Scheduler(async) }); }); })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); }); },{"./Scheduler":56,"./env":68,"./makePromise":71}],56:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { // Credit to Twisol (https://github.com/Twisol) for suggesting // this type of extensible queue + trampoline approach for next-tick conflation. /** * Async task scheduler * @param {function} async function to schedule a single async function * @constructor */ function Scheduler(async) { this._async = async; this._running = false; this._queue = this; this._queueLen = 0; this._afterQueue = {}; this._afterQueueLen = 0; var self = this; this.drain = function() { self._drain(); }; } /** * Enqueue a task * @param {{ run:function }} task */ Scheduler.prototype.enqueue = function(task) { this._queue[this._queueLen++] = task; this.run(); }; /** * Enqueue a task to run after the main task queue * @param {{ run:function }} task */ Scheduler.prototype.afterQueue = function(task) { this._afterQueue[this._afterQueueLen++] = task; this.run(); }; Scheduler.prototype.run = function() { if (!this._running) { this._running = true; this._async(this.drain); } }; /** * Drain the handler queue entirely, and then the after queue */ Scheduler.prototype._drain = function() { var i = 0; for (; i < this._queueLen; ++i) { this._queue[i].run(); this._queue[i] = void 0; } this._queueLen = 0; this._running = false; for (i = 0; i < this._afterQueueLen; ++i) { this._afterQueue[i].run(); this._afterQueue[i] = void 0; } this._afterQueueLen = 0; }; return Scheduler; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],57:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { /** * Custom error type for promises rejected by promise.timeout * @param {string} message * @constructor */ function TimeoutError (message) { Error.call(this); this.message = message; this.name = TimeoutError.name; if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, TimeoutError); } } TimeoutError.prototype = Object.create(Error.prototype); TimeoutError.prototype.constructor = TimeoutError; return TimeoutError; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],58:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { makeApply.tryCatchResolve = tryCatchResolve; return makeApply; function makeApply(Promise, call) { if(arguments.length < 2) { call = tryCatchResolve; } return apply; function apply(f, thisArg, args) { var p = Promise._defer(); var l = args.length; var params = new Array(l); callAndResolve({ f:f, thisArg:thisArg, args:args, params:params, i:l-1, call:call }, p._handler); return p; } function callAndResolve(c, h) { if(c.i < 0) { return call(c.f, c.thisArg, c.params, h); } var handler = Promise._handler(c.args[c.i]); handler.fold(callAndResolveNext, c, void 0, h); } function callAndResolveNext(c, x, h) { c.params[c.i] = x; c.i -= 1; callAndResolve(c, h); } } function tryCatchResolve(f, thisArg, args, resolver) { try { resolver.resolve(f.apply(thisArg, args)); } catch(e) { resolver.reject(e); } } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],59:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(require) { var state = require('../state'); var applier = require('../apply'); return function array(Promise) { var applyFold = applier(Promise); var toPromise = Promise.resolve; var all = Promise.all; var ar = Array.prototype.reduce; var arr = Array.prototype.reduceRight; var slice = Array.prototype.slice; // Additional array combinators Promise.any = any; Promise.some = some; Promise.settle = settle; Promise.map = map; Promise.filter = filter; Promise.reduce = reduce; Promise.reduceRight = reduceRight; /** * When this promise fulfills with an array, do * onFulfilled.apply(void 0, array) * @param {function} onFulfilled function to apply * @returns {Promise} promise for the result of applying onFulfilled */ Promise.prototype.spread = function(onFulfilled) { return this.then(all).then(function(array) { return onFulfilled.apply(this, array); }); }; return Promise; /** * One-winner competitive race. * Return a promise that will fulfill when one of the promises * in the input array fulfills, or will reject when all promises * have rejected. * @param {array} promises * @returns {Promise} promise for the first fulfilled value */ function any(promises) { var p = Promise._defer(); var resolver = p._handler; var l = promises.length>>>0; var pending = l; var errors = []; for (var h, x, i = 0; i < l; ++i) { x = promises[i]; if(x === void 0 && !(i in promises)) { --pending; continue; } h = Promise._handler(x); if(h.state() > 0) { resolver.become(h); Promise._visitRemaining(promises, i, h); break; } else { h.visit(resolver, handleFulfill, handleReject); } } if(pending === 0) { resolver.reject(new RangeError('any(): array must not be empty')); } return p; function handleFulfill(x) { /*jshint validthis:true*/ errors = null; this.resolve(x); // this === resolver } function handleReject(e) { /*jshint validthis:true*/ if(this.resolved) { // this === resolver return; } errors.push(e); if(--pending === 0) { this.reject(errors); } } } /** * N-winner competitive race * Return a promise that will fulfill when n input promises have * fulfilled, or will reject when it becomes impossible for n * input promises to fulfill (ie when promises.length - n + 1 * have rejected) * @param {array} promises * @param {number} n * @returns {Promise} promise for the earliest n fulfillment values * * @deprecated */ function some(promises, n) { /*jshint maxcomplexity:7*/ var p = Promise._defer(); var resolver = p._handler; var results = []; var errors = []; var l = promises.length>>>0; var nFulfill = 0; var nReject; var x, i; // reused in both for() loops // First pass: count actual array items for(i=0; i<l; ++i) { x = promises[i]; if(x === void 0 && !(i in promises)) { continue; } ++nFulfill; } // Compute actual goals n = Math.max(n, 0); nReject = (nFulfill - n + 1); nFulfill = Math.min(n, nFulfill); if(n > nFulfill) { resolver.reject(new RangeError('some(): array must contain at least ' + n + ' item(s), but had ' + nFulfill)); } else if(nFulfill === 0) { resolver.resolve(results); } // Second pass: observe each array item, make progress toward goals for(i=0; i<l; ++i) { x = promises[i]; if(x === void 0 && !(i in promises)) { continue; } Promise._handler(x).visit(resolver, fulfill, reject, resolver.notify); } return p; function fulfill(x) { /*jshint validthis:true*/ if(this.resolved) { // this === resolver return; } results.push(x); if(--nFulfill === 0) { errors = null; this.resolve(results); } } function reject(e) { /*jshint validthis:true*/ if(this.resolved) { // this === resolver return; } errors.push(e); if(--nReject === 0) { results = null; this.reject(errors); } } } /** * Apply f to the value of each promise in a list of promises * and return a new list containing the results. * @param {array} promises * @param {function(x:*, index:Number):*} f mapping function * @returns {Promise} */ function map(promises, f) { return Promise._traverse(f, promises); } /** * Filter the provided array of promises using the provided predicate. Input may * contain promises and values * @param {Array} promises array of promises and values * @param {function(x:*, index:Number):boolean} predicate filtering predicate. * Must return truthy (or promise for truthy) for items to retain. * @returns {Promise} promise that will fulfill with an array containing all items * for which predicate returned truthy. */ function filter(promises, predicate) { var a = slice.call(promises); return Promise._traverse(predicate, a).then(function(keep) { return filterSync(a, keep); }); } function filterSync(promises, keep) { // Safe because we know all promises have fulfilled if we've made it this far var l = keep.length; var filtered = new Array(l); for(var i=0, j=0; i<l; ++i) { if(keep[i]) { filtered[j++] = Promise._handler(promises[i]).value; } } filtered.length = j; return filtered; } /** * Return a promise that will always fulfill with an array containing * the outcome states of all input promises. The returned promise * will never reject. * @param {Array} promises * @returns {Promise} promise for array of settled state descriptors */ function settle(promises) { return all(promises.map(settleOne)); } function settleOne(p) { var h = Promise._handler(p); if(h.state() === 0) { return toPromise(p).then(state.fulfilled, state.rejected); } h._unreport(); return state.inspect(h); } /** * Traditional reduce function, similar to `Array.prototype.reduce()`, but * input may contain promises and/or values, and reduceFunc * may return either a value or a promise, *and* initialValue may * be a promise for the starting value. * @param {Array|Promise} promises array or promise for an array of anything, * may contain a mix of promises and values. * @param {function(accumulated:*, x:*, index:Number):*} f reduce function * @returns {Promise} that will resolve to the final reduced value */ function reduce(promises, f /*, initialValue */) { return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2]) : ar.call(promises, liftCombine(f)); } /** * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but * input may contain promises and/or values, and reduceFunc * may return either a value or a promise, *and* initialValue may * be a promise for the starting value. * @param {Array|Promise} promises array or promise for an array of anything, * may contain a mix of promises and values. * @param {function(accumulated:*, x:*, index:Number):*} f reduce function * @returns {Promise} that will resolve to the final reduced value */ function reduceRight(promises, f /*, initialValue */) { return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2]) : arr.call(promises, liftCombine(f)); } function liftCombine(f) { return function(z, x, i) { return applyFold(f, void 0, [z,x,i]); }; } }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); })); },{"../apply":58,"../state":72}],60:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function flow(Promise) { var resolve = Promise.resolve; var reject = Promise.reject; var origCatch = Promise.prototype['catch']; /** * Handle the ultimate fulfillment value or rejection reason, and assume * responsibility for all errors. If an error propagates out of result * or handleFatalError, it will be rethrown to the host, resulting in a * loud stack track on most platforms and a crash on some. * @param {function?} onResult * @param {function?} onError * @returns {undefined} */ Promise.prototype.done = function(onResult, onError) { this._handler.visit(this._handler.receiver, onResult, onError); }; /** * Add Error-type and predicate matching to catch. Examples: * promise.catch(TypeError, handleTypeError) * .catch(predicate, handleMatchedErrors) * .catch(handleRemainingErrors) * @param onRejected * @returns {*} */ Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) { if (arguments.length < 2) { return origCatch.call(this, onRejected); } if(typeof onRejected !== 'function') { return this.ensure(rejectInvalidPredicate); } return origCatch.call(this, createCatchFilter(arguments[1], onRejected)); }; /** * Wraps the provided catch handler, so that it will only be called * if the predicate evaluates truthy * @param {?function} handler * @param {function} predicate * @returns {function} conditional catch handler */ function createCatchFilter(handler, predicate) { return function(e) { return evaluatePredicate(e, predicate) ? handler.call(this, e) : reject(e); }; } /** * Ensures that onFulfilledOrRejected will be called regardless of whether * this promise is fulfilled or rejected. onFulfilledOrRejected WILL NOT * receive the promises' value or reason. Any returned value will be disregarded. * onFulfilledOrRejected may throw or return a rejected promise to signal * an additional error. * @param {function} handler handler to be called regardless of * fulfillment or rejection * @returns {Promise} */ Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) { if(typeof handler !== 'function') { return this; } return this.then(function(x) { return runSideEffect(handler, this, identity, x); }, function(e) { return runSideEffect(handler, this, reject, e); }); }; function runSideEffect (handler, thisArg, propagate, value) { var result = handler.call(thisArg); return maybeThenable(result) ? propagateValue(result, propagate, value) : propagate(value); } function propagateValue (result, propagate, x) { return resolve(result).then(function () { return propagate(x); }); } /** * Recover from a failure by returning a defaultValue. If defaultValue * is a promise, it's fulfillment value will be used. If defaultValue is * a promise that rejects, the returned promise will reject with the * same reason. * @param {*} defaultValue * @returns {Promise} new promise */ Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) { return this.then(void 0, function() { return defaultValue; }); }; /** * Shortcut for .then(function() { return value; }) * @param {*} value * @return {Promise} a promise that: * - is fulfilled if value is not a promise, or * - if value is a promise, will fulfill with its value, or reject * with its reason. */ Promise.prototype['yield'] = function(value) { return this.then(function() { return value; }); }; /** * Runs a side effect when this promise fulfills, without changing the * fulfillment value. * @param {function} onFulfilledSideEffect * @returns {Promise} */ Promise.prototype.tap = function(onFulfilledSideEffect) { return this.then(onFulfilledSideEffect)['yield'](this); }; return Promise; }; function rejectInvalidPredicate() { throw new TypeError('catch predicate must be a function'); } function evaluatePredicate(e, predicate) { return isError(predicate) ? e instanceof predicate : predicate(e); } function isError(predicate) { return predicate === Error || (predicate != null && predicate.prototype instanceof Error); } function maybeThenable(x) { return (typeof x === 'object' || typeof x === 'function') && x !== null; } function identity(x) { return x; } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],61:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ /** @author Jeff Escalante */ (function(define) { 'use strict'; define(function() { return function fold(Promise) { Promise.prototype.fold = function(f, z) { var promise = this._beget(); this._handler.fold(function(z, x, to) { Promise._handler(z).fold(function(x, z, to) { to.resolve(f.call(this, z, x)); }, x, this, to); }, z, promise._handler.receiver, promise._handler); return promise; }; return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],62:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(require) { var inspect = require('../state').inspect; return function inspection(Promise) { Promise.prototype.inspect = function() { return inspect(Promise._handler(this)); }; return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); })); },{"../state":72}],63:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function generate(Promise) { var resolve = Promise.resolve; Promise.iterate = iterate; Promise.unfold = unfold; return Promise; /** * @deprecated Use github.com/cujojs/most streams and most.iterate * Generate a (potentially infinite) stream of promised values: * x, f(x), f(f(x)), etc. until condition(x) returns true * @param {function} f function to generate a new x from the previous x * @param {function} condition function that, given the current x, returns * truthy when the iterate should stop * @param {function} handler function to handle the value produced by f * @param {*|Promise} x starting value, may be a promise * @return {Promise} the result of the last call to f before * condition returns true */ function iterate(f, condition, handler, x) { return unfold(function(x) { return [x, f(x)]; }, condition, handler, x); } /** * @deprecated Use github.com/cujojs/most streams and most.unfold * Generate a (potentially infinite) stream of promised values * by applying handler(generator(seed)) iteratively until * condition(seed) returns true. * @param {function} unspool function that generates a [value, newSeed] * given a seed. * @param {function} condition function that, given the current seed, returns * truthy when the unfold should stop * @param {function} handler function to handle the value produced by unspool * @param x {*|Promise} starting value, may be a promise * @return {Promise} the result of the last value produced by unspool before * condition returns true */ function unfold(unspool, condition, handler, x) { return resolve(x).then(function(seed) { return resolve(condition(seed)).then(function(done) { return done ? seed : resolve(unspool(seed)).spread(next); }); }); function next(item, newSeed) { return resolve(handler(item)).then(function() { return unfold(unspool, condition, handler, newSeed); }); } } }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],64:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function progress(Promise) { /** * @deprecated * Register a progress handler for this promise * @param {function} onProgress * @returns {Promise} */ Promise.prototype.progress = function(onProgress) { return this.then(void 0, void 0, onProgress); }; return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],65:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(require) { var env = require('../env'); var TimeoutError = require('../TimeoutError'); function setTimeout(f, ms, x, y) { return env.setTimer(function() { f(x, y, ms); }, ms); } return function timed(Promise) { /** * Return a new promise whose fulfillment value is revealed only * after ms milliseconds * @param {number} ms milliseconds * @returns {Promise} */ Promise.prototype.delay = function(ms) { var p = this._beget(); this._handler.fold(handleDelay, ms, void 0, p._handler); return p; }; function handleDelay(ms, x, h) { setTimeout(resolveDelay, ms, x, h); } function resolveDelay(x, h) { h.resolve(x); } /** * Return a new promise that rejects after ms milliseconds unless * this promise fulfills earlier, in which case the returned promise * fulfills with the same value. * @param {number} ms milliseconds * @param {Error|*=} reason optional rejection reason to use, defaults * to a TimeoutError if not provided * @returns {Promise} */ Promise.prototype.timeout = function(ms, reason) { var p = this._beget(); var h = p._handler; var t = setTimeout(onTimeout, ms, reason, p._handler); this._handler.visit(h, function onFulfill(x) { env.clearTimer(t); this.resolve(x); // this = h }, function onReject(x) { env.clearTimer(t); this.reject(x); // this = h }, h.notify); return p; }; function onTimeout(reason, h, ms) { var e = typeof reason === 'undefined' ? new TimeoutError('timed out after ' + ms + 'ms') : reason; h.reject(e); } return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); })); },{"../TimeoutError":57,"../env":68}],66:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(require) { var setTimer = require('../env').setTimer; var format = require('../format'); return function unhandledRejection(Promise) { var logError = noop; var logInfo = noop; var localConsole; if(typeof console !== 'undefined') { // Alias console to prevent things like uglify's drop_console option from // removing console.log/error. Unhandled rejections fall into the same // category as uncaught exceptions, and build tools shouldn't silence them. localConsole = console; logError = typeof localConsole.error !== 'undefined' ? function (e) { localConsole.error(e); } : function (e) { localConsole.log(e); }; logInfo = typeof localConsole.info !== 'undefined' ? function (e) { localConsole.info(e); } : function (e) { localConsole.log(e); }; } Promise.onPotentiallyUnhandledRejection = function(rejection) { enqueue(report, rejection); }; Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) { enqueue(unreport, rejection); }; Promise.onFatalRejection = function(rejection) { enqueue(throwit, rejection.value); }; var tasks = []; var reported = []; var running = null; function report(r) { if(!r.handled) { reported.push(r); logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value)); } } function unreport(r) { var i = reported.indexOf(r); if(i >= 0) { reported.splice(i, 1); logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value)); } } function enqueue(f, x) { tasks.push(f, x); if(running === null) { running = setTimer(flush, 0); } } function flush() { running = null; while(tasks.length > 0) { tasks.shift()(tasks.shift()); } } return Promise; }; function throwit(e) { throw e; } function noop() {} }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); })); },{"../env":68,"../format":69}],67:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function addWith(Promise) { /** * Returns a promise whose handlers will be called with `this` set to * the supplied receiver. Subsequent promises derived from the * returned promise will also have their handlers called with receiver * as `this`. Calling `with` with undefined or no arguments will return * a promise whose handlers will again be called in the usual Promises/A+ * way (no `this`) thus safely undoing any previous `with` in the * promise chain. * * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+ * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41) * * @param {object} receiver `this` value for all handlers attached to * the returned promise. * @returns {Promise} */ Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) { var p = this._beget(); var child = p._handler; child.receiver = receiver; this._handler.chain(child, receiver); return p; }; return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],68:[function(require,module,exports){ (function (process){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/ (function(define) { 'use strict'; define(function(require) { /*jshint maxcomplexity:6*/ // Sniff "best" async scheduling option // Prefer process.nextTick or MutationObserver, then check for // setTimeout, and finally vertx, since its the only env that doesn't // have setTimeout var MutationObs; var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout; // Default env var setTimer = function(f, ms) { return setTimeout(f, ms); }; var clearTimer = function(t) { return clearTimeout(t); }; var asap = function (f) { return capturedSetTimeout(f, 0); }; // Detect specific env if (isNode()) { // Node asap = function (f) { return process.nextTick(f); }; } else if (MutationObs = hasMutationObserver()) { // Modern browser asap = initMutationObserver(MutationObs); } else if (!capturedSetTimeout) { // vert.x var vertxRequire = require; var vertx = vertxRequire('vertx'); setTimer = function (f, ms) { return vertx.setTimer(ms, f); }; clearTimer = vertx.cancelTimer; asap = vertx.runOnLoop || vertx.runOnContext; } return { setTimer: setTimer, clearTimer: clearTimer, asap: asap }; function isNode () { return typeof process !== 'undefined' && process !== null && typeof process.nextTick === 'function'; } function hasMutationObserver () { return (typeof MutationObserver === 'function' && MutationObserver) || (typeof WebKitMutationObserver === 'function' && WebKitMutationObserver); } function initMutationObserver(MutationObserver) { var scheduled; var node = document.createTextNode(''); var o = new MutationObserver(run); o.observe(node, { characterData: true }); function run() { var f = scheduled; scheduled = void 0; f(); } var i = 0; return function (f) { scheduled = f; node.data = (i ^= 1); }; } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); })); }).call(this,require('_process')) },{"_process":1}],69:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return { formatError: formatError, formatObject: formatObject, tryStringify: tryStringify }; /** * Format an error into a string. If e is an Error and has a stack property, * it's returned. Otherwise, e is formatted using formatObject, with a * warning added about e not being a proper Error. * @param {*} e * @returns {String} formatted string, suitable for output to developers */ function formatError(e) { var s = typeof e === 'object' && e !== null && e.stack ? e.stack : formatObject(e); return e instanceof Error ? s : s + ' (WARNING: non-Error used)'; } /** * Format an object, detecting "plain" objects and running them through * JSON.stringify if possible. * @param {Object} o * @returns {string} */ function formatObject(o) { var s = String(o); if(s === '[object Object]' && typeof JSON !== 'undefined') { s = tryStringify(o, s); } return s; } /** * Try to return the result of JSON.stringify(x). If that fails, return * defaultValue * @param {*} x * @param {*} defaultValue * @returns {String|*} JSON.stringify(x) or defaultValue */ function tryStringify(x, defaultValue) { try { return JSON.stringify(x); } catch(e) { return defaultValue; } } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],70:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function liftAll(liftOne, combine, dst, src) { if(typeof combine === 'undefined') { combine = defaultCombine; } return Object.keys(src).reduce(function(dst, key) { var f = src[key]; return typeof f === 'function' ? combine(dst, liftOne(f), key) : dst; }, typeof dst === 'undefined' ? defaultDst(src) : dst); }; function defaultCombine(o, f, k) { o[k] = f; return o; } function defaultDst(src) { return typeof src === 'function' ? src.bind() : Object.create(src); } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],71:[function(require,module,exports){ (function (process){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function makePromise(environment) { var tasks = environment.scheduler; var emitRejection = initEmitRejection(); var objectCreate = Object.create || function(proto) { function Child() {} Child.prototype = proto; return new Child(); }; /** * Create a promise whose fate is determined by resolver * @constructor * @returns {Promise} promise * @name Promise */ function Promise(resolver, handler) { this._handler = resolver === Handler ? handler : init(resolver); } /** * Run the supplied resolver * @param resolver * @returns {Pending} */ function init(resolver) { var handler = new Pending(); try { resolver(promiseResolve, promiseReject, promiseNotify); } catch (e) { promiseReject(e); } return handler; /** * Transition from pre-resolution state to post-resolution state, notifying * all listeners of the ultimate fulfillment or rejection * @param {*} x resolution value */ function promiseResolve (x) { handler.resolve(x); } /** * Reject this promise with reason, which will be used verbatim * @param {Error|*} reason rejection reason, strongly suggested * to be an Error type */ function promiseReject (reason) { handler.reject(reason); } /** * @deprecated * Issue a progress event, notifying all progress listeners * @param {*} x progress event payload to pass to all listeners */ function promiseNotify (x) { handler.notify(x); } } // Creation Promise.resolve = resolve; Promise.reject = reject; Promise.never = never; Promise._defer = defer; Promise._handler = getHandler; /** * Returns a trusted promise. If x is already a trusted promise, it is * returned, otherwise returns a new trusted Promise which follows x. * @param {*} x * @return {Promise} promise */ function resolve(x) { return isPromise(x) ? x : new Promise(Handler, new Async(getHandler(x))); } /** * Return a reject promise with x as its reason (x is used verbatim) * @param {*} x * @returns {Promise} rejected promise */ function reject(x) { return new Promise(Handler, new Async(new Rejected(x))); } /** * Return a promise that remains pending forever * @returns {Promise} forever-pending promise. */ function never() { return foreverPendingPromise; // Should be frozen } /** * Creates an internal {promise, resolver} pair * @private * @returns {Promise} */ function defer() { return new Promise(Handler, new Pending()); } // Transformation and flow control /** * Transform this promise's fulfillment value, returning a new Promise * for the transformed result. If the promise cannot be fulfilled, onRejected * is called with the reason. onProgress *may* be called with updates toward * this promise's fulfillment. * @param {function=} onFulfilled fulfillment handler * @param {function=} onRejected rejection handler * @param {function=} onProgress @deprecated progress handler * @return {Promise} new promise */ Promise.prototype.then = function(onFulfilled, onRejected, onProgress) { var parent = this._handler; var state = parent.join().state(); if ((typeof onFulfilled !== 'function' && state > 0) || (typeof onRejected !== 'function' && state < 0)) { // Short circuit: value will not change, simply share handler return new this.constructor(Handler, parent); } var p = this._beget(); var child = p._handler; parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress); return p; }; /** * If this promise cannot be fulfilled due to an error, call onRejected to * handle the error. Shortcut for .then(undefined, onRejected) * @param {function?} onRejected * @return {Promise} */ Promise.prototype['catch'] = function(onRejected) { return this.then(void 0, onRejected); }; /** * Creates a new, pending promise of the same type as this promise * @private * @returns {Promise} */ Promise.prototype._beget = function() { return begetFrom(this._handler, this.constructor); }; function begetFrom(parent, Promise) { var child = new Pending(parent.receiver, parent.join().context); return new Promise(Handler, child); } // Array combinators Promise.all = all; Promise.race = race; Promise._traverse = traverse; /** * Return a promise that will fulfill when all promises in the * input array have fulfilled, or will reject when one of the * promises rejects. * @param {array} promises array of promises * @returns {Promise} promise for array of fulfillment values */ function all(promises) { return traverseWith(snd, null, promises); } /** * Array<Promise<X>> -> Promise<Array<f(X)>> * @private * @param {function} f function to apply to each promise's value * @param {Array} promises array of promises * @returns {Promise} promise for transformed values */ function traverse(f, promises) { return traverseWith(tryCatch2, f, promises); } function traverseWith(tryMap, f, promises) { var handler = typeof f === 'function' ? mapAt : settleAt; var resolver = new Pending(); var pending = promises.length >>> 0; var results = new Array(pending); for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) { x = promises[i]; if (x === void 0 && !(i in promises)) { --pending; continue; } traverseAt(promises, handler, i, x, resolver); } if(pending === 0) { resolver.become(new Fulfilled(results)); } return new Promise(Handler, resolver); function mapAt(i, x, resolver) { if(!resolver.resolved) { traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver); } } function settleAt(i, x, resolver) { results[i] = x; if(--pending === 0) { resolver.become(new Fulfilled(results)); } } } function traverseAt(promises, handler, i, x, resolver) { if (maybeThenable(x)) { var h = getHandlerMaybeThenable(x); var s = h.state(); if (s === 0) { h.fold(handler, i, void 0, resolver); } else if (s > 0) { handler(i, h.value, resolver); } else { resolver.become(h); visitRemaining(promises, i+1, h); } } else { handler(i, x, resolver); } } Promise._visitRemaining = visitRemaining; function visitRemaining(promises, start, handler) { for(var i=start; i<promises.length; ++i) { markAsHandled(getHandler(promises[i]), handler); } } function markAsHandled(h, handler) { if(h === handler) { return; } var s = h.state(); if(s === 0) { h.visit(h, void 0, h._unreport); } else if(s < 0) { h._unreport(); } } /** * Fulfill-reject competitive race. Return a promise that will settle * to the same state as the earliest input promise to settle. * * WARNING: The ES6 Promise spec requires that race()ing an empty array * must return a promise that is pending forever. This implementation * returns a singleton forever-pending promise, the same singleton that is * returned by Promise.never(), thus can be checked with === * * @param {array} promises array of promises to race * @returns {Promise} if input is non-empty, a promise that will settle * to the same outcome as the earliest input promise to settle. if empty * is empty, returns a promise that will never settle. */ function race(promises) { if(typeof promises !== 'object' || promises === null) { return reject(new TypeError('non-iterable passed to race()')); } // Sigh, race([]) is untestable unless we return *something* // that is recognizable without calling .then() on it. return promises.length === 0 ? never() : promises.length === 1 ? resolve(promises[0]) : runRace(promises); } function runRace(promises) { var resolver = new Pending(); var i, x, h; for(i=0; i<promises.length; ++i) { x = promises[i]; if (x === void 0 && !(i in promises)) { continue; } h = getHandler(x); if(h.state() !== 0) { resolver.become(h); visitRemaining(promises, i+1, h); break; } else { h.visit(resolver, resolver.resolve, resolver.reject); } } return new Promise(Handler, resolver); } // Promise internals // Below this, everything is @private /** * Get an appropriate handler for x, without checking for cycles * @param {*} x * @returns {object} handler */ function getHandler(x) { if(isPromise(x)) { return x._handler.join(); } return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x); } /** * Get a handler for thenable x. * NOTE: You must only call this if maybeThenable(x) == true * @param {object|function|Promise} x * @returns {object} handler */ function getHandlerMaybeThenable(x) { return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x); } /** * Get a handler for potentially untrusted thenable x * @param {*} x * @returns {object} handler */ function getHandlerUntrusted(x) { try { var untrustedThen = x.then; return typeof untrustedThen === 'function' ? new Thenable(untrustedThen, x) : new Fulfilled(x); } catch(e) { return new Rejected(e); } } /** * Handler for a promise that is pending forever * @constructor */ function Handler() {} Handler.prototype.when = Handler.prototype.become = Handler.prototype.notify // deprecated = Handler.prototype.fail = Handler.prototype._unreport = Handler.prototype._report = noop; Handler.prototype._state = 0; Handler.prototype.state = function() { return this._state; }; /** * Recursively collapse handler chain to find the handler * nearest to the fully resolved value. * @returns {object} handler nearest the fully resolved value */ Handler.prototype.join = function() { var h = this; while(h.handler !== void 0) { h = h.handler; } return h; }; Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) { this.when({ resolver: to, receiver: receiver, fulfilled: fulfilled, rejected: rejected, progress: progress }); }; Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) { this.chain(failIfRejected, receiver, fulfilled, rejected, progress); }; Handler.prototype.fold = function(f, z, c, to) { this.when(new Fold(f, z, c, to)); }; /** * Handler that invokes fail() on any handler it becomes * @constructor */ function FailIfRejected() {} inherit(Handler, FailIfRejected); FailIfRejected.prototype.become = function(h) { h.fail(); }; var failIfRejected = new FailIfRejected(); /** * Handler that manages a queue of consumers waiting on a pending promise * @constructor */ function Pending(receiver, inheritedContext) { Promise.createContext(this, inheritedContext); this.consumers = void 0; this.receiver = receiver; this.handler = void 0; this.resolved = false; } inherit(Handler, Pending); Pending.prototype._state = 0; Pending.prototype.resolve = function(x) { this.become(getHandler(x)); }; Pending.prototype.reject = function(x) { if(this.resolved) { return; } this.become(new Rejected(x)); }; Pending.prototype.join = function() { if (!this.resolved) { return this; } var h = this; while (h.handler !== void 0) { h = h.handler; if (h === this) { return this.handler = cycle(); } } return h; }; Pending.prototype.run = function() { var q = this.consumers; var handler = this.handler; this.handler = this.handler.join(); this.consumers = void 0; for (var i = 0; i < q.length; ++i) { handler.when(q[i]); } }; Pending.prototype.become = function(handler) { if(this.resolved) { return; } this.resolved = true; this.handler = handler; if(this.consumers !== void 0) { tasks.enqueue(this); } if(this.context !== void 0) { handler._report(this.context); } }; Pending.prototype.when = function(continuation) { if(this.resolved) { tasks.enqueue(new ContinuationTask(continuation, this.handler)); } else { if(this.consumers === void 0) { this.consumers = [continuation]; } else { this.consumers.push(continuation); } } }; /** * @deprecated */ Pending.prototype.notify = function(x) { if(!this.resolved) { tasks.enqueue(new ProgressTask(x, this)); } }; Pending.prototype.fail = function(context) { var c = typeof context === 'undefined' ? this.context : context; this.resolved && this.handler.join().fail(c); }; Pending.prototype._report = function(context) { this.resolved && this.handler.join()._report(context); }; Pending.prototype._unreport = function() { this.resolved && this.handler.join()._unreport(); }; /** * Wrap another handler and force it into a future stack * @param {object} handler * @constructor */ function Async(handler) { this.handler = handler; } inherit(Handler, Async); Async.prototype.when = function(continuation) { tasks.enqueue(new ContinuationTask(continuation, this)); }; Async.prototype._report = function(context) { this.join()._report(context); }; Async.prototype._unreport = function() { this.join()._unreport(); }; /** * Handler that wraps an untrusted thenable and assimilates it in a future stack * @param {function} then * @param {{then: function}} thenable * @constructor */ function Thenable(then, thenable) { Pending.call(this); tasks.enqueue(new AssimilateTask(then, thenable, this)); } inherit(Pending, Thenable); /** * Handler for a fulfilled promise * @param {*} x fulfillment value * @constructor */ function Fulfilled(x) { Promise.createContext(this); this.value = x; } inherit(Handler, Fulfilled); Fulfilled.prototype._state = 1; Fulfilled.prototype.fold = function(f, z, c, to) { runContinuation3(f, z, this, c, to); }; Fulfilled.prototype.when = function(cont) { runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver); }; var errorId = 0; /** * Handler for a rejected promise * @param {*} x rejection reason * @constructor */ function Rejected(x) { Promise.createContext(this); this.id = ++errorId; this.value = x; this.handled = false; this.reported = false; this._report(); } inherit(Handler, Rejected); Rejected.prototype._state = -1; Rejected.prototype.fold = function(f, z, c, to) { to.become(this); }; Rejected.prototype.when = function(cont) { if(typeof cont.rejected === 'function') { this._unreport(); } runContinuation1(cont.rejected, this, cont.receiver, cont.resolver); }; Rejected.prototype._report = function(context) { tasks.afterQueue(new ReportTask(this, context)); }; Rejected.prototype._unreport = function() { if(this.handled) { return; } this.handled = true; tasks.afterQueue(new UnreportTask(this)); }; Rejected.prototype.fail = function(context) { this.reported = true; emitRejection('unhandledRejection', this); Promise.onFatalRejection(this, context === void 0 ? this.context : context); }; function ReportTask(rejection, context) { this.rejection = rejection; this.context = context; } ReportTask.prototype.run = function() { if(!this.rejection.handled && !this.rejection.reported) { this.rejection.reported = true; emitRejection('unhandledRejection', this.rejection) || Promise.onPotentiallyUnhandledRejection(this.rejection, this.context); } }; function UnreportTask(rejection) { this.rejection = rejection; } UnreportTask.prototype.run = function() { if(this.rejection.reported) { emitRejection('rejectionHandled', this.rejection) || Promise.onPotentiallyUnhandledRejectionHandled(this.rejection); } }; // Unhandled rejection hooks // By default, everything is a noop Promise.createContext = Promise.enterContext = Promise.exitContext = Promise.onPotentiallyUnhandledRejection = Promise.onPotentiallyUnhandledRejectionHandled = Promise.onFatalRejection = noop; // Errors and singletons var foreverPendingHandler = new Handler(); var foreverPendingPromise = new Promise(Handler, foreverPendingHandler); function cycle() { return new Rejected(new TypeError('Promise cycle')); } // Task runners /** * Run a single consumer * @constructor */ function ContinuationTask(continuation, handler) { this.continuation = continuation; this.handler = handler; } ContinuationTask.prototype.run = function() { this.handler.join().when(this.continuation); }; /** * Run a queue of progress handlers * @constructor */ function ProgressTask(value, handler) { this.handler = handler; this.value = value; } ProgressTask.prototype.run = function() { var q = this.handler.consumers; if(q === void 0) { return; } for (var c, i = 0; i < q.length; ++i) { c = q[i]; runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver); } }; /** * Assimilate a thenable, sending it's value to resolver * @param {function} then * @param {object|function} thenable * @param {object} resolver * @constructor */ function AssimilateTask(then, thenable, resolver) { this._then = then; this.thenable = thenable; this.resolver = resolver; } AssimilateTask.prototype.run = function() { var h = this.resolver; tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify); function _resolve(x) { h.resolve(x); } function _reject(x) { h.reject(x); } function _notify(x) { h.notify(x); } }; function tryAssimilate(then, thenable, resolve, reject, notify) { try { then.call(thenable, resolve, reject, notify); } catch (e) { reject(e); } } /** * Fold a handler value with z * @constructor */ function Fold(f, z, c, to) { this.f = f; this.z = z; this.c = c; this.to = to; this.resolver = failIfRejected; this.receiver = this; } Fold.prototype.fulfilled = function(x) { this.f.call(this.c, this.z, x, this.to); }; Fold.prototype.rejected = function(x) { this.to.reject(x); }; Fold.prototype.progress = function(x) { this.to.notify(x); }; // Other helpers /** * @param {*} x * @returns {boolean} true iff x is a trusted Promise */ function isPromise(x) { return x instanceof Promise; } /** * Test just enough to rule out primitives, in order to take faster * paths in some code * @param {*} x * @returns {boolean} false iff x is guaranteed *not* to be a thenable */ function maybeThenable(x) { return (typeof x === 'object' || typeof x === 'function') && x !== null; } function runContinuation1(f, h, receiver, next) { if(typeof f !== 'function') { return next.become(h); } Promise.enterContext(h); tryCatchReject(f, h.value, receiver, next); Promise.exitContext(); } function runContinuation3(f, x, h, receiver, next) { if(typeof f !== 'function') { return next.become(h); } Promise.enterContext(h); tryCatchReject3(f, x, h.value, receiver, next); Promise.exitContext(); } /** * @deprecated */ function runNotify(f, x, h, receiver, next) { if(typeof f !== 'function') { return next.notify(x); } Promise.enterContext(h); tryCatchReturn(f, x, receiver, next); Promise.exitContext(); } function tryCatch2(f, a, b) { try { return f(a, b); } catch(e) { return reject(e); } } /** * Return f.call(thisArg, x), or if it throws return a rejected promise for * the thrown exception */ function tryCatchReject(f, x, thisArg, next) { try { next.become(getHandler(f.call(thisArg, x))); } catch(e) { next.become(new Rejected(e)); } } /** * Same as above, but includes the extra argument parameter. */ function tryCatchReject3(f, x, y, thisArg, next) { try { f.call(thisArg, x, y, next); } catch(e) { next.become(new Rejected(e)); } } /** * @deprecated * Return f.call(thisArg, x), or if it throws, *return* the exception */ function tryCatchReturn(f, x, thisArg, next) { try { next.notify(f.call(thisArg, x)); } catch(e) { next.notify(e); } } function inherit(Parent, Child) { Child.prototype = objectCreate(Parent.prototype); Child.prototype.constructor = Child; } function snd(x, y) { return y; } function noop() {} function initEmitRejection() { /*global process, self, CustomEvent*/ if(typeof process !== 'undefined' && process !== null && typeof process.emit === 'function') { // Returning falsy here means to call the default // onPotentiallyUnhandledRejection API. This is safe even in // browserify since process.emit always returns falsy in browserify: // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46 return function(type, rejection) { return type === 'unhandledRejection' ? process.emit(type, rejection.value, rejection) : process.emit(type, rejection); }; } else if(typeof self !== 'undefined' && typeof CustomEvent === 'function') { return (function(noop, self, CustomEvent) { var hasCustomEvent = false; try { var ev = new CustomEvent('unhandledRejection'); hasCustomEvent = ev instanceof CustomEvent; } catch (e) {} return !hasCustomEvent ? noop : function(type, rejection) { var ev = new CustomEvent(type, { detail: { reason: rejection.value, key: rejection }, bubbles: false, cancelable: true }); return !self.dispatchEvent(ev); }; }(noop, self, CustomEvent)); } return noop; } return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); }).call(this,require('_process')) },{"_process":1}],72:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return { pending: toPendingState, fulfilled: toFulfilledState, rejected: toRejectedState, inspect: inspect }; function toPendingState() { return { state: 'pending' }; } function toRejectedState(e) { return { state: 'rejected', reason: e }; } function toFulfilledState(x) { return { state: 'fulfilled', value: x }; } function inspect(handler) { var state = handler.state(); return state === 0 ? toPendingState() : state > 0 ? toFulfilledState(handler.value) : toRejectedState(handler.value); } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],73:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(require) { var PromiseMonitor = require('./monitor/PromiseMonitor'); var ConsoleReporter = require('./monitor/ConsoleReporter'); var promiseMonitor = new PromiseMonitor(new ConsoleReporter()); return function(Promise) { return promiseMonitor.monitor(Promise); }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); })); },{"./monitor/ConsoleReporter":74,"./monitor/PromiseMonitor":75}],74:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(require) { var error = require('./error'); var unhandledRejectionsMsg = '[promises] Unhandled rejections: '; var allHandledMsg = '[promises] All previously unhandled rejections have now been handled'; function ConsoleReporter() { this._previouslyReported = false; } ConsoleReporter.prototype = initDefaultLogging(); ConsoleReporter.prototype.log = function(traces) { if(traces.length === 0) { if(this._previouslyReported) { this._previouslyReported = false; this.msg(allHandledMsg); } return; } this._previouslyReported = true; this.groupStart(unhandledRejectionsMsg + traces.length); try { this._log(traces); } finally { this.groupEnd(); } }; ConsoleReporter.prototype._log = function(traces) { for(var i=0; i<traces.length; ++i) { this.warn(error.format(traces[i])); } }; function initDefaultLogging() { /*jshint maxcomplexity:7*/ var log, warn, groupStart, groupEnd; if(typeof console === 'undefined') { log = warn = consoleNotAvailable; } else { // Alias console to prevent things like uglify's drop_console option from // removing console.log/error. Unhandled rejections fall into the same // category as uncaught exceptions, and build tools shouldn't silence them. var localConsole = console; if(typeof localConsole.error === 'function' && typeof localConsole.dir === 'function') { warn = function(s) { localConsole.error(s); }; log = function(s) { localConsole.log(s); }; if(typeof localConsole.groupCollapsed === 'function') { groupStart = function(s) { localConsole.groupCollapsed(s); }; groupEnd = function() { localConsole.groupEnd(); }; } } else { // IE8 has console.log and JSON, so we can make a // reasonably useful warn() from those. // Credit to webpro (https://github.com/webpro) for this idea if (typeof localConsole.log ==='function' && typeof JSON !== 'undefined') { log = warn = function (x) { if(typeof x !== 'string') { try { x = JSON.stringify(x); } catch(e) {} } localConsole.log(x); }; } } } return { msg: log, warn: warn, groupStart: groupStart || warn, groupEnd: groupEnd || consoleNotAvailable }; } function consoleNotAvailable() {} return ConsoleReporter; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); })); },{"./error":77}],75:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(require) { var defaultStackJumpSeparator = 'from execution context:'; var defaultStackFilter = /[\s\(\/\\](node|module|timers)\.js:|when([\/\\]{1,2}(lib|monitor|es6-shim)[\/\\]{1,2}|\.js)|(new\sPromise)\b|(\b(PromiseMonitor|ConsoleReporter|Scheduler|RunHandlerTask|ProgressTask|Promise|.*Handler)\.[\w_]\w\w+\b)|\b(tryCatch\w+|getHandler\w*)\b/i; var setTimer = require('../lib/env').setTimer; var error = require('./error'); var executionContext = []; function PromiseMonitor(reporter) { this.logDelay = 0; this.stackFilter = defaultStackFilter; this.stackJumpSeparator = defaultStackJumpSeparator; this.filterDuplicateFrames = true; this._reporter = reporter; if(typeof reporter.configurePromiseMonitor === 'function') { reporter.configurePromiseMonitor(this); } this._traces = []; this._traceTask = 0; var self = this; this._doLogTraces = function() { self._logTraces(); }; } PromiseMonitor.prototype.monitor = function(Promise) { var self = this; Promise.createContext = function(p, context) { p.context = self.createContext(p, context); }; Promise.enterContext = function(p) { executionContext.push(p.context); }; Promise.exitContext = function() { executionContext.pop(); }; Promise.onPotentiallyUnhandledRejection = function(rejection, extraContext) { return self.addTrace(rejection, extraContext); }; Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) { return self.removeTrace(rejection); }; Promise.onFatalRejection = function(rejection, extraContext) { return self.fatal(rejection, extraContext); }; return this; }; PromiseMonitor.prototype.createContext = function(at, parentContext) { var context = { parent: parentContext || executionContext[executionContext.length - 1], stack: void 0 }; error.captureStack(context, at.constructor); return context; }; PromiseMonitor.prototype.addTrace = function(handler, extraContext) { var t, i; for(i = this._traces.length-1; i >= 0; --i) { t = this._traces[i]; if(t.handler === handler) { break; } } if(i >= 0) { t.extraContext = extraContext; } else { this._traces.push({ handler: handler, extraContext: extraContext }); } this.logTraces(); }; PromiseMonitor.prototype.removeTrace = function(/*handler*/) { this.logTraces(); }; PromiseMonitor.prototype.fatal = function(handler, extraContext) { var err = new Error(); err.stack = this._createLongTrace(handler.value, handler.context, extraContext).join('\n'); setTimer(function() { throw err; }, 0); }; PromiseMonitor.prototype.logTraces = function() { if(!this._traceTask) { this._traceTask = setTimer(this._doLogTraces, this.logDelay); } }; PromiseMonitor.prototype._logTraces = function() { this._traceTask = void 0; this._traces = this._traces.filter(filterHandled); this._reporter.log(this.formatTraces(this._traces)); }; PromiseMonitor.prototype.formatTraces = function(traces) { return traces.map(function(t) { return this._createLongTrace(t.handler.value, t.handler.context, t.extraContext); }, this); }; PromiseMonitor.prototype._createLongTrace = function(e, context, extraContext) { var trace = error.parse(e) || [String(e) + ' (WARNING: non-Error used)']; trace = filterFrames(this.stackFilter, trace, 0); this._appendContext(trace, context); this._appendContext(trace, extraContext); return this.filterDuplicateFrames ? this._removeDuplicates(trace) : trace; }; PromiseMonitor.prototype._removeDuplicates = function(trace) { var seen = {}; var sep = this.stackJumpSeparator; var count = 0; return trace.reduceRight(function(deduped, line, i) { if(i === 0) { deduped.unshift(line); } else if(line === sep) { if(count > 0) { deduped.unshift(line); count = 0; } } else if(!seen[line]) { seen[line] = true; deduped.unshift(line); ++count; } return deduped; }, []); }; PromiseMonitor.prototype._appendContext = function(trace, context) { trace.push.apply(trace, this._createTrace(context)); }; PromiseMonitor.prototype._createTrace = function(traceChain) { var trace = []; var stack; while(traceChain) { stack = error.parse(traceChain); if (stack) { stack = filterFrames(this.stackFilter, stack); appendStack(trace, stack, this.stackJumpSeparator); } traceChain = traceChain.parent; } return trace; }; function appendStack(trace, stack, separator) { if (stack.length > 1) { stack[0] = separator; trace.push.apply(trace, stack); } } function filterFrames(stackFilter, stack) { return stack.filter(function(frame) { return !stackFilter.test(frame); }); } function filterHandled(t) { return !t.handler.handled; } return PromiseMonitor; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); })); },{"../lib/env":68,"./error":77}],76:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(require) { var monitor = require('../monitor'); var Promise = require('../when').Promise; return monitor(Promise); }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); })); },{"../monitor":73,"../when":78}],77:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { var parse, captureStack, format; if(Error.captureStackTrace) { // Use Error.captureStackTrace if available parse = function(e) { return e && e.stack && e.stack.split('\n'); }; format = formatAsString; captureStack = Error.captureStackTrace; } else { // Otherwise, do minimal feature detection to determine // how to capture and format reasonable stacks. parse = function(e) { var stack = e && e.stack && e.stack.split('\n'); if(stack && e.message) { stack.unshift(e.message); } return stack; }; (function() { var e = new Error(); if(typeof e.stack !== 'string') { format = formatAsString; captureStack = captureSpiderMonkeyStack; } else { format = formatAsErrorWithStack; captureStack = useStackDirectly; } }()); } function captureSpiderMonkeyStack(host) { try { throw new Error(); } catch(err) { host.stack = err.stack; } } function useStackDirectly(host) { host.stack = new Error().stack; } function formatAsString(longTrace) { return join(longTrace); } function formatAsErrorWithStack(longTrace) { var e = new Error(); e.stack = formatAsString(longTrace); return e; } // About 5-10x faster than String.prototype.join o_O function join(a) { var sep = false; var s = ''; for(var i=0; i< a.length; ++i) { if(sep) { s += '\n' + a[i]; } else { s+= a[i]; sep = true; } } return s; } return { parse: parse, format: format, captureStack: captureStack }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],78:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** * Promises/A+ and when() implementation * when is part of the cujoJS family of libraries (http://cujojs.com/) * @author Brian Cavalier * @author John Hann * @version 3.7.2 */ (function(define) { 'use strict'; define(function (require) { var timed = require('./lib/decorators/timed'); var array = require('./lib/decorators/array'); var flow = require('./lib/decorators/flow'); var fold = require('./lib/decorators/fold'); var inspect = require('./lib/decorators/inspect'); var generate = require('./lib/decorators/iterate'); var progress = require('./lib/decorators/progress'); var withThis = require('./lib/decorators/with'); var unhandledRejection = require('./lib/decorators/unhandledRejection'); var TimeoutError = require('./lib/TimeoutError'); var Promise = [array, flow, fold, generate, progress, inspect, withThis, timed, unhandledRejection] .reduce(function(Promise, feature) { return feature(Promise); }, require('./lib/Promise')); var apply = require('./lib/apply')(Promise); // Public API when.promise = promise; // Create a pending promise when.resolve = Promise.resolve; // Create a resolved promise when.reject = Promise.reject; // Create a rejected promise when.lift = lift; // lift a function to return promises when['try'] = attempt; // call a function and return a promise when.attempt = attempt; // alias for when.try when.iterate = Promise.iterate; // DEPRECATED (use cujojs/most streams) Generate a stream of promises when.unfold = Promise.unfold; // DEPRECATED (use cujojs/most streams) Generate a stream of promises when.join = join; // Join 2 or more promises when.all = all; // Resolve a list of promises when.settle = settle; // Settle a list of promises when.any = lift(Promise.any); // One-winner race when.some = lift(Promise.some); // Multi-winner race when.race = lift(Promise.race); // First-to-settle race when.map = map; // Array.map() for promises when.filter = filter; // Array.filter() for promises when.reduce = lift(Promise.reduce); // Array.reduce() for promises when.reduceRight = lift(Promise.reduceRight); // Array.reduceRight() for promises when.isPromiseLike = isPromiseLike; // Is something promise-like, aka thenable when.Promise = Promise; // Promise constructor when.defer = defer; // Create a {promise, resolve, reject} tuple // Error types when.TimeoutError = TimeoutError; /** * Get a trusted promise for x, or by transforming x with onFulfilled * * @param {*} x * @param {function?} onFulfilled callback to be called when x is * successfully fulfilled. If promiseOrValue is an immediate value, callback * will be invoked immediately. * @param {function?} onRejected callback to be called when x is * rejected. * @param {function?} onProgress callback to be called when progress updates * are issued for x. @deprecated * @returns {Promise} a new promise that will fulfill with the return * value of callback or errback or the completion value of promiseOrValue if * callback and/or errback is not supplied. */ function when(x, onFulfilled, onRejected, onProgress) { var p = Promise.resolve(x); if (arguments.length < 2) { return p; } return p.then(onFulfilled, onRejected, onProgress); } /** * Creates a new promise whose fate is determined by resolver. * @param {function} resolver function(resolve, reject, notify) * @returns {Promise} promise whose fate is determine by resolver */ function promise(resolver) { return new Promise(resolver); } /** * Lift the supplied function, creating a version of f that returns * promises, and accepts promises as arguments. * @param {function} f * @returns {Function} version of f that returns promises */ function lift(f) { return function() { for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) { a[i] = arguments[i]; } return apply(f, this, a); }; } /** * Call f in a future turn, with the supplied args, and return a promise * for the result. * @param {function} f * @returns {Promise} */ function attempt(f /*, args... */) { /*jshint validthis:true */ for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) { a[i] = arguments[i+1]; } return apply(f, this, a); } /** * Creates a {promise, resolver} pair, either or both of which * may be given out safely to consumers. * @return {{promise: Promise, resolve: function, reject: function, notify: function}} */ function defer() { return new Deferred(); } function Deferred() { var p = Promise._defer(); function resolve(x) { p._handler.resolve(x); } function reject(x) { p._handler.reject(x); } function notify(x) { p._handler.notify(x); } this.promise = p; this.resolve = resolve; this.reject = reject; this.notify = notify; this.resolver = { resolve: resolve, reject: reject, notify: notify }; } /** * Determines if x is promise-like, i.e. a thenable object * NOTE: Will return true for *any thenable object*, and isn't truly * safe, since it may attempt to access the `then` property of x (i.e. * clever/malicious getters may do weird things) * @param {*} x anything * @returns {boolean} true if x is promise-like */ function isPromiseLike(x) { return x && typeof x.then === 'function'; } /** * Return a promise that will resolve only once all the supplied arguments * have resolved. The resolution value of the returned promise will be an array * containing the resolution values of each of the arguments. * @param {...*} arguments may be a mix of promises and values * @returns {Promise} */ function join(/* ...promises */) { return Promise.all(arguments); } /** * Return a promise that will fulfill once all input promises have * fulfilled, or reject when any one input promise rejects. * @param {array|Promise} promises array (or promise for an array) of promises * @returns {Promise} */ function all(promises) { return when(promises, Promise.all); } /** * Return a promise that will always fulfill with an array containing * the outcome states of all input promises. The returned promise * will only reject if `promises` itself is a rejected promise. * @param {array|Promise} promises array (or promise for an array) of promises * @returns {Promise} promise for array of settled state descriptors */ function settle(promises) { return when(promises, Promise.settle); } /** * Promise-aware array map function, similar to `Array.prototype.map()`, * but input array may contain promises or values. * @param {Array|Promise} promises array of anything, may contain promises and values * @param {function(x:*, index:Number):*} mapFunc map function which may * return a promise or value * @returns {Promise} promise that will fulfill with an array of mapped values * or reject if any input promise rejects. */ function map(promises, mapFunc) { return when(promises, function(promises) { return Promise.map(promises, mapFunc); }); } /** * Filter the provided array of promises using the provided predicate. Input may * contain promises and values * @param {Array|Promise} promises array of promises and values * @param {function(x:*, index:Number):boolean} predicate filtering predicate. * Must return truthy (or promise for truthy) for items to retain. * @returns {Promise} promise that will fulfill with an array containing all items * for which predicate returned truthy. */ function filter(promises, predicate) { return when(promises, function(promises) { return Promise.filter(promises, predicate); }); } return when; }); })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); }); },{"./lib/Promise":55,"./lib/TimeoutError":57,"./lib/apply":58,"./lib/decorators/array":59,"./lib/decorators/flow":60,"./lib/decorators/fold":61,"./lib/decorators/inspect":62,"./lib/decorators/iterate":63,"./lib/decorators/progress":64,"./lib/decorators/timed":65,"./lib/decorators/unhandledRejection":66,"./lib/decorators/with":67}],79:[function(require,module,exports){ /** * Module dependencies. */ var global = (function() { return this; })(); /** * WebSocket constructor. */ var WebSocket = global.WebSocket || global.MozWebSocket; /** * Module exports. */ module.exports = WebSocket ? ws : null; /** * WebSocket constructor. * * The third `opts` options object gets ignored in web browsers, since it's * non-standard, and throws a TypeError if passed to the constructor. * See: https://github.com/einaros/ws/issues/227 * * @param {String} uri * @param {Array} protocols (optional) * @param {Object) opts (optional) * @api public */ function ws(uri, protocols, opts) { var instance; if (protocols) { instance = new WebSocket(uri, protocols); } else { instance = new WebSocket(uri); } return instance; } if (WebSocket) ws.prototype = WebSocket.prototype; },{}],80:[function(require,module,exports){ module.exports={ "name": "autobahn", "version": "0.9.7", "description": "An implementation of The Web Application Messaging Protocol (WAMP).", "main": "index.js", "scripts": { "test": "nodeunit test/test.js" }, "dependencies": { "when": ">= 2.8.0", "ws": ">= 0.4.31", "crypto-js": ">= 3.1.2-2" }, "devDependencies": { "browserify": ">= 3.28.1", "nodeunit": ">= 0.8.6" }, "repository": { "type": "git", "url": "git://github.com/crossbario/autobahn-js.git" }, "keywords": [ "WAMP", "WebSocket", "RPC", "PubSub" ], "author": "Tavendo GmbH", "license": "MIT" } },{}]},{},[4])(4) });
Dynalon/autobahn-js
test/detectenvironment/autobahn.js
JavaScript
mit
441,739
import React from 'react'; import { dummyDate } from '../../../.storybook/helpers'; import { BuildEnvironmentSection } from './BuildEnvironmentSection'; export default { title: 'admin/info/BuildEnvironmentSection', component: BuildEnvironmentSection, decorators: [ (fn) => <div className='rc-old'>{fn()}</div>, ], }; const info = { compile: { platform: 'info.compile.platform', arch: 'info.compile.arch', osRelease: 'info.compile.osRelease', nodeVersion: 'info.compile.nodeVersion', date: dummyDate, }, }; export const _default = () => <BuildEnvironmentSection info={info} />;
Sing-Li/Rocket.Chat
client/admin/info/BuildEnvironmentSection.stories.js
JavaScript
mit
599
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "ноль", ONE: "один", TWO: "два", FEW: "несколько", MANY: "много", OTHER: "другие"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "до полудня", "после полудня" ], "DAY": [ "Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Патница", "Суббота" ], "ERANAMES": [ "До Рождества Христова", "Нашей Эры" ], "ERAS": [ "BC", "AD" ], "FIRSTDAYOFWEEK": 6, "MONTH": [ "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь" ], "SHORTDAY": [ "Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб" ], "SHORTMONTH": [ "Янв", "Фев", "Март", "Апр", "Май", "Июн", "Июл", "Авг", "Сен", "Окт", "Ноя", "Дек" ], "STANDALONEMONTH": [ "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, MMMM d, y", "longDate": "MMMM d, y", "medium": "MMM d, y h:mm:ss a", "mediumDate": "MMM d, y", "mediumTime": "h:mm:ss a", "short": "d.m.yy h:mm a", "shortDate": "d.m.yy", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "Р", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "ru", "localeID": "ru", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
dwalin93/OSeM-Projekt
dist/translations/angular/angular-locale_ru.js
JavaScript
mit
3,049
var _ = require('../util.js'); function simpleDiff(now, old){ var nlen = now.length; var olen = old.length; if(nlen !== olen){ return true; } for(var i = 0; i < nlen ; i++){ if(now[i] !== old[i]) return true; } return false } function equals(a,b){ return a === b; } // array1 - old array // array2 - new array function ld(array1, array2, equalFn){ var n = array1.length; var m = array2.length; var equalFn = equalFn || equals; var matrix = []; for(var i = 0; i <= n; i++){ matrix.push([i]); } for(var j=1;j<=m;j++){ matrix[0][j]=j; } for(var i = 1; i <= n; i++){ for(var j = 1; j <= m; j++){ if(equalFn(array1[i-1], array2[j-1])){ matrix[i][j] = matrix[i-1][j-1]; }else{ matrix[i][j] = Math.min( matrix[i-1][j]+1, //delete matrix[i][j-1]+1//add ) } } } return matrix; } // arr2 - new array // arr1 - old array function diffArray(arr2, arr1, diff, diffFn) { if(!diff) return simpleDiff(arr2, arr1); var matrix = ld(arr1, arr2, diffFn) var n = arr1.length; var i = n; var m = arr2.length; var j = m; var edits = []; var current = matrix[i][j]; while(i>0 || j>0){ // the last line if (i === 0) { edits.unshift(3); j--; continue; } // the last col if (j === 0) { edits.unshift(2); i--; continue; } var northWest = matrix[i - 1][j - 1]; var west = matrix[i - 1][j]; var north = matrix[i][j - 1]; var min = Math.min(north, west, northWest); if (min === west) { edits.unshift(2); //delete i--; current = west; } else if (min === northWest ) { if (northWest === current) { edits.unshift(0); //no change } else { edits.unshift(1); //update current = northWest; } i--; j--; } else { edits.unshift(3); //add j--; current = north; } } var LEAVE = 0; var ADD = 3; var DELELE = 2; var UPDATE = 1; var n = 0;m=0; var steps = []; var step = {index: null, add:0, removed:[]}; for(var i=0;i<edits.length;i++){ if(edits[i] > 0 ){ // NOT LEAVE if(step.index === null){ step.index = m; } } else { //LEAVE if(step.index != null){ steps.push(step) step = {index: null, add:0, removed:[]}; } } switch(edits[i]){ case LEAVE: n++; m++; break; case ADD: step.add++; m++; break; case DELELE: step.removed.push(arr1[n]) n++; break; case UPDATE: step.add++; step.removed.push(arr1[n]) n++; m++; break; } } if(step.index != null){ steps.push(step) } return steps } // diffObject // ---- // test if obj1 deepEqual obj2 function diffObject( now, last, diff ){ if(!diff){ for( var j in now ){ if( last[j] !== now[j] ) return true } for( var n in last ){ if(last[n] !== now[n]) return true; } }else{ var nKeys = _.keys(now); var lKeys = _.keys(last); /** * [description] * @param {[type]} a [description] * @param {[type]} b){ return now[b] [description] * @return {[type]} [description] */ return diffArray(nKeys, lKeys, diff, function(a, b){ return now[b] === last[a]; }); } return false; } module.exports = { diffArray: diffArray, diffObject: diffObject }
zyy7259/regular-strap
third/regular/src/helper/diff.js
JavaScript
mit
3,523
!((document, $) => { 'use strict'; var keys = { ARROWS: [37, 38, 39, 40], ARROW_LEFT: 37, ARROW_UP: 38, ARROW_RIGHT: 39, ARROW_DOWN: 40, ENTER: 13, SPACE: 32, PAGE_UP: 33, PAGE_DOWN: 34 }; /** @param {Object} startTab - The tab to start searching from. @param {Object} $list - A list of nav buttons as a jQuery object. @param {Object} key - The triggering key code. @returns {Object} - The tab to the left or right of `startTab`. */ function findAdjacentTab(startTab, $list, key) { var dir = (key === keys.ARROW_LEFT || key === keys.ARROW_UP) ? 'prev' : 'next'; var adjacentTab = (dir === 'prev') ? $(startTab.parentNode) .prev()[0] : $(startTab.parentNode) .next()[0]; if (!adjacentTab) { var allTabs = $list.find('.tabs__nav-item'); if (dir === 'prev') { adjacentTab = allTabs[allTabs.length - 1]; } else { adjacentTab = allTabs[0]; } } return $(adjacentTab) .find('.tabs__nav-trigger')[0]; } /** @param {Object} newActive - Tab to be made active. @param {Object} $list - A list of nav buttons as a jQuery object. @returns {undefined} */ function setActiveAndInactive(newActive, $list) { $list.find('.tabs__nav-item') .each(function () { var assocPanelID = $(this) .find('.tabs__nav-trigger') .first() .attr('aria-controls'); var anchor = $(this) .find('.tabs__nav-trigger')[0]; if (this !== newActive.parentNode) { $(this) .removeClass('is-active'); anchor.tabIndex = -1; anchor.setAttribute('aria-selected', 'false'); $('#' + assocPanelID) .removeClass('is-current') .attr('aria-hidden', 'true'); } else { $(this) .addClass('is-active'); anchor.tabIndex = 0; anchor.setAttribute('aria-selected', 'true'); $('#' + assocPanelID) .addClass('is-current') .removeAttr('aria-hidden'); } }); } var $allTabGroups = $('.tabs'); $allTabGroups.each(function () { var $tabs = $(this); var $navlist = $tabs.find('.tabs__navlist'); $navlist.on('keydown', '.tabs__nav-item .tabs__nav-trigger', function (keyVent) { var which = keyVent.which; var target = keyVent.target; if ($.inArray(which, keys.ARROWS) > -1) { var adjacentTab = findAdjacentTab(target, $navlist, which); if (adjacentTab) { keyVent.preventDefault(); adjacentTab.focus(); setActiveAndInactive(adjacentTab, $navlist); } } else if (which === keys.ENTER || which === keys.SPACE) { keyVent.preventDefault(); target.click(); } else if (which === keys.PAGE_DOWN) { keyVent.preventDefault(); var assocPanel = $('#' + this.getAttribute('aria-controls')); if (assocPanel) { assocPanel.focus(); } } } ); // Click support $navlist.on('click', '.tabs__nav-item .tabs__nav-trigger', function () { var currentTarget = $navlist.find('.tabs__nav-item.is-active .tabs__nav-trigger')[0]; if (currentTarget !== $(this)[0]) { var eventData = { 'previousTarget': currentTarget, 'newTarget': $(this)[0] }; var event = new CustomEvent('rb.tabs.tabChanged', { detail: eventData }); $(this)[0].dispatchEvent(event); } setActiveAndInactive(this, $navlist); }); }); $(document.body) .on('keydown', '.tabs__panel', function (e) { if (e.which === keys.PAGE_UP) { e.preventDefault(); var $navlist = $(this) .closest('.tabs') .find('.tabs__navlist'); var activeTab = $navlist .find('.tabs__nav-item.is-active .tabs__nav-trigger')[0]; if (activeTab) { activeTab.focus(); } } }); })(document, jQuery);
cehfisher/a11y-style-guide
src/global/js/tabs.js
JavaScript
mit
4,138
var page=new WebPage,system=require("system"),slideWidth=system.args[3]?system.args[3].split("x")[0]:960,slideHeight=system.args[3]?system.args[3].split("x")[1]:700;page.viewportSize={width:slideWidth,height:slideHeight};page.paperSize={width:Math.round(2*slideWidth),height:Math.round(2*slideHeight),border:0};var inputFile=system.args[1]||"index.html?print-pdf",outputFile=system.args[2]||"slides.pdf";null===outputFile.match(/\.pdf$/gi)&&(outputFile+=".pdf"); console.log("Printing PDF (Paper size: "+page.paperSize.width+"x"+page.paperSize.height+")");page.open(inputFile,function(a){window.setTimeout(function(){console.log("Printed successfully");page.render(outputFile);phantom.exit()},1E3)});
fvizeus/fvizeus.github.io
plugin/print-pdf/print-pdf.js
JavaScript
mit
700
export function isOffline( state ) { return ( state.application.connectionState === 'OFFLINE' ) } export function isOnline( state ) { return ( state.application.connectionState === 'ONLINE' ) }
Kimsangcheon/wp-calypso
client/state/application/selectors.js
JavaScript
gpl-2.0
199
(function ($, document, window) { function reloadList(page) { ApiClient.getScheduledTasks({ isHidden: false }).done(function (tasks) { populateList(page, tasks); Dashboard.hideLoadingMsg(); }); } function populateList(page, tasks) { tasks = tasks.sort(function (a, b) { a = a.Category + " " + a.Name; b = b.Category + " " + b.Name; if (a == b) { return 0; } if (a < b) { return -1; } return 1; }); var html = ""; html += '<ul data-role="listview" data-inset="true" data-auto-enhanced="false" data-split-icon="Play">'; var currentCategory; for (var i = 0, length = tasks.length; i < length; i++) { var task = tasks[i]; if (task.Category != currentCategory) { currentCategory = task.Category; html += "<li data-role='list-divider'>" + currentCategory + "</li>"; } html += "<li title='" + task.Description + "'>"; html += "<a href='scheduledtask.html?id=" + task.Id + "'>"; html += "<h3>" + task.Name + "</h3>"; html += "<p id='" + task.Id + "'>" + getTaskProgressHtml(task) + "</p>"; if (task.State == "Idle") { html += "<a id='btnTask" + task.Id + "' class='btnStartTask' href='#' data-taskid='" + task.Id + "' data-icon='play'>" + Globalize.translate('ButtonStart') + "</a>"; } else if (task.State == "Running") { html += "<a id='btnTask" + task.Id + "' class='btnStopTask' href='#' data-taskid='" + task.Id + "' data-icon='stop'>" + Globalize.translate('ButtonStop') + "</a>"; } else { html += "<a id='btnTask" + task.Id + "' class='btnStartTask' href='#' data-taskid='" + task.Id + "' data-icon='play' style='display:none;'>" + Globalize.translate('ButtonStart') + "</a>"; } html += "</a>"; html += "</li>"; } html += "</ul>"; $('#divScheduledTasks', page).html(html).trigger('create'); } function getTaskProgressHtml(task) { var html = ''; if (task.State == "Idle") { if (task.LastExecutionResult) { html += Globalize.translate('LabelScheduledTaskLastRan').replace("{0}", humane_date(task.LastExecutionResult.EndTimeUtc)) .replace("{1}", humane_elapsed(task.LastExecutionResult.StartTimeUtc, task.LastExecutionResult.EndTimeUtc)); if (task.LastExecutionResult.Status == "Failed") { html += " <span style='color:#FF0000;'>" + Globalize.translate('LabelFailed') + "</span>"; } else if (task.LastExecutionResult.Status == "Cancelled") { html += " <span style='color:#0026FF;'>" + Globalize.translate('LabelCancelled') + "</span>"; } else if (task.LastExecutionResult.Status == "Aborted") { html += " <span style='color:#FF0000;'>" + Globalize.translate('LabelAbortedByServerShutdown') + "</span>"; } } } else if (task.State == "Running") { var progress = (task.CurrentProgressPercentage || 0).toFixed(1); html += '<progress max="100" value="' + progress + '" title="' + progress + '%">'; html += '' + progress + '%'; html += '</progress>'; html += "<span style='color:#009F00;margin-left:5px;'>" + progress + "%</span>"; } else { html += "<span style='color:#FF0000;'>" + Globalize.translate('LabelStopping') + "</span>"; } return html; } function onWebSocketMessage(e, msg) { if (msg.MessageType == "ScheduledTasksInfo") { var tasks = msg.Data; var page = $.mobile.activePage; updateTasks(page, tasks); } } function updateTasks(page, tasks) { for (var i = 0, length = tasks.length; i < length; i++) { var task = tasks[i]; $('#' + task.Id, page).html(getTaskProgressHtml(task)); var btnTask = $('#btnTask' + task.Id, page); updateTaskButton(btnTask, task.State); } } function updateTaskButton(btnTask, state) { var elem; if (state == "Idle") { elem = btnTask.addClass('btnStartTask').removeClass('btnStopTask').show().data("icon", "play").attr("title", Globalize.translate('ButtonStart')); elem.removeClass('ui-icon-stop').addClass('ui-icon-play'); } else if (state == "Running") { elem = btnTask.addClass('btnStopTask').removeClass('btnStartTask').show().data("icon", "stop").attr("title", Globalize.translate('ButtonStop')); elem.removeClass('ui-icon-play').addClass('ui-icon-stop'); } else { elem = btnTask.addClass('btnStartTask').removeClass('btnStopTask').hide().data("icon", "play").attr("title", Globalize.translate('ButtonStart')); elem.removeClass('ui-icon-stop').addClass('ui-icon-play'); } } function onWebSocketConnectionOpen() { startInterval(); reloadList($.mobile.activePage); } function startInterval() { if (ApiClient.isWebSocketOpen()) { ApiClient.sendWebSocketMessage("ScheduledTasksInfoStart", "1000,1000"); } } function stopInterval() { if (ApiClient.isWebSocketOpen()) { ApiClient.sendWebSocketMessage("ScheduledTasksInfoStop"); } } $(document).on('pageshow', "#scheduledTasksPage", function () { var page = this; Dashboard.showLoadingMsg(); startInterval(); reloadList(page); $(ApiClient).on("websocketmessage", onWebSocketMessage).on("websocketopen", onWebSocketConnectionOpen); $('#divScheduledTasks', page).on('click', '.btnStartTask', function () { var button = this; var id = button.getAttribute('data-taskid'); ApiClient.startScheduledTask(id).done(function () { updateTaskButton($(button), "Running"); reloadList(page); }); }).on('click', '.btnStopTask', function () { var button = this; var id = button.getAttribute('data-taskid'); ApiClient.stopScheduledTask(id).done(function () { updateTaskButton($(button), ""); reloadList(page); }); }); }).on('pagehide', "#scheduledTasksPage", function () { var page = this; $(ApiClient).off("websocketmessage", onWebSocketMessage).off("websocketopen", onWebSocketConnectionOpen); stopInterval(); $('#divScheduledTasks', page).off('click', '.btnStartTask').off('click', '.btnStopTask'); }); })(jQuery, document, window);
hamstercat/Emby
MediaBrowser.WebDashboard/dashboard-ui/scripts/scheduledtaskspage.js
JavaScript
gpl-2.0
7,041
export { EncounterArmor } from './encounter_armor.js'; export { EncounterCoins } from './encounter_coins.js'; export { EncounterItem } from './encounter_item.js'; export { EncounterMagicItem } from './encounter_magic_item.js'; export { EncounterWeapon } from './encounter_weapon.js'; export { EnvironmentSection } from './environment_section.js'; export { Environment } from './environment.js'; export { MapsAndImagesSection } from './maps_and_images_section.js'; export { MonsterAbilityScore } from './monster_ability_score.js'; export { MonsterSection } from './monster_section.js'; export { Monster } from './monster.js'; export { NotesSection } from './notes_section.js'; export { NPCSection } from './npc_section.js'; export { NPC } from './npc.js'; export { PlayerTextSection } from './player_text_section.js'; export { PlayerText } from './player_text.js'; export { PointOfInterestSection } from './point_of_interest_section.js'; export { PointOfInterest } from './point_of_interest.js'; export { TreasureSection } from './treasure_section.js';
charactersheet/charactersheet
src/charactersheet/models/dm/encounter_sections/index.js
JavaScript
gpl-2.0
1,069
// we create the global game object, an instance of Phaser.Game var game = new Phaser.Game(800, 500, Phaser.AUTO, 'world',null,true,true,null); // the first parameter is the key you use to jump between stated // the key must be unique within the state manager // the second parameter is the object that contains the state code // these come from the js files we included in the head tag in the html file game.state.add('State001', bonsanto.State001); game.state.add('State002', bonsanto.State002); game.state.add('State003', bonsanto.State003); game.state.start('State001');
Techbot/JiGS-PHP-RPG-engine
legacy/components/com_battle/views/plate/tmpl/026a_bonsanto/script.js
JavaScript
gpl-2.0
584
FD50.plugin("bootstrap3", function($) { var jQuery = $; /*! * Bootstrap v3.0.3 (http://getbootstrap.com) * Copyright 2015 Twitter, Inc. * Licensed under http://www.apache.org/licenses/LICENSE-2.0 */ if (window["Foundry5/Bootstrap"]) { throw new Error("An instance of Bootstrap has been initialized before this.") } else { window["Foundry5/Bootstrap"] = { version: "3.0.3", foundry: jQuery } } /* ======================================================================== * Bootstrap: transition.js v3.0.3 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd' , 'MozTransition' : 'transitionend' , 'OTransition' : 'oTransitionEnd otransitionend' , 'transition' : 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function (duration) { var called = false, $el = this $(this).one($.support.transition.end, function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() }) }(jQuery); /* ======================================================================== * Bootstrap: alert.js v3.0.3 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-bp-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.hasClass('alert') ? $this : $this.parent() } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { $parent.trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one($.support.transition.end, removeElement) .emulateTransitionEnd(150) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= var old = $.fn.alert $.fn.alert = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.0.3 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) } Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state = state + 'Text' if (!data.resetText) $el.data('resetText', $el[val]()) $el[val](data[state] || this.options[state]) // push to event loop to allow forms to submit setTimeout(function () { state == 'loadingText' ? $el.addClass(d).attr(d, d) : $el.removeClass(d).removeAttr(d); }, 0) } Button.prototype.toggle = function () { var $parent = this.$element.closest('[data-bp-toggle="buttons"]') var changed = true if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') === 'radio') { // see if clicking on current one if ($input.prop('checked') && this.$element.hasClass('active')) changed = false else $parent.find('.active').removeClass('active') } if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change') } if (changed) this.$element.toggleClass('active') } // BUTTON PLUGIN DEFINITION // ======================== var old = $.fn.button $.fn.button = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document).on('click.bs.button.data-api', '[data-bp-toggle^=button]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') $btn.button('toggle') e.preventDefault() }) }(jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.0.3 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = this.sliding = this.interval = this.$active = this.$items = null this.options.pause == 'hover' && this.$element .on('mouseenter', $.proxy(this.pause, this)) .on('mouseleave', $.proxy(this.cycle, this)) } Carousel.DEFAULTS = { interval: 5000 , pause: 'hover' , wrap: true } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getActiveIndex = function () { this.$active = this.$element.find('.item.active') this.$items = this.$active.parent().children() return this.$items.index(this.$active) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getActiveIndex() if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition.end) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || $active[type]() var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var fallback = type == 'next' ? 'first' : 'last' var that = this if (!$next.length) { if (!this.options.wrap) return $next = this.$element.find('.item')[fallback]() } this.sliding = true isCycling && this.pause() var e = $.Event('slide.bs.carousel', { relatedTarget: $next[0], direction: direction }) if ($next.hasClass('active')) return if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') this.$element.one('slid.bs.carousel', function () { var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()]) $nextIndicator && $nextIndicator.addClass('active') }) } if ($.support.transition && this.$element.hasClass('slide')) { this.$element.trigger(e) if (e.isDefaultPrevented()) return $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one($.support.transition.end, function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger('slid.bs.carousel') }, 0) }) .emulateTransitionEnd(600) } else { this.$element.trigger(e) if (e.isDefaultPrevented()) return $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger('slid.bs.carousel') } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== var old = $.fn.carousel $.fn.carousel = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= $(document).on('click.bs.carousel.data-api', '[data-bp-slide], [data-bp-slide-to]', function (e) { var $this = $(this), href var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-bp-slide-to') if (slideIndex) options.interval = false $target.carousel(options) if (slideIndex = $this.attr('data-bp-slide-to')) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() }) $(window).on('load', function () { $('[data-bp-ride="carousel"]').each(function () { var $carousel = $(this) $carousel.carousel($carousel.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.0.3 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.transitioning = null if (this.options.parent) this.$parent = $(this.options.parent) if (this.options.toggle) this.toggle() } Collapse.DEFAULTS = { toggle: true } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var startEvent = $.Event('show.bs.collapse') this.$element.triggerHandler(startEvent) if (startEvent.isDefaultPrevented()) return var actives = this.$parent && this.$parent.find('> .panel > .in') if (actives && actives.length) { var hasData = actives.data('bs.collapse') if (hasData && hasData.transitioning) return actives.collapse('hide') hasData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing') [dimension](0) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('in') [dimension]('auto') this.transitioning = 0 this.$element.trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) [dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.triggerHandler(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element [dimension](this.$element[dimension]()) [0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse') .removeClass('in') this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .trigger('hidden.bs.collapse') .removeClass('collapsing') .addClass('collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } // COLLAPSE PLUGIN DEFINITION // ========================== var old = $.fn.collapse $.fn.collapse = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-bp-toggle=collapse]', function (e) { var $this = $(this), href var target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 var $target = $(target) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() var parent = $this.attr('data-parent') var $parent = parent && $(parent) if (!data || !data.transitioning) { if ($parent) $parent.find('[data-bp-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed') $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed') } $target.collapse(option) }) }(jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.0.3 * http://getbootstrap.com/javascript/#dropdowns * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-bp-toggle=dropdown]' var Dropdown = function (element) { $(element).on('click.bs.dropdown', this.toggle) } Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we use a backdrop because click events don't delegate $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus) } $parent.triggerHandler(e = $.Event('show.bs.dropdown')) if (e.isDefaultPrevented()) return $parent .toggleClass('open') .trigger('shown.bs.dropdown') $this.focus() } return false } Dropdown.prototype.keydown = function (e) { if (!/(38|40|27)/.test(e.keyCode)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if (!isActive || (isActive && e.keyCode == 27)) { if (e.which == 27) $parent.find(toggle).focus() return $this.click() } var $items = $('[role=menu] li:not(.divider):visible a', $parent) if (!$items.length) return var index = $items.index($items.filter(':focus')) if (e.keyCode == 38 && index > 0) index-- // up if (e.keyCode == 40 && index < $items.length - 1) index++ // down if (!~index) index=0 $items.eq(index).focus() } function clearMenus() { $(backdrop).remove() $(toggle).each(function (e) { var $parent = getParent($(this)) if (!$parent.hasClass('open')) return $parent.triggerHandler(e = $.Event('hide.bs.dropdown')) if (e.isDefaultPrevented()) return $parent.removeClass('open').trigger('hidden.bs.dropdown') }) } function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } // DROPDOWN PLUGIN DEFINITION // ========================== var old = $.fn.dropdown $.fn.dropdown = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.dropdown') if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown_ form, .dropdown-static', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api' , toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown) }(jQuery); /* ======================================================================== * Bootstrap: modal.js v3.0.3 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$element = $(element) this.$backdrop = this.isShown = null if (this.options.remote) this.$element.load(this.options.remote) } Modal.DEFAULTS = { backdrop: true , keyboard: true , show: true } Modal.prototype.toggle = function (_relatedTarget) { return this[!this.isShown ? 'show' : 'hide'](_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.triggerHandler(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.$element.on('click.dismiss.modal', '[data-bp-dismiss="modal"]', $.proxy(this.hide, this)) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) // don't move modals dom position } that.$element.show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$element.find('.modal-dialog') // wait for modal to slide in .one($.support.transition.end, function () { that.$element.focus().trigger(e) }) .emulateTransitionEnd(300) : that.$element.focus().trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.triggerHandler(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .attr('aria-hidden', true) .off('click.dismiss.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one($.support.transition.end, $.proxy(this.hideModal, this)) .emulateTransitionEnd(300) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.focus() } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keyup.dismiss.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.removeBackdrop() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) this.$element.on('click.dismiss.modal', $.proxy(function (e) { if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this) }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (callback) { callback() } } // MODAL PLUGIN DEFINITION // ======================= var old = $.fn.modal $.fn.modal = function (option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-bp-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 var option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) e.preventDefault() $target .modal(option, this) .one('hide', function () { $this.is(':visible') && $this.focus() }) }) $(document) .on('show.bs.modal', '.modal.bs', function () { $(document.body).addClass('modal-open') }) .on('hidden.bs.modal', '.modal.bs', function () { $(document.body).removeClass('modal-open') }) }(jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.0.3 * http://getbootstrap.com/javascript/#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = this.options = this.enabled = this.timeout = this.hoverState = this.$element = null this.init('tooltip', element, options) } Tooltip.DEFAULTS = { animation: true , placement: 'top' , selector: false , template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>' , trigger: 'hover focus' , title: '' , delay: 0 , html: false , container: false } Tooltip.prototype.init = function (type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--;) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focus' var eventOut = trigger == 'hover' ? 'mouseleave' : 'blur' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay , hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function () { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.'+ this.type) if (this.hasContent() && this.enabled) { this.$element.triggerHandler(e) if (e.isDefaultPrevented()) return var $tip = this.tip() this.setContent() if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement.split('-')[0]); this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var $parent = this.$element.parent() var orgPlacement = placement var docScroll = document.documentElement.scrollTop || document.body.scrollTop var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth() var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight() var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' : placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' : placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' : placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) this.$element.trigger('shown.bs.' + this.type) } } Tooltip.prototype.applyPlacement = function(offset, placement) { var replace var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top = offset.top + marginTop offset.left = offset.left + marginLeft $tip .offset(offset) .addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { replace = true offset.top = offset.top + height - actualHeight } if (['top', 'bottom'].indexOf(placement.split('-')[0]) === 0) { var delta = 0 if (offset.left < 0) { delta = offset.left * -2 offset.left = 0 $tip.offset(offset) actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight } this.replaceArrow(delta - width + actualWidth, actualWidth, 'left') } if (['left', 'right'].indexOf(placement.split('-')[0]) === 0) { this.replaceArrow(actualHeight - height, actualHeight, 'top') } if (replace) $tip.offset(offset) } Tooltip.prototype.replaceArrow = function(delta, dimension, position) { this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + "%") : '') } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function () { var that = this var $tip = this.tip() var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() } this.$element.triggerHandler(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && this.$tip.hasClass('fade') ? $tip .one($.support.transition.end, complete) .emulateTransitionEnd(150) : complete() this.$element.trigger('hidden.bs.' + this.type) return this } Tooltip.prototype.fixTitle = function () { var $e = this.$element if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function () { return this.getTitle() } Tooltip.prototype.getPosition = function () { var el = this.$element[0] return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : { width: el.offsetWidth , height: el.offsetHeight }, this.$element.offset()) } Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'left-top' ? { top: pos.top, left: pos.left - actualWidth } : placement == 'left-bottom' ? { top: pos.top + pos.height - actualHeight, left: pos.left - actualWidth } : placement == 'right-top' ? { top: pos.top, left: pos.left + pos.width } : placement == 'right-bottom' ? { top: pos.top + pos.height - actualHeight, left: pos.left + pos.width } : placement == 'top-left' ? { top: pos.top - actualHeight, left: pos.left } : placement == 'top-right' ? { top: pos.top - actualHeight, left: pos.left + pos.width - actualWidth } : placement == 'bottom-left' ? { top: pos.top + pos.height, left: pos.left } : placement == 'bottom-right' ? { top: pos.top + pos.height, left: pos.left + pos.width - actualWidth } : placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } } Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.tip = function () { return this.$tip = this.$tip || $(this.options.template) } Tooltip.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow') } Tooltip.prototype.validate = function () { if (!this.$element[0].parentNode) { this.hide() this.$element = null this.options = null } } Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = e ? $(e.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) : this self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } Tooltip.prototype.destroy = function () { this.hide().$element.off('.' + this.type).removeData('bs.' + this.type) } // TOOLTIP PLUGIN DEFINITION // ========================= var old = $.fn.tooltip $.fn.tooltip = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(jQuery); /* ======================================================================== * Bootstrap: popover.js v3.0.3 * http://getbootstrap.com/javascript/#popovers * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function (element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.DEFAULTS = $.extend({} , $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right' , trigger: 'click' , content: '' , template: '<div id="fd" class="fd-popover"><div class="arrow"></div><h3 class="fd-popover-title"></h3><div class="fd-popover-content"></div></div>' }) // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function () { return Popover.DEFAULTS } Popover.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() var content = this.getContent() $tip.find('.fd-popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.fd-popover-content')[this.options.html ? 'html' : 'text'](content) $tip.removeClass('fade top bottom left right in') // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.fd-popover-title').html()) $tip.find('.fd-popover-title').hide() } Popover.prototype.hasContent = function () { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function () { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find('.arrow') } Popover.prototype.tip = function () { if (!this.$tip) this.$tip = $(this.options.template) return this.$tip } // POPOVER PLUGIN DEFINITION // ========================= var old = $.fn.popover $.fn.popover = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option if (!data) $this.data('bs.popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.popover.Constructor = Popover // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.0.3 * http://getbootstrap.com/javascript/#scrollspy * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { var href var process = $.proxy(this.process, this) this.$element = $(element).is('body') ? $(window) : $(element) this.$body = $('body') this.$scrollElement = this.$element.on('scroll.bs.scroll-spy.data-api', process) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 || '') + ' .nav li > a' this.offsets = $([]) this.targets = $([]) this.activeTarget = null this.refresh() this.process() } ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.refresh = function () { var offsetMethod = this.$element[0] == window ? 'offset' : 'position' this.offsets = $([]) this.targets = $([]) var self = this var $targets = this.$body .find(this.selector) .map(function () { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#\w/.test(href) && $(href) return ($href && $href.length && [[ $href[offsetMethod]().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]]) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { self.offsets.push(this[0]) self.targets.push(this[1]) }) } ScrollSpy.prototype.process = function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight var maxScroll = scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (scrollTop >= maxScroll) { return activeTarget != (i = targets.last()[0]) && this.activate(i) } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate( targets[i] ) } } ScrollSpy.prototype.activate = function (target) { this.activeTarget = target $(this.selector) .parents('.active') .removeClass('active') var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') } // SCROLLSPY PLUGIN DEFINITION // =========================== var old = $.fn.scrollspy $.fn.scrollspy = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load', function () { $('[data-bp-spy="scroll"]').each(function () { var $spy = $(this) $spy.scrollspy($spy.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: tab.js v3.0.3 * http://getbootstrap.com/javascript/#tabs * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // TAB CLASS DEFINITION // ==================== var Tab = function (element) { this.element = $(element) } Tab.prototype.show = function () { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.data('target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } if ($this.parent('li').hasClass('active')) return var previous = $ul.find('.active:last a')[0] var e = $.Event('show.bs.tab', { relatedTarget: previous }) $this.triggerHandler(e) if (e.isDefaultPrevented()) return var $target = $(selector) this.activate($this.parent('li'), $ul) this.activate($target, $target.parent(), function () { $this.trigger({ type: 'shown.bs.tab' , relatedTarget: previous }) }) } Tab.prototype.activate = function (element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && $active.hasClass('fade') function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') element.addClass('active') if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu')) { element.closest('li.dropdown').addClass('active') } callback && callback() } transition ? $active .one($.support.transition.end, next) .emulateTransitionEnd(150) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== var old = $.fn.tab $.fn.tab = function ( option ) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function () { $.fn.tab = old return this } // TAB DATA-API // ============ $(document).on('click.bs.tab.data-api', '[data-bp-toggle="tab"], [data-bp-toggle="pill"]', function (e) { e.preventDefault() $(this).tab('show') }) }(jQuery); /* ======================================================================== * Bootstrap: affix.js v3.0.3 * http://getbootstrap.com/javascript/#affix * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // AFFIX CLASS DEFINITION // ====================== var Affix = function (element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$window = $(window) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = this.unpin = null this.checkPosition() } Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0 } Affix.prototype.checkPositionWithEventLoop = function () { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var scrollHeight = $(document).height() var scrollTop = this.$window.scrollTop() var position = this.$element.offset() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top() if (typeof offsetBottom == 'function') offsetBottom = offset.bottom() var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' : offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false if (this.affixed === affix) return if (this.unpin) this.$element.css('top', '') this.affixed = affix this.unpin = affix == 'bottom' ? position.top - scrollTop : null this.$element.removeClass(Affix.RESET).addClass('affix' + (affix ? '-' + affix : '')) if (affix == 'bottom') { this.$element.offset({ top: document.body.offsetHeight - offsetBottom - this.$element.height() }) } } // AFFIX PLUGIN DEFINITION // ======================= var old = $.fn.affix $.fn.affix = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function () { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function () { $('[data-bp-spy="affix"]').each(function () { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom) data.offset.bottom = data.offsetBottom if (data.offsetTop) data.offset.top = data.offsetTop $spy.affix(data) }) }) }(jQuery); /** * bootstrap-notify.js v1.0 * -- * http://twitter.com/nijikokun * Copyright 2012 Nijiko Yonskai, Goodybag * -- * 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. */ !function ($) { var Notification = function (element, options) { // Element collection this.$element = $(element); this.$note = $('<div class="alert"></div>'); this.options = $.extend(true, $.fn.notify.defaults, options); // Setup from options if(this.options.transition) if(this.options.transition == 'fade') this.$note.addClass('in').addClass(this.options.transition); else this.$note.addClass(this.options.transition); else this.$note.addClass('fade').addClass('in'); if(this.options.type) this.$note.addClass('alert-' + this.options.type); else this.$note.addClass('alert-success'); if(!this.options.message && this.$element.data("message") !== '') // dom text this.$note.html(this.$element.data("message")); else if(typeof this.options.message === 'object') if(this.options.message.html) this.$note.html(this.options.message.html); else if(this.options.message.text) this.$note.text(this.options.message.text); else this.$note.html(this.options.message); if(this.options.closable) var link = $('<a class="close pull-right" href="javascript: void(0);">&times;</a>'); $(link).on('click', $.proxy(onClose, this)); this.$note.prepend(link); return this; }; onClose = function() { this.options.onClose(); $(this.$note).remove(); this.options.onClosed(); }; Notification.prototype.show = function () { if(this.options.fadeOut.enabled) this.$note.delay(this.options.fadeOut.delay || 3000).fadeOut('slow', $.proxy(onClose, this)); this.$element.append(this.$note); this.$note.alert(); }; Notification.prototype.hide = function () { if(this.options.fadeOut.enabled) this.$note.delay(this.options.fadeOut.delay || 3000).fadeOut('slow', $.proxy(onClose, this)); else onClose.call(this); }; $.fn.notify = function (options) { return new Notification(this, options); }; $.fn.notify.defaults = { type: 'success', closable: true, transition: 'fade', fadeOut: { enabled: true, delay: 3000 }, message: null, onClose: function () {}, onClosed: function () {} } }($); });
BetterBetterBetter/B3App
media/foundry/5.0/scripts/bootstrap3.js
JavaScript
gpl-2.0
62,727
/* Switch-spec.js * * copyright (c) 2010-2022, Christian Mayer and the CometVisu contributers. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ /** * Unit tests for switch widget * * @author Tobias Bräutigam * @since 2016 */ describe('testing a switch', function() { it('should test the switch creator', function() { var res = this.createTestElement('switch', {flavour: 'potassium'}, '<label>Test</label>'); var switchWidget = Array.from(res.getDomElement().children).filter(function(m) { return m.matches('.switch'); })[0]; expect(switchWidget).toHaveFlavour('potassium'); var actor = res.getActor(); expect(actor).not.toBeNull(); expect(actor).toHaveClass('switchUnpressed'); expect(actor).not.toHaveClass('switchPressed'); var value = res.getValueElement(); expect(value).not.toBeNull(); expect(value.innerText).toBe('-'); var label = Array.from(switchWidget.children).filter(function(m) { return m.matches('.label'); })[0]; expect(label).not.toBeNull(); expect(label.innerText).toBe('Test'); expect(res.getOnValue()).toBe('1'); expect(res.getOffValue()).toBe('0'); }); it('should test the switch creator with different on/off values', function() { var res = this.createTestElement('switch', {on_value: 'turn_on', off_value: 'turn_off'}); expect(res.getOnValue()).toBe('turn_on'); expect(res.getOffValue()).toBe('turn_off'); }); it('should update a switch', function() { var res = this.createTestElement('switch', {}, '<label>Test</label>'); res.update('12/7/37', 1); var actor = res.getActor(); expect(actor).not.toBe(null); expect(actor).toHaveClass('switchPressed'); expect(actor).not.toHaveClass('switchUnpressed'); res.update('12/7/37', 0); expect(actor).toHaveClass('switchUnpressed'); expect(actor).not.toHaveClass('switchPressed'); }); it('should trigger the switch action', function() { var res = this.createTestElement('switch', {}, '<label>Test</label>'); this.initWidget(res); spyOn(res, 'sendToBackend'); var actor = res.getActor(); expect(actor).not.toBe(null); var Reg = qx.event.Registration; res.update('12/7/37', 0); Reg.fireEvent(actor, 'tap', qx.event.type.Event, []); expect(res.sendToBackend).toHaveBeenCalledWith('1'); res.update('12/7/37', 1); Reg.fireEvent(actor, 'tap', qx.event.type.Event, []); expect(res.sendToBackend).toHaveBeenCalledWith('0'); }); });
ChristianMayer/CometVisu
source/test/karma/ui/structure/pure/Switch-spec.js
JavaScript
gpl-3.0
3,171
var classgr__base__error__handler = [ [ "gr_base_error_handler", "classgr__base__error__handler.html#ad4b18ebae96256e537650772dd3cb1f6", null ], [ "count_error", "classgr__base__error__handler.html#a840a56a5d19b2269ea9328ba54bd4236", null ], [ "nerrors", "classgr__base__error__handler.html#a828a9e2ea41d6e6a6a5f46f2097a67c7", null ], [ "nwarnings", "classgr__base__error__handler.html#a7567f2ef1370cb0f71d2ea204fd16968", null ], [ "reset_counts", "classgr__base__error__handler.html#a6d7cc692da78d6eeece40d0733e3998a", null ] ];
aviralchandra/Sandhi
build/gr36/docs/doxygen/html/classgr__base__error__handler.js
JavaScript
gpl-3.0
549
/*! * Bootstrap v3.3.6 (http://getbootstrap.com) * Copyright 2011-2015 Twitter, Inc. * Licensed under the MIT license */ if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery') } +function ($) { 'use strict'; var version = $.fn.jquery.split(' ')[0].split('.') if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 2)) { throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3') } }(jQuery); /* ======================================================================== * Bootstrap: transition.js v3.3.6 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { WebkitTransition: 'webkitTransitionEnd', MozTransition: 'transitionend', OTransition: 'oTransitionEnd otransitionend', transition: 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return {end: transEndEventNames[name]} } } return false // explicit for ie8 ( ._.) } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function (duration) { var called = false var $el = this $(this).one('bsTransitionEnd', function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() if (!$.support.transition) return $.event.special.bsTransitionEnd = { bindType: $.support.transition.end, delegateType: $.support.transition.end, handle: function (e) { if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments) } } }) }(jQuery); /* ======================================================================== * Bootstrap: alert.js v3.3.6 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.VERSION = '3.3.6' Alert.TRANSITION_DURATION = 150 Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.closest('.alert') } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { // detach from parent, fire event then clean up data $parent.detach().trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one('bsTransitionEnd', removeElement) .emulateTransitionEnd(Alert.TRANSITION_DURATION) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.alert $.fn.alert = Plugin $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.3.6 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) this.isLoading = false } Button.VERSION = '3.3.6' Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state += 'Text' if (data.resetText == null) $el.data('resetText', $el[val]()) // push to event loop to allow forms to submit setTimeout($.proxy(function () { $el[val](data[state] == null ? this.options[state] : data[state]) if (state == 'loadingText') { this.isLoading = true $el.addClass(d).attr(d, d) } else if (this.isLoading) { this.isLoading = false $el.removeClass(d).removeAttr(d) } }, this), 0) } Button.prototype.toggle = function () { var changed = true var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') == 'radio') { if ($input.prop('checked')) changed = false $parent.find('.active').removeClass('active') this.$element.addClass('active') } else if ($input.prop('type') == 'checkbox') { if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false this.$element.toggleClass('active') } $input.prop('checked', this.$element.hasClass('active')) if (changed) $input.trigger('change') } else { this.$element.attr('aria-pressed', !this.$element.hasClass('active')) this.$element.toggleClass('active') } } // BUTTON PLUGIN DEFINITION // ======================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } var old = $.fn.button $.fn.button = Plugin $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document) .on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') Plugin.call($btn, 'toggle') if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) e.preventDefault() }) .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) { $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type)) }) }(jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.3.6 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = null this.sliding = null this.interval = null this.$active = null this.$items = null this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this)) this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element .on('mouseenter.bs.carousel', $.proxy(this.pause, this)) .on('mouseleave.bs.carousel', $.proxy(this.cycle, this)) } Carousel.VERSION = '3.3.6' Carousel.TRANSITION_DURATION = 600 Carousel.DEFAULTS = { interval: 5000, pause: 'hover', wrap: true, keyboard: true } Carousel.prototype.keydown = function (e) { if (/input|textarea/i.test(e.target.tagName)) return switch (e.which) { case 37: this.prev(); break case 39: this.next(); break default: return } e.preventDefault() } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getItemIndex = function (item) { this.$items = item.parent().children('.item') return this.$items.index(item || this.$active) } Carousel.prototype.getItemForDirection = function (direction, active) { var activeIndex = this.getItemIndex(active) var willWrap = (direction == 'prev' && activeIndex === 0) || (direction == 'next' && activeIndex == (this.$items.length - 1)) if (willWrap && !this.options.wrap) return active var delta = direction == 'prev' ? -1 : 1 var itemIndex = (activeIndex + delta) % this.$items.length return this.$items.eq(itemIndex) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active')) if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid" if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos)) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || this.getItemForDirection(type, $active) var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var that = this if ($next.hasClass('active')) return (this.sliding = false) var relatedTarget = $next[0] var slideEvent = $.Event('slide.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) this.$element.trigger(slideEvent) if (slideEvent.isDefaultPrevented()) return this.sliding = true isCycling && this.pause() if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)]) $nextIndicator && $nextIndicator.addClass('active') } var slidEvent = $.Event('slid.bs.carousel', {relatedTarget: relatedTarget, direction: direction}) // yes, "slid" if ($.support.transition && this.$element.hasClass('slide')) { $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one('bsTransitionEnd', function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger(slidEvent) }, 0) }) .emulateTransitionEnd(Carousel.TRANSITION_DURATION) } else { $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger(slidEvent) } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } var old = $.fn.carousel $.fn.carousel = Plugin $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= var clickHandler = function (e) { var href var $this = $(this) var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7 if (!$target.hasClass('carousel')) return var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false Plugin.call($target, options) if (slideIndex) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() } $(document) .on('click.bs.carousel.data-api', '[data-slide]', clickHandler) .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) Plugin.call($carousel, $carousel.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.3.6 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' + '[data-toggle="collapse"][data-target="#' + element.id + '"]') this.transitioning = null if (this.options.parent) { this.$parent = this.getParent() } else { this.addAriaAndCollapsedClass(this.$element, this.$trigger) } if (this.options.toggle) this.toggle() } Collapse.VERSION = '3.3.6' Collapse.TRANSITION_DURATION = 350 Collapse.DEFAULTS = { toggle: true } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var activesData var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing') if (actives && actives.length) { activesData = actives.data('bs.collapse') if (activesData && activesData.transitioning) return } var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return if (actives && actives.length) { Plugin.call(actives, 'hide') activesData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing')[dimension](0) .attr('aria-expanded', true) this.$trigger .removeClass('collapsed') .attr('aria-expanded', true) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('collapse in')[dimension]('') this.transitioning = 0 this.$element .trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element[dimension](this.$element[dimension]())[0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse in') .attr('aria-expanded', false) this.$trigger .addClass('collapsed') .attr('aria-expanded', false) this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .removeClass('collapsing') .addClass('collapse') .trigger('hidden.bs.collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } Collapse.prototype.getParent = function () { return $(this.options.parent) .find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]') .each($.proxy(function (i, element) { var $element = $(element) this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element) }, this)) .end() } Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) { var isOpen = $element.hasClass('in') $element.attr('aria-expanded', isOpen) $trigger .toggleClass('collapsed', !isOpen) .attr('aria-expanded', isOpen) } function getTargetFromTrigger($trigger) { var href var target = $trigger.attr('data-target') || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7 return $(target) } // COLLAPSE PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.collapse $.fn.collapse = Plugin $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) { var $this = $(this) if (!$this.attr('data-target')) e.preventDefault() var $target = getTargetFromTrigger($this) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() Plugin.call($target, option) }) }(jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.3.6 * http://getbootstrap.com/javascript/#dropdowns * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle="dropdown"]' var Dropdown = function (element) { $(element).on('click.bs.dropdown', this.toggle) } Dropdown.VERSION = '3.3.6' function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } function clearMenus(e) { if (e && e.which === 3) return $(backdrop).remove() $(toggle).each(function () { var $this = $(this) var $parent = getParent($this) var relatedTarget = {relatedTarget: this} if (!$parent.hasClass('open')) return if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this.attr('aria-expanded', 'false') $parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget)) }) } Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we use a backdrop because click events don't delegate $(document.createElement('div')) .addClass('dropdown-backdrop') .insertAfter($(this)) .on('click', clearMenus) } var relatedTarget = {relatedTarget: this} $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this .trigger('focus') .attr('aria-expanded', 'true') $parent .toggleClass('open') .trigger($.Event('shown.bs.dropdown', relatedTarget)) } return false } Dropdown.prototype.keydown = function (e) { if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if (!isActive && e.which != 27 || isActive && e.which == 27) { if (e.which == 27) $parent.find(toggle).trigger('focus') return $this.trigger('click') } var desc = ' li:not(.disabled):visible a' var $items = $parent.find('.dropdown-menu' + desc) if (!$items.length) return var index = $items.index(e.target) if (e.which == 38 && index > 0) index-- // up if (e.which == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items.eq(index).trigger('focus') } // DROPDOWN PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.dropdown') if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.dropdown $.fn.dropdown = Plugin $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown) .on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown) }(jQuery); /* ======================================================================== * Bootstrap: modal.js v3.3.6 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$body = $(document.body) this.$element = $(element) this.$dialog = this.$element.find('.modal-dialog') this.$backdrop = null this.isShown = null this.originalBodyPad = null this.scrollbarWidth = 0 this.ignoreBackdropClick = false if (this.options.remote) { this.$element .find('.modal-content') .load(this.options.remote, $.proxy(function () { this.$element.trigger('loaded.bs.modal') }, this)) } } Modal.VERSION = '3.3.6' Modal.TRANSITION_DURATION = 300 Modal.BACKDROP_TRANSITION_DURATION = 150 Modal.DEFAULTS = { backdrop: true, keyboard: true, show: true } Modal.prototype.toggle = function (_relatedTarget) { return this.isShown ? this.hide() : this.show(_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', {relatedTarget: _relatedTarget}) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.checkScrollbar() this.setScrollbar() this.$body.addClass('modal-open') this.escape() this.resize() this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.$dialog.on('mousedown.dismiss.bs.modal', function () { that.$element.one('mouseup.dismiss.bs.modal', function (e) { if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true }) }) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(that.$body) // don't move modals dom position } that.$element .show() .scrollTop(0) that.adjustDialog() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element.addClass('in') that.enforceFocus() var e = $.Event('shown.bs.modal', {relatedTarget: _relatedTarget}) transition ? that.$dialog // wait for modal to slide in .one('bsTransitionEnd', function () { that.$element.trigger('focus').trigger(e) }) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : that.$element.trigger('focus').trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() this.resize() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .off('click.dismiss.bs.modal') .off('mouseup.dismiss.bs.modal') this.$dialog.off('mousedown.dismiss.bs.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one('bsTransitionEnd', $.proxy(this.hideModal, this)) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.trigger('focus') } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keydown.dismiss.bs.modal') } } Modal.prototype.resize = function () { if (this.isShown) { $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this)) } else { $(window).off('resize.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.$body.removeClass('modal-open') that.resetAdjustments() that.resetScrollbar() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $(document.createElement('div')) .addClass('modal-backdrop ' + animate) .appendTo(this.$body) this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) { if (this.ignoreBackdropClick) { this.ignoreBackdropClick = false return } if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus() : this.hide() }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one('bsTransitionEnd', callback) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') var callbackRemove = function () { that.removeBackdrop() callback && callback() } $.support.transition && this.$element.hasClass('fade') ? this.$backdrop .one('bsTransitionEnd', callbackRemove) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callbackRemove() } else if (callback) { callback() } } // these following methods are used to handle overflowing modals Modal.prototype.handleUpdate = function () { this.adjustDialog() } Modal.prototype.adjustDialog = function () { var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight this.$element.css({ paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '', paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : '' }) } Modal.prototype.resetAdjustments = function () { this.$element.css({ paddingLeft: '', paddingRight: '' }) } Modal.prototype.checkScrollbar = function () { var fullWindowWidth = window.innerWidth if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8 var documentElementRect = document.documentElement.getBoundingClientRect() fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left) } this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth this.scrollbarWidth = this.measureScrollbar() } Modal.prototype.setScrollbar = function () { var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10) this.originalBodyPad = document.body.style.paddingRight || '' if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth) } Modal.prototype.resetScrollbar = function () { this.$body.css('padding-right', this.originalBodyPad) } Modal.prototype.measureScrollbar = function () { // thx walsh var scrollDiv = document.createElement('div') scrollDiv.className = 'modal-scrollbar-measure' this.$body.append(scrollDiv) var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth this.$body[0].removeChild(scrollDiv) return scrollbarWidth } // MODAL PLUGIN DEFINITION // ======================= function Plugin(option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } var old = $.fn.modal $.fn.modal = Plugin $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7 var option = $target.data('bs.modal') ? 'toggle' : $.extend({remote: !/#/.test(href) && href}, $target.data(), $this.data()) if ($this.is('a')) e.preventDefault() $target.one('show.bs.modal', function (showEvent) { if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown $target.one('hidden.bs.modal', function () { $this.is(':visible') && $this.trigger('focus') }) }) Plugin.call($target, option, this) }) }(jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.3.6 * http://getbootstrap.com/javascript/#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = null this.options = null this.enabled = null this.timeout = null this.hoverState = null this.$element = null this.inState = null this.init('tooltip', element, options) } Tooltip.VERSION = '3.3.6' Tooltip.TRANSITION_DURATION = 150 Tooltip.DEFAULTS = { animation: true, placement: 'top', selector: false, template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', trigger: 'hover focus', title: '', delay: 0, html: false, container: false, viewport: { selector: 'body', padding: 0 } } Tooltip.prototype.init = function (type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport)) this.inState = {click: false, hover: false, focus: false} if (this.$element[0] instanceof document.constructor && !this.options.selector) { throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!') } var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--; ) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin' var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, {trigger: 'manual', selector: ''})) : this.fixTitle() } Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay, hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function () { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } if (obj instanceof $.Event) { self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true } if (self.tip().hasClass('in') || self.hoverState == 'in') { self.hoverState = 'in' return } clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.isInStateTrue = function () { for (var key in this.inState) { if (this.inState[key]) return true } return false } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } if (obj instanceof $.Event) { self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false } if (self.isInStateTrue()) return clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.' + this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0]) if (e.isDefaultPrevented() || !inDom) return var that = this var $tip = this.tip() var tipId = this.getUID(this.type) this.setContent() $tip.attr('id', tipId) this.$element.attr('aria-describedby', tipId) this.$element.attr('id', tipId) var popoverid = "#" + tipId var myelement = $(popoverid).attr("data-class") $tip.addClass(myelement); if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({top: 0, left: 0, display: 'block'}) .addClass(placement) .data('bs.' + this.type, this) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) this.$element.trigger('inserted.bs.' + this.type) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var orgPlacement = placement var viewportDim = this.getPosition(this.$viewport) placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' : placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' : placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' : placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) var complete = function () { var prevHoverState = that.hoverState that.$element.trigger('shown.bs.' + that.type) that.hoverState = null if (prevHoverState == 'out') that.leave(that) } $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() } } Tooltip.prototype.applyPlacement = function (offset, placement) { var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top += marginTop offset.left += marginLeft // $.fn.offset doesn't round pixel values // so we use setOffset directly with our own function B-0 $.offset.setOffset($tip[0], $.extend({ using: function (props) { $tip.css({ top: Math.round(props.top), left: Math.round(props.left) }) } }, offset), 0) $tip.addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { offset.top = offset.top + height - actualHeight } var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight) if (delta.left) offset.left += delta.left else offset.top += delta.top var isVertical = /top|bottom/.test(placement) var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight' $tip.offset(offset) this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical) } Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) { this.arrow() .css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%') .css(isVertical ? 'top' : 'left', '') } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function (callback) { var that = this var $tip = $(this.$tip) var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() that.$element .removeAttr('aria-describedby') .trigger('hidden.bs.' + that.type) callback && callback() } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && $tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() this.hoverState = null return this } Tooltip.prototype.fixTitle = function () { var $e = this.$element if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function () { return this.getTitle() } Tooltip.prototype.getPosition = function ($element) { $element = $element || this.$element var el = $element[0] var isBody = el.tagName == 'BODY' var elRect = el.getBoundingClientRect() if (elRect.width == null) { // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093 elRect = $.extend({}, elRect, {width: elRect.right - elRect.left, height: elRect.bottom - elRect.top}) } var elOffset = isBody ? {top: 0, left: 0} : $element.offset() var scroll = {scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop()} var outerDims = isBody ? {width: $(window).width(), height: $(window).height()} : null return $.extend({}, elRect, scroll, outerDims, elOffset) } Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2} : placement == 'top' ? {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2} : placement == 'left' ? {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth} : /* placement == 'right' */ {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width} } Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) { var delta = {top: 0, left: 0} if (!this.$viewport) return delta var viewportPadding = this.options.viewport && this.options.viewport.padding || 0 var viewportDimensions = this.getPosition(this.$viewport) if (/right|left/.test(placement)) { var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight if (topEdgeOffset < viewportDimensions.top) { // top overflow delta.top = viewportDimensions.top - topEdgeOffset } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset } } else { var leftEdgeOffset = pos.left - viewportPadding var rightEdgeOffset = pos.left + viewportPadding + actualWidth if (leftEdgeOffset < viewportDimensions.left) { // left overflow delta.left = viewportDimensions.left - leftEdgeOffset } else if (rightEdgeOffset > viewportDimensions.right) { // right overflow delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset } } return delta } Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.getUID = function (prefix) { do prefix += ~~(Math.random() * 1000000) while (document.getElementById(prefix)) return prefix } Tooltip.prototype.tip = function () { if (!this.$tip) { this.$tip = $(this.options.template) if (this.$tip.length != 1) { throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!') } } return this.$tip } Tooltip.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')) } Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = this if (e) { self = $(e.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(e.currentTarget, this.getDelegateOptions()) $(e.currentTarget).data('bs.' + this.type, self) } } if (e) { self.inState.click = !self.inState.click if (self.isInStateTrue()) self.enter(self) else self.leave(self) } else { self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } } Tooltip.prototype.destroy = function () { var that = this clearTimeout(this.timeout) this.hide(function () { that.$element.off('.' + that.type).removeData('bs.' + that.type) if (that.$tip) { that.$tip.detach() } that.$tip = null that.$arrow = null that.$viewport = null }) } // TOOLTIP PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data && /destroy|hide/.test(option)) return if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tooltip $.fn.tooltip = Plugin $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(jQuery); /* ======================================================================== * Bootstrap: popover.js v3.3.6 * http://getbootstrap.com/javascript/#popovers * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function (element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.VERSION = '3.3.6' Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right', trigger: 'click', content: '', template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function () { return Popover.DEFAULTS } Popover.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() var content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text' ](content) $tip.removeClass('fade top bottom left right in') // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() } Popover.prototype.hasContent = function () { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function () { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.arrow')) } // POPOVER PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option if (!data && /destroy|hide/.test(option)) return if (!data) $this.data('bs.popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.popover $.fn.popover = Plugin $.fn.popover.Constructor = Popover // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.3.6 * http://getbootstrap.com/javascript/#scrollspy * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { this.$body = $(document.body) this.$scrollElement = $(element).is(document.body) ? $(window) : $(element) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || '') + ' .nav li > a' this.offsets = [] this.targets = [] this.activeTarget = null this.scrollHeight = 0 this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this)) this.refresh() this.process() } ScrollSpy.VERSION = '3.3.6' ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.getScrollHeight = function () { return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight) } ScrollSpy.prototype.refresh = function () { var that = this var offsetMethod = 'offset' var offsetBase = 0 this.offsets = [] this.targets = [] this.scrollHeight = this.getScrollHeight() if (!$.isWindow(this.$scrollElement[0])) { offsetMethod = 'position' offsetBase = this.$scrollElement.scrollTop() } this.$body .find(this.selector) .map(function () { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#./.test(href) && $(href) return ($href && $href.length && $href.is(':visible') && [[$href[offsetMethod]().top + offsetBase, href]]) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { that.offsets.push(this[0]) that.targets.push(this[1]) }) } ScrollSpy.prototype.process = function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.getScrollHeight() var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (this.scrollHeight != scrollHeight) { this.refresh() } if (scrollTop >= maxScroll) { return activeTarget != (i = targets[targets.length - 1]) && this.activate(i) } if (activeTarget && scrollTop < offsets[0]) { this.activeTarget = null return this.clear() } for (i = offsets.length; i--; ) { activeTarget != targets[i] && scrollTop >= offsets[i] && (offsets[i + 1] === undefined || scrollTop < offsets[i + 1]) && this.activate(targets[i]) } } ScrollSpy.prototype.activate = function (target) { this.activeTarget = target this.clear() var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') } ScrollSpy.prototype.clear = function () { $(this.selector) .parentsUntil(this.options.target, '.active') .removeClass('active') } // SCROLLSPY PLUGIN DEFINITION // =========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.scrollspy $.fn.scrollspy = Plugin $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load.bs.scrollspy.data-api', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) Plugin.call($spy, $spy.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: tab.js v3.3.6 * http://getbootstrap.com/javascript/#tabs * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TAB CLASS DEFINITION // ==================== var Tab = function (element) { // jscs:disable requireDollarBeforejQueryAssignment this.element = $(element) // jscs:enable requireDollarBeforejQueryAssignment } Tab.VERSION = '3.3.6' Tab.TRANSITION_DURATION = 150 Tab.prototype.show = function () { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.data('target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } if ($this.parent('li').hasClass('active')) return var $previous = $ul.find('.active:last a') var hideEvent = $.Event('hide.bs.tab', { relatedTarget: $this[0] }) var showEvent = $.Event('show.bs.tab', { relatedTarget: $previous[0] }) $previous.trigger(hideEvent) $this.trigger(showEvent) if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return var $target = $(selector) this.activate($this.closest('li'), $ul) this.activate($target, $target.parent(), function () { $previous.trigger({ type: 'hidden.bs.tab', relatedTarget: $this[0] }) $this.trigger({ type: 'shown.bs.tab', relatedTarget: $previous[0] }) }) } Tab.prototype.activate = function (element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length) function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', false) element .addClass('active') .find('[data-toggle="tab"]') .attr('aria-expanded', true) if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu').length) { element .closest('li.dropdown') .addClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', true) } callback && callback() } $active.length && transition ? $active .one('bsTransitionEnd', next) .emulateTransitionEnd(Tab.TRANSITION_DURATION) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tab $.fn.tab = Plugin $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function () { $.fn.tab = old return this } // TAB DATA-API // ============ var clickHandler = function (e) { e.preventDefault() Plugin.call($(this), 'show') } $(document) .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler) .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler) }(jQuery); /* ======================================================================== * Bootstrap: affix.js v3.3.6 * http://getbootstrap.com/javascript/#affix * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // AFFIX CLASS DEFINITION // ====================== var Affix = function (element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$target = $(this.options.target) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = null this.unpin = null this.pinnedOffset = null this.checkPosition() } Affix.VERSION = '3.3.6' Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0, target: window } Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) { var scrollTop = this.$target.scrollTop() var position = this.$element.offset() var targetHeight = this.$target.height() if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false if (this.affixed == 'bottom') { if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom' return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom' } var initializing = this.affixed == null var colliderTop = initializing ? scrollTop : position.top var colliderHeight = initializing ? targetHeight : height if (offsetTop != null && scrollTop <= offsetTop) return 'top' if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom' return false } Affix.prototype.getPinnedOffset = function () { if (this.pinnedOffset) return this.pinnedOffset this.$element.removeClass(Affix.RESET).addClass('affix') var scrollTop = this.$target.scrollTop() var position = this.$element.offset() return (this.pinnedOffset = position.top - scrollTop) } Affix.prototype.checkPositionWithEventLoop = function () { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var height = this.$element.height() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom var scrollHeight = Math.max($(document).height(), $(document.body).height()) if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element) if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element) var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom) if (this.affixed != affix) { if (this.unpin != null) this.$element.css('top', '') var affixType = 'affix' + (affix ? '-' + affix : '') var e = $.Event(affixType + '.bs.affix') this.$element.trigger(e) if (e.isDefaultPrevented()) return this.affixed = affix this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null this.$element .removeClass(Affix.RESET) .addClass(affixType) .trigger(affixType.replace('affix', 'affixed') + '.bs.affix') } if (affix == 'bottom') { this.$element.offset({ top: scrollHeight - height - offsetBottom }) } } // AFFIX PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.affix $.fn.affix = Plugin $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function () { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom if (data.offsetTop != null) data.offset.top = data.offsetTop Plugin.call($spy, data) }) }) }(jQuery);
shazic/FirstWordPress
wp-content/themes/evolve/library/media/js/bootstrap/js/bootstrap.js
JavaScript
gpl-3.0
78,255
const NUMBER_OF_CLOUDS = 30; // clouds to show on screen const NUMBER_OF_IMAGES = 13; // images + 1 function init() { var container = document.getElementById("fogContainer"); for (var i = 0; i < NUMBER_OF_CLOUDS; i++) { container.appendChild(createACloud())} } function randomInteger(low, high) { return low + Math.floor(Math.random() * (high - low)); } function randomFloat(low, high) { return low + Math.random() * (high - low); } function pixelValue(value) { return value + "px"; } function durationValue(value) { return value + "s"; } function createACloud() { var cloudDiv = document.createElement("div"); var image = document.createElement("img"); image.src = "Haze_night/Private/images/fog" + randomInteger(4, NUMBER_OF_IMAGES) + ".png"; cloudDiv.style.top = pixelValue(randomInteger(-200, 350)); cloudDiv.style.left = pixelValue(randomInteger(-110, -110)); var spinAnimationName = (Math.random() < 0.5) ? "clockwiseSpin" : "counterclockwiseSpinAndFlip"; cloudDiv.style.webkitAnimationName = "float"; image.style.webkitAnimationName = spinAnimationName; var fadeAndfloatDuration = durationValue(randomFloat(40, 70)); var spinDuration = durationValue(randomFloat(30, 80)); cloudDiv.style.webkitAnimationDuration = fadeAndfloatDuration + ", " + fadeAndfloatDuration; image.style.webkitAnimationDuration = spinDuration; cloudDiv.appendChild(image); return cloudDiv; } window.addEventListener("load", init, false);
eweiman/HTC-Animated-Weather-iPhone
com.ludacrisvp.htcweather6Plus.iwidget/var/mobile/Library/iWidgets/HTC Weather iPhone 6 Plus/Private/Animations/Haze_night/Private/includes/fog.js
JavaScript
gpl-3.0
1,500
/** * GaiaEHR (Electronic Health Records) * Copyright (C) 2012 Ernesto Rodriguez * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ Ext.define('App.model.administration.LabObservations', { extend: 'Ext.data.Model', table: { name: 'labs_panels', comment: 'Laboratory Observations' }, fields: [ {name: 'id', type: 'string', comment: 'LOINC'}, {name: 'code_text_short', type: 'string' }, {name: 'parent_id', type: 'int', dataType: 'bigint' }, {name: 'parent_loinc', type: 'string', dataType: 'text' }, {name: 'parent_name', type: 'string', dataType: 'text' }, {name: 'sequence', type: 'string', dataType: 'text' }, {name: 'loinc_number', type: 'string', dataType: 'text' }, {name: 'loinc_name', type: 'string', dataType: 'text' }, {name: 'default_unit', type: 'string' }, {name: 'range_start', type: 'string' }, {name: 'range_end', type: 'string' }, {name: 'required_in_panel', type: 'string', dataType: 'text' }, {name: 'description', type: 'string', dataType: 'text' }, {name: 'active', type: 'bool' } ] });
chithubco/doctorapp
app/model/administration/LabObservations.js
JavaScript
gpl-3.0
1,649
angular.module("app").controller("DeleteRequiredSignoffsCtrl", function ($scope, $modalInstance, $q, CSRF, ProductRequiredSignoffs, PermissionsRequiredSignoffs, required_signoffs, mode, product, channel, current_user) { $scope.saving = false; $scope.errors = {}; $scope.required_signoffs = required_signoffs; $scope.mode = mode; $scope.product = product; $scope.channel = channel; $scope.to_delete = {}; $scope.title = "Remove Signoff Requirements for "; if ($scope.mode === "channel") { $scope.to_delete = $scope.required_signoffs[$scope.product]["channels"][$scope.channel]; $scope.title += " for the " + $scope.product + " " + $scope.channel + " channel"; } else { $scope.to_delete = $scope.required_signoffs[$scope.product]["permissions"]; $scope.title += " for " + $scope.product + " Permissions"; } $scope.saveChanges = function() { $scope.errors = {}; var service = null; if ($scope.mode === "channel") { service = ProductRequiredSignoffs; } else if ($scope.mode === "permissions") { service = PermissionsRequiredSignoffs; } else { $scope.errors["exception"] = "Couldn't detect mode"; return; } CSRF.getToken() .then(function(csrf_token) { $scope.saving = true; var promises = []; var successCallback = function(data, deferred) { return function(response) { var namespace = null; if ($scope.mode === "channel") { namespace = required_signoffs[$scope.product]["channels"][$scope.channel]; } else { namespace = required_signoffs[$scope.product]["permissions"]; } // Required Signoff wasn't pending, so a deletion will be a new Scheduled Change if (namespace[data["role"]]["sc"] === null) { namespace[data["role"]]["sc"] = { "required_signoffs": {}, "signoffs_required": 0, "sc_id": response["sc_id"], "scheduled_by": current_user, "sc_data_version": 1, "signoffs": {}, "change_type": "delete", }; } // Required Signoff was previously pending, so it was directly removed else { // If it was *only* a scheduled change, we delete the whole thing if (namespace[data["role"]]["data_version"] === null) { delete namespace[data["role"]]; } // If it was a scheduled change to an existing Required Signoff, just remove // the Scheduled Change portion else { namespace[data["role"]]["sc"] = null; } } deferred.resolve(); }; }; var errorCallback = function(data, deferred) { return function(response, status) { if (typeof response === "object") { $scope.errors = response; } else if (typeof response === "string"){ $scope.errors["exception"] = response; } else { sweetAlert("Unknown error occurred"); } deferred.resolve(); }; }; Object.keys($scope.to_delete).forEach(function(role_name) { var deferred = $q.defer(); promises.push(deferred.promise); var data = {"product": $scope.product, "role": role_name, "data_version": $scope.to_delete[role_name]["data_version"], "csrf_token": csrf_token}; if ($scope.mode === "channel") { data["channel"] = $scope.channel; } // Not a Scheduled Change, we'll have to create one to delete it if ($scope.to_delete[role_name]["sc"] === null) { data["when"] = new Date().getTime() + 5000; data["change_type"] = "delete"; service.addScheduledChange(data) .success(successCallback(data, deferred)) .error(errorCallback(data, deferred)); } // Already has a Scheduled Change else { var change_type = $scope.to_delete[role_name]["sc"]["change_type"]; // If that Scheduled Change is already a delete, great, nothing to do! if (change_type === "delete") { deferred.resolve(); return; } // If the Scheduled Change is an insert or update, we'll need to // remove that. For inserts, that's all we need to do, because // there is no current Required Signoff to deal with. data["sc_data_version"] = $scope.to_delete[role_name]["sc"]["sc_data_version"]; service.deleteScheduledChange($scope.to_delete[role_name]["sc"]["sc_id"], data) .success(successCallback(data, deferred)) .error(errorCallback(data, deferred)); // If we deleted an update, we'll need to queue up a delete to deal with // the current Required Signoff if (change_type === "update") { delete data["sc_data_version"]; data["when"] = new Date().getTime() + 5000; data["change_type"] = "delete"; service.addScheduledChange(data) .success(successCallback(data, deferred)) .error(errorCallback(data, deferred)); } } }); $q.all(promises) .then(function() { if (Object.keys($scope.errors).length === 0) { $modalInstance.close(); } $scope.saving = false; }); }); }; $scope.cancel = function () { $modalInstance.dismiss("cancel"); }; });
testbhearsum/balrog
ui/app/js/controllers/required_signoffs_delete.js
JavaScript
mpl-2.0
5,585
//call this to add a warning icon to a graph and log an error to the console function error(args) { console.log('ERROR : ', args.target, ' : ', args.error); d3.select(args.target).select('.mg-chart-title') .append('i') .attr('class', 'fa fa-x fa-exclamation-circle warning'); }
HDAT/hdat-statstest
src/js/misc/error.js
JavaScript
mpl-2.0
307
describe('EncounterService tests', function() { var encounterService; var q; var deferred; beforeEach(module('encounterService')); // create mock Encounter resource var mockEncounter = jasmine.createSpyObj('Encounter', ['query']); mockEncounter.query.andCallFake(function() { deferred = q.defer(); var promise_mock = { $promise: deferred.promise }; return promise_mock; }); beforeEach(module(function($provide) { $provide.value('Encounter', mockEncounter); })); // inject necessary dependencies beforeEach(inject(function (_EncounterService_,$q) { encounterService = _EncounterService_; q = $q; })); it('should call Encounter resource with query value', function() { encounterService.getEncounters({ 'q': 'abc' }); expect(mockEncounter.query).toHaveBeenCalledWith({ 'q': 'abc' }); }); });
yadamz/first-module
omod/src/test/webapp/resources/scripts/services/encounterServiceTest.js
JavaScript
mpl-2.0
942
load(libdir + "parallelarray-helpers.js"); // The bug this is testing for: // the input p and the scatter vector have length 4 // and the output p2 has length 3. Even though p2 // is shorter than the input lengths, we still need // to scan the entirety of the scatter vector, because // it may hold valid targets at distant indices. function test() { var p = new ParallelArray([2,3,5,17]); var r = p.scatter([0,0,2,1], 9, function (x,y) { return x * y; }, 3); var p2 = new ParallelArray([6,17,5]); assertEqParallelArray(r, p2); } if (getBuildConfiguration().parallelJS) test();
SlateScience/MozillaJS
js/src/jit-test/tests/parallelarray/scatter-regression-1.js
JavaScript
mpl-2.0
592
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // Keep track of events tied to both email and IP addresses module.exports = function (RATE_LIMIT_INTERVAL_MS, MAX_BAD_LOGINS, now) { now = now || Date.now var PASSWORD_CHECKING_ACTION = { accountLogin : true, accountDestroy : true, passwordChange : true, } function isPasswordCheckingAction(action) { return PASSWORD_CHECKING_ACTION[action] } function IpEmailRecord() { this.lf = [] } IpEmailRecord.parse = function (object) { var rec = new IpEmailRecord() object = object || {} rec.rl = object.rl // timestamp when the account was rate-limited rec.lf = object.lf || [] // timestamps when a login failure occurred return rec } IpEmailRecord.prototype.isOverBadLogins = function () { this.trimBadLogins(now()) return this.lf.length > MAX_BAD_LOGINS } IpEmailRecord.prototype.addBadLogin = function () { this.trimBadLogins(now()) this.lf.push(now()) } IpEmailRecord.prototype.trimBadLogins = function (now) { if (this.lf.length === 0) { return } // lf is naturally ordered from oldest to newest // and we only need to keep up to MAX_BAD_LOGINS + 1 var i = this.lf.length - 1 var n = 0 var login = this.lf[i] while (login > (now - RATE_LIMIT_INTERVAL_MS) && n <= MAX_BAD_LOGINS) { login = this.lf[--i] n++ } this.lf = this.lf.slice(i + 1) } IpEmailRecord.prototype.shouldBlock = function () { return this.isRateLimited() } IpEmailRecord.prototype.isRateLimited = function () { return !!(this.rl && (now() - this.rl < RATE_LIMIT_INTERVAL_MS)) } IpEmailRecord.prototype.rateLimit = function () { this.rl = now() this.lf = [] } IpEmailRecord.prototype.unblockIfReset = function (resetAt) { if (resetAt > this.rl) { this.lf = [] delete this.rl return true } return false } IpEmailRecord.prototype.retryAfter = function () { return Math.max(0, Math.floor(((this.rl || 0) + RATE_LIMIT_INTERVAL_MS - now()) / 1000)) } IpEmailRecord.prototype.update = function (action) { // if this is not an action that allows checking password, // then all ok (no block) if ( !isPasswordCheckingAction(action) ) { return 0 } if ( this.shouldBlock() ) { // if already blocked, then return a block return this.retryAfter() } // if over the bad logins, rate limit them and return the block if (this.isOverBadLogins()) { this.rateLimit() return this.retryAfter() } // no block, not yet over limit return 0 } return IpEmailRecord }
ofer43211/fxa-customs-server
ip_email_record.js
JavaScript
mpl-2.0
2,820
// Copyright (C) 2016 Jordan Harband. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- description: Object.getOwnPropertyDescriptors does not see inherited properties. esid: pending author: Jordan Harband ---*/ var F = function () {}; F.prototype.a = {}; F.prototype.b = {}; var f = new F(); var bValue = {}; f.b = bValue; // shadow the prototype Object.defineProperty(f, 'c', { enumerable: false, configurable: true, writable: false, value: {} }); // solely an own property var result = Object.getOwnPropertyDescriptors(f); assert.sameValue(!!result.b, true, 'b has a descriptor'); assert.sameValue(!!result.c, true, 'c has a descriptor'); assert.sameValue(result.b.enumerable, true, 'b is enumerable'); assert.sameValue(result.b.configurable, true, 'b is configurable'); assert.sameValue(result.b.writable, true, 'b is writable'); assert.sameValue(result.b.value, bValue, 'b’s value is `bValue`'); assert.sameValue(result.c.enumerable, false, 'c is enumerable'); assert.sameValue(result.c.configurable, true, 'c is configurable'); assert.sameValue(result.c.writable, false, 'c is writable'); assert.sameValue(result.c.value, f.c, 'c’s value is `f.c`'); assert.sameValue( Object.keys(result).length, 2, 'result has same number of own property names as f' );
cstipkovic/spidermonkey-research
js/src/tests/test262/built-ins/Object/getOwnPropertyDescriptors/inherited-properties-omitted.js
JavaScript
mpl-2.0
1,334
'use strict'; var minilog = require('minilog') , log = minilog('traverson') , abortTraversal = require('./abort_traversal') , applyTransforms = require('./transforms/apply_transforms') , httpRequests = require('./http_requests') , isContinuation = require('./is_continuation') , walker = require('./walker'); var checkHttpStatus = require('./transforms/check_http_status') , continuationToDoc = require('./transforms/continuation_to_doc') , continuationToResponse = require('./transforms/continuation_to_response') , convertEmbeddedDocToResponse = require('./transforms/convert_embedded_doc_to_response') , extractDoc = require('./transforms/extract_doc') , extractResponse = require('./transforms/extract_response') , extractUrl = require('./transforms/extract_url') , fetchLastResource = require('./transforms/fetch_last_resource') , executeLastHttpRequest = require('./transforms/execute_last_http_request') , executeHttpRequest = require('./transforms/execute_http_request') , parse = require('./transforms/parse') , parseLinkHeader = require('./transforms/parse_link_header'); /** * Starts the link traversal process and end it with an HTTP get. */ exports.get = function(t, callback) { var transformsAfterLastStep; if (t.convertResponseToObject) { transformsAfterLastStep = [ continuationToDoc, fetchLastResource, checkHttpStatus, parse, parseLinkHeader, extractDoc, ]; } else { transformsAfterLastStep = [ continuationToResponse, fetchLastResource, convertEmbeddedDocToResponse, extractResponse, ]; } walker.walk(t, transformsAfterLastStep, callback); return createTraversalHandle(t); }; /** * Special variant of get() that does not execute the last request but instead * yields the last URL to the callback. */ exports.getUrl = function(t, callback) { walker.walk(t, [ extractUrl ], callback); return createTraversalHandle(t); }; /** * Starts the link traversal process and sends an HTTP POST request with the * given body to the last URL. Passes the HTTP response of the POST request to * the callback. */ exports.post = function(t, callback) { walkAndExecute(t, t.requestModuleInstance, t.requestModuleInstance.post, callback); return createTraversalHandle(t); }; /** * Starts the link traversal process and sends an HTTP PUT request with the * given body to the last URL. Passes the HTTP response of the PUT request to * the callback. */ exports.put = function(t, callback) { walkAndExecute(t, t.requestModuleInstance, t.requestModuleInstance.put, callback); return createTraversalHandle(t); }; /** * Starts the link traversal process and sends an HTTP PATCH request with the * given body to the last URL. Passes the HTTP response of the PATCH request to * the callback. */ exports.patch = function(t, callback) { walkAndExecute(t, t.requestModuleInstance, t.requestModuleInstance.patch, callback); return createTraversalHandle(t); }; /** * Starts the link traversal process and sends an HTTP DELETE request to the * last URL. Passes the HTTP response of the DELETE request to the callback. */ exports.delete = function(t, callback) { walkAndExecute(t, t.requestModuleInstance, t.requestModuleInstance.del, callback); return createTraversalHandle(t); }; function walkAndExecute(t, request, method, callback) { var transformsAfterLastStep; if (t.convertResponseToObject) { transformsAfterLastStep = [ executeHttpRequest, checkHttpStatus, parse, parseLinkHeader, extractDoc, ]; } else { transformsAfterLastStep = [ executeLastHttpRequest, ]; } t.lastMethod = method; walker.walk(t, transformsAfterLastStep, callback); } function createTraversalHandle(t) { return { abort: t.abortTraversal }; }
cgi-eoss/fstep
fs-tep-portal/src/main/resources/app/scripts/vendor/traverson/lib/actions.js
JavaScript
agpl-3.0
3,942
/// Copyright (c) 2009 Microsoft Corporation /// /// 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 Microsoft nor the names of its contributors may be used to /// endorse or promote products derived from this software without specific prior written permission. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR /// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS /// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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. ES5Harness.registerTest({ id: "15.2.3.5-4-170", path: "TestCases/chapter15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-170.js", description: "Object.create - one property in 'Properties' is the Math object that uses Object's [[Get]] method to access the 'value' property (8.10.5 step 5.a)", test: function testcase() { try { Math.value = "MathValue"; var newObj = Object.create({}, { prop: Math }); return newObj.prop === "MathValue"; } finally { delete Math.value; } }, precondition: function prereq() { return fnExists(Object.create); } });
hnafar/IronJS
Src/Tests/ietestcenter/chapter15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-170.js
JavaScript
apache-2.0
2,234
/* * Copyright 2016 IBM Corp. * * 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. */ module.exports = function(kernelP) { return (function() { var Utils = require('../utils.js'); var PipelineStage = require('./PipelineStage')(); /** * @classdesc * Abstract class for transformers that transform one dataset into another. * @class * @memberof module:eclairjs/ml * @extends module:eclairjs/ml.PipelineStage */ function Transformer() { Utils.handleAbstractConstructor(this, arguments); } Transformer.prototype = Object.create(PipelineStage.prototype); Transformer.prototype.constructor = Transformer; /** * Transforms the dataset with optional parameters * @param {module:eclairjs/sql.Dataset} dataset input dataset * @param {module:eclairjs/ml/param.ParamMap | module:eclairjs/ml/param.ParamPair} [params] additional parameters, overwrite embedded params, overwrite embedded params * @param {...module:eclairjs/ml/param.ParamPair} [otherParamPairs] other param pairs, Only used if argument two is {@link module:eclairjs/ml/param.ParamPair}. Overwrite embedded params * @returns {module:eclairjs/sql.Dataset} transformed dataset */ Transformer.prototype.transform = function() { var Dataset = require('../sql/Dataset'); var args = { target: this, method: 'transform', args: Utils.wrapArguments(arguments), returnType: Dataset }; return Utils.generate(args); }; /** * @param {module:eclairjs/ml/param.ParamMap} extra * @returns {module:eclairjs/ml.Transformer} */ Transformer.prototype.copy = function(extra) { var args = { target: this, method: 'copy', args: Utils.wrapArguments(arguments), returnType: Utils.getContextClass(this) }; return Utils.generate(args); }; return Transformer; })(); };
EclairJS/eclairjs-node
lib/ml/Transformer.js
JavaScript
apache-2.0
2,461
/******************************************************************************* * Copyright 2015 IBM Corp. * * 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. *******************************************************************************/ var Probe = require('../lib/probe.js'); var aspect = require('../lib/aspect.js'); var request = require('../lib/request.js'); var util = require('util'); var am = require('..'); function SocketioProbe() { Probe.call(this, 'socket.io'); } util.inherits(SocketioProbe, Probe); SocketioProbe.prototype.attach = function(name, target) { var that = this; if(name != "socket.io") return target; /* * Don't set __ddProbeAttached__ = true as we need to probe and return * the constructor each time */ /* * Patch the constructor so that we can patch io.sockets.emit() calls * to broadcast to clients. This also picks up calls to io.emit() as * they map down to io.socket.emit() */ var newtarget = aspect.afterConstructor(target, {}, function(target, methodName, methodArgs, context, server) { var broadcast = 'broadcast'; aspect.around(server.sockets, 'emit', function(target, methodName, methodArgs, context){ that.metricsProbeStart(context, broadcast, methodArgs); that.requestProbeStart(context, broadcast, methodArgs); }, function(target, methodName, methodArgs, context, rc){ that.metricsProbeEnd(context, broadcast, methodArgs); that.requestProbeEnd(context, broadcast, methodArgs); } ); return server; } ); /* * Remap the listen API to point to new constructor */ newtarget.listen = newtarget; /* * We patch the constructor every time, but only want to patch prototype * functions once otherwise we'll generate multiple events */ if (!target.__prototypeProbeAttached__) { target.__prototypeProbeAttached__ = true; aspect.before(target.prototype, ['on', 'addListener'], function(target, methodName, methodArgs, context) { if(methodArgs[0] !== 'connection') return; if (aspect.findCallbackArg(methodArgs) != undefined) { aspect.aroundCallback(methodArgs, context, function(target, methodArgs, context) { var socket = methodArgs[0]; /* * Patch Socket#emit() calls */ aspect.around(socket, 'emit', function(target, methodName, methodArgs, context){ that.metricsProbeStart(context, methodName, methodArgs); that.requestProbeStart(context, methodName, methodArgs); }, function(target, methodName, methodArgs, context, rc){ //Call the transaction link with a name and the callback for strong trace var callbackPosition = aspect.findCallbackArg(methodArgs); if (typeof(callbackPosition) != 'undefined') { aspect.strongTraceTransactionLink('socket.io: ', methodName, methodArgs[callbackPosition]); } that.metricsProbeEnd(context, methodName, methodArgs); that.requestProbeEnd(context, methodName, methodArgs); return rc; } ); /* * Patch socket.on incoming events */ var receive = 'receive'; aspect.before(socket, ['on', 'addListener'], function(target, methodName, methodArgs, context) { aspect.aroundCallback(methodArgs, context, function(target, callbackArgs, context){ that.metricsProbeStart(context, receive, methodArgs); that.requestProbeStart(context, receive, methodArgs); }, function (target, callbackArgs, context, rc) { //Call the transaction link with a name and the callback for strong trace var callbackPosition = aspect.findCallbackArg(methodArgs); if (typeof(callbackPosition) != 'undefined') { aspect.strongTraceTransactionLink('socket.io: ', methodName, methodArgs[callbackPosition]); } that.metricsProbeEnd(context, receive, methodArgs); that.requestProbeEnd(context, receive, methodArgs); return rc; } ); } ); } ); } }); } return newtarget; }; /* * Lightweight metrics probe for Socket.io websocket connections * * These provide: * time: time event started * method: the type of socket.io action * event: the event broadcast/emitted/received * duration: the time for the action to complete */ SocketioProbe.prototype.metricsEnd = function(context, methodName, methodArgs) { if(context && context.timer) { context.timer.stop(); am.emit('socketio', {time: context.timer.startTimeMillis, method: methodName, event: methodArgs[0], duration: context.timer.timeDelta}); } }; /* * Heavyweight request probes for Socket.io websocket connections */ SocketioProbe.prototype.requestStart = function (context, methodName, methodArgs) { /* * method names are "broadcast", "receive" and "emit" */ if (methodName !== 'receive') { context.req = request.startRequest('socketio', methodName, false, context.timer); } else { context.req = request.startRequest('socketio', methodName, true, context.timer); } }; SocketioProbe.prototype.requestEnd = function (context, methodName, methodArgs) { if(context && context.req) context.req.stop({method: methodName, event: methodArgs[0]}); }; module.exports = SocketioProbe;
kgriesh/appmetrics
probes/socketio-probe.js
JavaScript
apache-2.0
5,878
// Copyright (C) Copyright 2015 the V8 project authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es6id: 25.2.1.1 description: Assignment of function `name` attribute info: > [...] 3. Return CreateDynamicFunction(C, NewTarget, "generator", args). ES6 19.2.1.1.1 RuntimeSemantics: CreateDynamicFunction(constructor, newTarget, kind, args) [...] 29. Perform SetFunctionName(F, "anonymous"). includes: [propertyHelper.js] ---*/ var GeneratorFunction = Object.getPrototypeOf(function* () {}).constructor; assert.sameValue(GeneratorFunction().name, 'anonymous'); verifyNotEnumerable(GeneratorFunction(), 'name'); verifyNotWritable(GeneratorFunction(), 'name'); verifyConfigurable(GeneratorFunction(), 'name');
m0ppers/arangodb
3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/GeneratorFunction/instance-name.js
JavaScript
apache-2.0
794
var C = (function () { function C() { } C.prototype.x = function () { return 1; }; return C; })(); var D = (function () { function D() { } D.prototype.x = function (v) { }; return D; })();
popravich/typescript
tests/baselines/reference/propertyAndFunctionWithSameName.js
JavaScript
apache-2.0
254
#!/usr/bin/env node_modules/mocha/bin/mocha /* jshint node:true */ /* global describe */ /** * ares.spec.js -- ARES server test suite */ var path = require("path"), fs = require("graceful-fs"), npmlog = require('npmlog'), temp = require("temp"), mkdirp = require("mkdirp"), rimraf = require("rimraf"); var knownOpts = { "config": path, "help": Boolean, "level": ['silly', 'verbose', 'info', 'http', 'warn', 'error'] }; var shortHands = { "c": "--config", "h": "--help", "l": "--level", "v": "--level verbose" }; var helpString = [ "", "Ares server tester.", "Usage: '" + process.argv[0] + " " + process.argv[1] + " [OPTIONS]", "", "Options:", " -c, --config path to ide.json [default: '" + path.resolve(__dirname, "..", "..", "ide.json") + "]", " -h, --help help message [boolean]", " -v, --verbose verbose execution mode [boolean]", " -q, --quiet really quiet [boolean]", "" ]; var argv = require('nopt')(knownOpts, shortHands, process.argv, 2 /*drop 'node' & basename*/); argv.config = argv.config || path.resolve(__dirname, "..", "..", "ide.json"); if (argv.help) { helpString.forEach(function(s) { console.log(s); }); process.exit(0); } /**********************************************************************/ var log = npmlog; log.heading = 'ares.spec'; log.level = argv.level || 'error'; /**********************************************************************/ log.verbose("main", "running in verbose mode"); log.verbose("main", "argv:", argv); var myPort = 9019; log.verbose("main", "loading " + argv.config); var config = JSON.parse(fs.readFileSync(argv.config, 'utf8')); log.verbose("main", "config:", config); var myTestDir = "_test"; /* * test suite */ function getHome() { return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME']; } describe("Testing filesystems", function() { var FsSpec = require("./fs.spec.js"); var dropbox = config.services.filter(function(service) { return service.id === 'dropbox'; })[0]; if (dropbox && dropbox.auth && dropbox.auth.appKey) { describe("fsDropbox", function(done) { var myDropboxApp = 'com.enyojs.ares'; // Assume a user's account grip in the local file-system. var myTestDirPath = path.join(getHome(), 'Dropbox', 'Apps', myDropboxApp, myTestDir); rimraf.sync(myTestDirPath); mkdirp.sync(myTestDirPath); new FsSpec({ filesystem: "./../../hermes/fsDropbox.js", pathname: "/", port: myPort, dir: myTestDir, level: argv.level, auth: dropbox.auth }); }); } describe("fsLocal", function() { var myFsPath = temp.mkdirSync({prefix: 'com.palm.ares.test.fs'}); new FsSpec({ filesystem: "./../../hermes/fsLocal.js", pathname: "/", port: myPort, dir: myTestDir, level: argv.level, root: myFsPath }); }); });
recurve/ares-ecosystem
test/server/ares.spec.js
JavaScript
apache-2.0
2,853
var twintyfour=true, $inputbox=$('.timepicker'); var setTimearea=function(meridian){ var $div=$('<div/>'), $input=$('<input type="text"/>'); var lists=['hour', 'min', 'sec']; $div.clone().addClass('timepicker_wrap').insertAfter($inputbox); for(var i=0; i< lists.length; i++){ $div.clone().addClass(lists[i]).appendTo('.timepicker_wrap'); $div.clone().addClass('btn prev').appendTo('.'+lists[i]); $div.clone().addClass('ti_tx').append($input.clone().addClass('in_txt')).appendTo('.'+lists[i]); $div.clone().addClass('btn next').appendTo('.'+lists[i]); } if(meridian){ twintyfour=false; $div.clone().addClass('meridian').appendTo('.timepicker_wrap'); $div.clone().addClass('btn prev').appendTo('.meridian'); $div.clone().addClass('ti_tx').append($input.clone().addClass('in_txt')).appendTo('.meridian'); $div.clone().addClass('btn next').appendTo('.meridian'); } }; var checkTime=function(tnum, place){ var $area=$(place.parentElement.parentElement).find('.in_txt'), m, h; switch(place.parentElement.className){ case 'hour': if(place.classList[1] === 'prev') { h=resuceNum(tnum); $area.eq(0).val(addZero(h, true)); } else if(place.classList[1] === 'next'){ h=addNum(tnum); $area.eq(0).val(addZero(h, true)); } break; case 'min': if(place.classList[1] === 'prev') { m=resuceNum(tnum); $area.eq(1).val(addZero(m)); } else if(place.classList[1] === 'next'){ m=addNum(tnum); $area.eq(1).val(addZero(m)); } break; case 'sec': if(place.classList[1] === 'prev') { sec=resuceNum(tnum); $area.eq(2).val(addZero(sec)); } else if(place.classList[1] === 'next'){ sec=addNum(tnum); $area.eq(2).val(addZero(sec)); } break; case 'meridian': if($area.eq(3).val() === 'AM') $area.eq(3).val('PM'); else $area.eq(3).val('AM'); break; default: alert('get fail'); } }; function addZero(i, hours) { if(hours){ if(i>24) i=1; else if (i<1) i=24; !twintyfour ? i>12 ? i-=12 : '':''; } else{ if(i>59) i=0; else if(i < 0) i=59; } if (i < 10) { i = "0" + i; } return i; } function setInit(inputbox){ var $area=$(inputbox[0].nextElementSibling).find('.in_txt'); var date=new Date(), tz='AM'; var list=[addZero(date.getHours(), true), addZero(date.getMinutes()), addZero(date.getSeconds()), tz]; if(inputbox.val().length===0){ for(var i=0; i<$area.length; i++) $($area[i]).val(list[i]); setValue(inputbox, $area); }else { var formateTime=inputbox.val().split(':'); for(var i=0; i<$area.length; i++) $($area[i]).val(formateTime[i]); } } function isSetTimeArea(dom){ var open=false; if($('body').find('.timepicker_wrap')[1] !==undefined) open=$.contains($('body').find('.timepicker_wrap')[0],dom)|| $.contains($('body').find('.timepicker_wrap')[1],dom) else open=$.contains($('body').find('.timepicker_wrap')[0],dom) return open; } function setValue(inputbox, area){ area.eq(3).val()===undefined ? inputbox.val(area.eq(0).val()+':'+area.eq(1).val()+':'+area.eq(2).val()) : inputbox.val(area.eq(0).val()+':'+area.eq(1).val()+':'+area.eq(2).val()+':'+area.eq(3).val()); } function addNum(i){ return ++i; } function resuceNum(i){ return --i; } function closeIt() { $tab=$('.timepicker_wrap'); $tab.stop().fadeOut(1000); } window.onLoad=setTimearea(false); //show merdian or not; Empty to hide merdian select !function (){ 'use strict'; var $submit=$('input[type=submit]'); $inputbox.on('focus', function(){ var input = $(this),$tab=$(this.nextElementSibling); if (input.is($inputbox)) input.select(); $tab.stop().fadeIn(1000); setInit(input); }); $(document).on('click', function(e){ var _this=e.target; setTimeout(function(){ var focused_element = $(document.activeElement); if (!focused_element.is(':input') && !isSetTimeArea(_this)){ for(var i= 0, l=focused_element.find('.in_txt:visible').length; i<l; i++){ if(focused_element.find('.in_txt:visible')[i].value!== 'AM' && focused_element.find('.in_txt:visible')[i].value!=='PM'){ if(focused_element.find('.in_txt:visible')[i].value!==undefined){ $(focused_element.find('.in_txt:visible')[i]).val((addZero(parseInt(focused_element.find('.in_txt:visible')[i].value)))); } } } focused_element.find('.timepicker_wrap:visible')[0] !==undefined ? setValue($(focused_element.find('.timepicker_wrap:visible')[0].parentElement).find('.timepicker'), $(focused_element.find('.in_txt:visible'))): ''; closeIt(); } }, 0); }); $('.prev').on('click', function(e){ var $area=$(this.parentElement.parentElement).find('.in_txt'); checkTime($(e.target.nextElementSibling.children).val(), e.target); setValue($(this.parentNode.parentElement.previousElementSibling), $area); }); $('.next').on('click', function(e){ var $area=$(this.parentElement.parentElement).find('.in_txt'); checkTime($(e.target.previousElementSibling.children).val(), e.target); setValue($(this.parentNode.parentElement.previousElementSibling), $area); }); }(window, document);
sunitha-ramesh/CodeDeployGitHubDemo
codedeploydemopro/scripts/pickerjs.js
JavaScript
apache-2.0
5,874
/** * @license * Copyright 2019 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.u2', name: 'Dialog', extends: 'foam.u2.Element', documentation: `This class is a basic dialog container: it has a heading, a body, and a set of actions. Generally, use $$DOC{ref:"foam.u2.EasyDialog"} to easily handle simple cases. For more complex cases, you can put any Element you like into a $$DOC{ref:"foam.u2.ModalOverlay"}.`, requires: [ 'Action' ], imports: [ 'overlay' ], properties: [ 'title', 'body', { type: 'Array', name: 'buttons', documentation: `An array of buttons. Each is a [function, label] pair or an Action. These will be displayed in <em>reverse</em> order as MD buttons at the bottom of the dialog. The default is a single "OK" button that closes the dialog.`, factory: function() { return [[function() { this.overlay.close(); }.bind(this), 'OK']]; }, adapt: function(old, nu) { if ( nu ) { for ( var i = 0 ; i < nu.length ; i++ ) { if ( ! this.Action.isInstance(nu[i]) ) { nu[i] = this.Action.create({ name: nu[i][1], label: nu[i][1], code: nu[i][0] }); } } } return nu; } }, { class: 'Boolean', name: 'padding', documetation: 'Controls the padding inside the dialog.', attribute: true, value: true }, ], methods: [ function initE() { this.SUPER(); this.addClass(this.myClass()); if ( this.title ) { this.start() .addClass(this.myClass('header')) .enableClass(this.myClass('padding'), this.padding$) .add(this.title) .end(); } this.start() .addClass(this.myClass('body')) .enableClass(this.myClass('padding'), this.padding$) .add(this.body) .end(); this.start().addClass(this.myClass('buttons')).add(this.buttons).end(); } ], css: ` ^ { background-color: #fff; display: block; margin: 10px; overflow: hidden; } ^header { font-size: 20px; font-weight: 500; } ^padding { margin: 24px; } ^buttons { display: flex; flex-direction: row-reverse; } ` });
jacksonic/vjlofvhjfgm
src/foam/u2/Dialog.js
JavaScript
apache-2.0
2,464
// Copyright 2011 Traceur Authors. // // 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. suite('parser.js', function() { var errorReporter = { reportError: function(position, message) { throw new chai.AssertionError({message: message + ', ' + position}); } }; test('Module', function() { var program = 'module Foo { export var x = 42; ' + 'module M from \'url\'; ' + 'import z from \'x\'.y; ' + 'import * from M; ' + 'import {a:b,c} from M.x;' + '};\n'; var sourceFile = new traceur.syntax.SourceFile('Name', program); var parser = new traceur.syntax.Parser(errorReporter, sourceFile); parser.parseProgram(true); }); });
rwaldron/traceur-todomvc
test/unit/syntax/parser.js
JavaScript
apache-2.0
1,265
/*! * gulp-csscomb | https://github.com/koistya/gulp-csscomb * Copyright (c) Konstantin Tarkus (@koistya). See LICENSE.txt */ 'use strict'; var Comb = require('csscomb'); var fs = require('fs'); var gutil = require('gulp-util'); var path = require('path'); var through = require('through2'); var PluginError = gutil.PluginError; // Constants var PLUGIN_NAME = 'gulp-csscomb'; var SUPPORTED_EXTENSIONS = ['.css', '.sass', '.scss', '.less']; // Plugin level function (dealing with files) function Plugin(configPath, options) { if (arguments.length == 1 && typeof configPath === 'object') { options = configPath; configPath = options.configPath; } else if (arguments.length == 2 && typeof options === 'boolean') { options = { verbose: options }; // for backward compatibility } options = options || {}; configPath = configPath || null; var verbose = options.verbose || false; //var lint = options.lint || false; // TODO: Report about found issues in style sheets // Create a stream through which each file will pass var stream = through.obj(function(file, enc, cb) { if (file.isNull()) { // Do nothing } else if (file.isStream()) { this.emit('error', new PluginError(PLUGIN_NAME, 'Streams are not supported!')); return cb(); } else if (file.isBuffer() && SUPPORTED_EXTENSIONS.indexOf(path.extname(file.path)) !== -1) { if (verbose) { gutil.log(PLUGIN_NAME, 'Processing ' + gutil.colors.magenta(file.path)); } if (configPath && !fs.existsSync(configPath)) { this.emit('error', new PluginError(PLUGIN_NAME, 'Configuration file not found: ' + gutil.colors.magenta(configPath))); return cb(); } configPath = Comb.getCustomConfigPath(configPath || path.join(path.dirname(file.path), '.csscomb.json')); var config = Comb.getCustomConfig(configPath); if (verbose) { gutil.log(PLUGIN_NAME, 'Using configuration file ' + gutil.colors.magenta(configPath)); } var comb = new Comb(config || 'csscomb'); var syntax = options.syntax || file.path.split('.').pop(); try { var output = comb.processString( file.contents.toString('utf8'), { syntax: syntax, filename: file.path }); file.contents = new Buffer(output); } catch (err) { this.emit('error', new PluginError(PLUGIN_NAME, file.path + '\n' + err)); } } // make sure the file goes through the next gulp plugin this.push(file); // tell the stream engine that we are done with this file return cb(); }); // Return the file stream return stream; } // Export the plugin main function module.exports = Plugin;
athena-github/athena-github.github.io
xiangmuu--weizhan/node_modules/.3.0.8@gulp-csscomb/index.js
JavaScript
apache-2.0
2,726
//// [emitSuperCallBeforeEmitParameterPropertyDeclaration1.ts] class A { blub = 6; } class B extends A { constructor(public x: number) { "use strict"; 'someStringForEgngInject'; super() } } //// [emitSuperCallBeforeEmitParameterPropertyDeclaration1.js] var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { this.blub = 6; } return A; }()); var B = (function (_super) { __extends(B, _super); function B(x) { "use strict"; 'someStringForEgngInject'; var _this = _super.call(this) || this; _this.x = x; return _this; } return B; }(A));
jeremyepling/TypeScript
tests/baselines/reference/emitSuperCallBeforeEmitParameterPropertyDeclaration1.js
JavaScript
apache-2.0
917
/*! * Copyright 2014 Apereo Foundation (AF) Licensed under the * Educational Community 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://opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ var passport = require('passport'); var ConfigAPI = require('oae-config'); var OAE = require('oae-util/lib/oae'); var AuthenticationConfig = ConfigAPI.config('oae-authentication'); var AuthenticationConstants = require('oae-authentication/lib/constants').AuthenticationConstants; var AuthenticationUtil = require('oae-authentication/lib/util'); /** * @REST postAuthGoogle * * Log in using Google authentication * * @Server tenant * @Method POST * @Path /auth/google * @Return {void} * @HttpResponse 302 The user will be redirected to Google where they can log in * @HttpResponse 400 The authentication strategy is disabled for this tenant */ OAE.tenantRouter.on('post', '/api/auth/google', function(req, res, next) { // Get the ID under which we registered this strategy for this tenant var strategyId = AuthenticationUtil.getStrategyId(req.tenant, AuthenticationConstants.providers.GOOGLE); var options = { // To avoid authenticating with the wrong Google account, we give the user the opportunity to select or add // the correct account during the OAuth authentication cycle 'prompt': 'select_account' }; // If there's only one allowed domain, add that to options as the hosted domain // @see https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters var domains = AuthenticationConfig.getValue(req.tenant.alias, AuthenticationConstants.providers.GOOGLE, 'domains').split(','); if (domains && domains.length === 1) { options['hd'] = domains[0]; } // Perform the initial authentication step AuthenticationUtil.handleExternalSetup(strategyId, options, req, res, next); }); /** * @REST getAuthGoogleCallback * * Callback URL after the user has logged in using Google authentication * * @Api private * @Server tenant * @Method POST * @Path /auth/google/callback * @Return {void} */ OAE.tenantRouter.on('get', '/api/auth/google/callback', function(req, res, next) { // Get the ID under which we registered this strategy for this tenant var strategyId = AuthenticationUtil.getStrategyId(req.tenant, AuthenticationConstants.providers.GOOGLE); // Log the user in AuthenticationUtil.handleExternalCallback(strategyId, req, res, next); });
nicolaasmatthijs/Hilary
node_modules/oae-authentication/lib/strategies/google/rest.js
JavaScript
apache-2.0
2,999
'use strict'; const fs = require('fs'); const path = require('path'); const async = require('async'); const spawn = require('child_process').spawn; const clc = require('cli-color'); const allFailed = clc.red.bold; const allPassed = clc.green; const failed = clc.yellow; const passed = (t) => t; const files = fs.readdirSync(__dirname).filter(function (filename) { return filename.slice(0, 5) === 'test-'; }); async.mapSeries(files, runTest, function (err, passed) { if (err) throw err; let failed = 0; for (const ok of passed) { if (!ok) failed += 1; } if (failed > 0) { console.log(allFailed('failed') + ` - ${failed} tests failed`); } else { console.log(allPassed('passed') + ` - ${passed.length} tests passed`); } }); function runTest(filename, done) { process.stdout.write(` - running ${filename} ...`); const p = spawn(process.execPath, [path.resolve(__dirname, filename)], { stdio: ['ignore', 1, 2], env: { 'NODE_ASYNC_HOOK_NO_WARNING': '1' } }); p.once('close', function (statusCode) { const ok = (statusCode === 0); if (ok) { console.log(' ' + passed('ok')); } else { console.log(' - ' + failed('failed')); } done(null, ok); }); }
cloudfoundry/nodejs-buildpack
fixtures/with_appdynamics/node_modules/async-hook-jl/test/runner.js
JavaScript
apache-2.0
1,239
//// [staticAsIdentifier.ts] class C1 { static static [x: string]: string; } class C2 { static static m() {} } class C3 { static static p: string; } class C4 { static static foo() {} } //// [staticAsIdentifier.js] var C1 = /** @class */ (function () { function C1() { } return C1; }()); var C2 = /** @class */ (function () { function C2() { } C2.prototype.m = function () { }; return C2; }()); var C3 = /** @class */ (function () { function C3() { } return C3; }()); var C4 = /** @class */ (function () { function C4() { } C4.foo = function () { }; return C4; }());
kitsonk/TypeScript
tests/baselines/reference/staticAsIdentifier.js
JavaScript
apache-2.0
677
// Copyright 2015, EMC, Inc. 'use strict'; var di = require('di'), util = require('util'); module.exports = apcObmServiceFactory; di.annotate(apcObmServiceFactory, new di.Provide('apc-obm-service')); di.annotate(apcObmServiceFactory, new di.Inject('Promise', 'OBM.base', '_') ); function apcObmServiceFactory(Promise, BaseObmService, _) { function ApcObmService(options) { BaseObmService.call(this, options); this.requiredKeys = ['community', 'host', 'port']; this.mibCommand = 'PowerNet-MIB::sPDUOutletCtl'; } util.inherits(ApcObmService, BaseObmService); ApcObmService.prototype.reboot = function() { return this._runInternal([this.mibCommand + '.' + this.options.config.port, 'i', '3']); }; ApcObmService.prototype.powerOn = function() { return this._runInternal([this.mibCommand + '.' + this.options.config.port, 'i', '1']); }; ApcObmService.prototype.powerOff = function() { return this._runInternal([this.mibCommand + '.' + this.options.config.port, 'i', '2']); }; ApcObmService.prototype.powerStatus = function() { return this._runInternal([this.mibCommand + '.' + this.options.config.port], 'snmpwalk') .then(function (result) { if (_.contains(result.stdout, 'outletOn')) { return Promise.resolve(true); } if (_.contains(result.stdout, 'outletOff')) { return Promise.resolve(false); } return Promise.reject( new Error('Unable to determine power state (' + result.stdout + ').') ); }); }; ApcObmService.prototype._runInternal = function (command, file) { return this.run({ command: file || 'snmpset', args: [ '-v2c', '-c', this.options.config.community, this.options.config.host ].concat(command) }); }; ApcObmService.create = function(options) { return BaseObmService.create(ApcObmService, options); }; return ApcObmService; }
AlaricChan/on-tasks
lib/services/apc-obm-service.js
JavaScript
apache-2.0
2,121
// Generated by CoffeeScript 1.3.3 (function() { var InstagramMedia; InstagramMedia = (function() { function InstagramMedia(parent) { this.parent = parent; } /* Basic Media */ InstagramMedia.prototype.popular = function(params) { var credentials; credentials = this.parent._credentials({}); params['path'] = "/" + this.parent._api_version + "/media/popular?" + (this.parent._to_querystring(credentials)); return this.parent._request(params); }; InstagramMedia.prototype.info = function(params) { var credentials; credentials = this.parent._credentials({}); params['path'] = "/" + this.parent._api_version + "/media/" + params['media_id'] + "?" + (this.parent._to_querystring(credentials)); return this.parent._request(params); }; InstagramMedia.prototype.search = function(params) { params = this.parent._credentials(params); params['path'] = "/" + this.parent._api_version + "/media/search?" + (this.parent._to_querystring(params)); return this.parent._request(params); }; /* Likes */ InstagramMedia.prototype.likes = function(params) { var credentials; credentials = this.parent._credentials({}); params['path'] = "/" + this.parent._api_version + "/media/" + params['media_id'] + "/likes?" + (this.parent._to_querystring(credentials)); return this.parent._request(params); }; InstagramMedia.prototype.like = function(params) { params['post_data'] = this.parent._credentials({}, 'access_token'); params['method'] = 'POST'; params['path'] = "/" + this.parent._api_version + "/media/" + params['media_id'] + "/likes"; return this.parent._request(params); }; InstagramMedia.prototype.unlike = function(params) { params = this.parent._credentials(params, 'access_token'); params['method'] = 'DELETE'; params['path'] = "/" + this.parent._api_version + "/media/" + params['media_id'] + "/likes?" + (this.parent._to_querystring(params)); return this.parent._request(params); }; /* Comments */ InstagramMedia.prototype.comments = function(params) { var credentials; credentials = this.parent._credentials({}); params['path'] = "/" + this.parent._api_version + "/media/" + params['media_id'] + "/comments?" + (this.parent._to_querystring(credentials)); return this.parent._request(params); }; InstagramMedia.prototype.comment = function(params) { params['post_data'] = this.parent._credentials({ text: params['text'] }, 'access_token'); params['method'] = 'POST'; params['path'] = "/" + this.parent._api_version + "/media/" + params['media_id'] + "/comments"; return this.parent._request(params); }; InstagramMedia.prototype.uncomment = function(params) { var credentials; credentials = this.parent._credentials({}, 'access_token'); params['method'] = 'DELETE'; params['path'] = "/" + this.parent._api_version + "/media/" + params['media_id'] + "/comments/" + params['comment_id'] + "?" + (this.parent._to_querystring(credentials)); return this.parent._request(params); }; /* Subscriptions */ InstagramMedia.prototype.subscribe = function(params) { params['object'] = 'geography'; return this.parent.subscriptions._subscribe(params); }; InstagramMedia.prototype.unsubscribe = function(params) { return this.parent.subscriptions._unsubscribe(params); }; InstagramMedia.prototype.unsubscribe_all = function(params) { params['object'] = 'geography'; return this.parent.subscriptions._unsubscribe(params); }; return InstagramMedia; })(); module.exports = InstagramMedia; }).call(this);
Rmalnoult/pearlstagram-nodejs
node_modules/instagram-node-lib/lib/class.instagram.media.js
JavaScript
apache-2.0
3,838
/** * @license * Copyright 2018 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.nanos.auth.twofactor', name: 'AbstractTOTPAuthService', extends: 'foam.nanos.auth.twofactor.AbstractOTPAuthService', abstract: true, documentation: 'Abstract time-based one-time password auth service', javaImports: [ 'java.util.Date' ], methods: [ { name: 'checkCode', type: 'Boolean', args: [ { name: 'key', type: 'Byte[]' }, { name: 'code', type: 'Long' }, { name: 'stepsize', type: 'Long' }, { name: 'window', type: 'Integer' } ], javaCode: `try { long t = new Date().getTime() / stepsize; for (int i = -window; i <= window; ++i) { long hash = calculateCode(key, t + i); if (hash == code) { return true; } } return false; } catch (Throwable t) { return false; }` } ] });
jacksonic/vjlofvhjfgm
src/foam/nanos/auth/twofactor/AbstractTOTPAuthService.js
JavaScript
apache-2.0
1,063
/* * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. */ define([ 'underscore', 'knockout', "protocol", 'query-form-model', 'core-basedir/reports/qe/ui/js/common/qe.model.config' ], function (_, Knockout, protocolUtils, QueryFormModel, qeModelConfig) { var SearchFlowFormModel = QueryFormModel.extend({ defaultSelectFields: ['flow_class_id', 'direction_ing'], constructor: function (modelData) { var defaultConfig = qeModelConfig.getQueryModelConfig({ table_name: cowc.FLOW_RECORD_TABLE, limit: 5000, time_range: 600, table_type: cowc.QE_FLOW_TABLE_TYPE, filters: '', filter_json: '', select: "other_vrouter_ip, vrouter, vrouter_ip," + "sourcevn, sourceip, sport, destvn," + "destip, dport, protocol, agg-bytes," + "agg-packets, direction_ing", query_prefix: cowc.FR_QUERY_PREFIX}); modelData = $.extend(true, {}, defaultConfig, modelData); QueryFormModel.prototype.constructor.call(this, modelData); this.setTableFieldValues(); return this; }, setTableFieldValues: function () { var searchFlowModel = this.model(); var valueOptionList = { vrouter: [], sourcevn: [], destvn: [], protocol: [] }; searchFlowModel.attributes.where_data_object['value_option_list'] = valueOptionList; var protocolData = []; $.each(protocolUtils.protocolList, function(idx, obj) { protocolData.push(obj['name']); }); valueOptionList['protocol'] = protocolData; $.ajax({ url: '/api/admin/networks', dataType: 'json' }).done(function (response){ var vnList = getValueByJsonPath(response, 'virtual-networks', []), results = []; for (var i = 0; i < vnList.length; i++) { var vnObj = vnList[i]; if (vnObj['fq_name'] != null) { var fqn = vnObj['fq_name'].join(':'); results.push(fqn); } } valueOptionList['sourcevn'] = results; valueOptionList['destvn'] = results; }); $.ajax({ url: '/api/admin/monitor/infrastructure/vrouters/cached-summary', dataType: 'json' }).done(function (response) { var vRouterList = getValueByJsonPath(response,'data',[]), results = []; for (var i = 0; i < vRouterList.length; i++) { var vRouterName = vRouterList[i]['name']; results.push(vRouterName); } valueOptionList['vrouter'] = results; }); }, getTimeGranularityUnits: function() { var self = this; return Knockout.computed(function () { var timeRange = self.time_range(), fromTime = new Date(self.from_time()).getTime(), toTime = new Date(self.to_time()).getTime(), timeGranularityUnits = []; timeGranularityUnits.push({id: "secs", text: "secs"}); if (timeRange == -1) { timeRange = (toTime - fromTime) / 1000; } if (timeRange > 60) { timeGranularityUnits.push({id: "mins", text: "mins"}); } if (timeRange > 3600) { timeGranularityUnits.push({id: "hrs", text: "hrs"}); } if (timeRange > 86400) { timeGranularityUnits.push({id: "days", text: "days"}); } return timeGranularityUnits; }, this); }, validations: {} }); return SearchFlowFormModel; });
vishnuvv/contrail-web-controller
webroot/monitor/infrastructure/underlay/ui/js/models/SearchFlowFormModel.js
JavaScript
apache-2.0
4,508
(function() { 'use strict'; angular.module('newplayer.service', []); })();
thenewgroup/elx-newplayer
app/scripts/service/service.module.js
JavaScript
apache-2.0
80
define([ '../Core/Cartesian3', '../Core/defined', '../Core/Intersect', '../Core/ManagedArray', '../Core/Math', './Cesium3DTileOptimizationHint', './Cesium3DTileRefine' ], function( Cartesian3, defined, Intersect, ManagedArray, CesiumMath, Cesium3DTileOptimizationHint, Cesium3DTileRefine) { 'use strict'; /** * @private */ function Cesium3DTilesetTraversal() { } function isVisible(tile) { return tile._visible && tile._inRequestVolume; } var traversal = { stack : new ManagedArray(), stackMaximumLength : 0 }; var emptyTraversal = { stack : new ManagedArray(), stackMaximumLength : 0 }; var descendantTraversal = { stack : new ManagedArray(), stackMaximumLength : 0 }; var selectionTraversal = { stack : new ManagedArray(), stackMaximumLength : 0, ancestorStack : new ManagedArray(), ancestorStackMaximumLength : 0 }; var descendantSelectionDepth = 2; Cesium3DTilesetTraversal.selectTiles = function(tileset, frameState) { tileset._requestedTiles.length = 0; if (tileset.debugFreezeFrame) { return; } tileset._selectedTiles.length = 0; tileset._selectedTilesToStyle.length = 0; tileset._emptyTiles.length = 0; tileset._hasMixedContent = false; var root = tileset.root; updateTile(tileset, root, frameState); // The root tile is not visible if (!isVisible(root)) { return; } // The tileset doesn't meet the SSE requirement, therefore the tree does not need to be rendered if (root.getScreenSpaceError(frameState, true) <= tileset._maximumScreenSpaceError) { return; } if (!skipLevelOfDetail(tileset)) { executeBaseTraversal(tileset, root, frameState); } else if (tileset.immediatelyLoadDesiredLevelOfDetail) { executeSkipTraversal(tileset, root, frameState); } else { executeBaseAndSkipTraversal(tileset, root, frameState); } traversal.stack.trim(traversal.stackMaximumLength); emptyTraversal.stack.trim(emptyTraversal.stackMaximumLength); descendantTraversal.stack.trim(descendantTraversal.stackMaximumLength); selectionTraversal.stack.trim(selectionTraversal.stackMaximumLength); selectionTraversal.ancestorStack.trim(selectionTraversal.ancestorStackMaximumLength); // Update the priority for any requests found during traversal // Update after traversal so that min and max values can be used to normalize priority values var requestedTiles = tileset._requestedTiles; var length = requestedTiles.length; for (var i = 0; i < length; ++i) { requestedTiles[i].updatePriority(); } }; function executeBaseTraversal(tileset, root, frameState) { var baseScreenSpaceError = tileset._maximumScreenSpaceError; var maximumScreenSpaceError = tileset._maximumScreenSpaceError; executeTraversal(tileset, root, baseScreenSpaceError, maximumScreenSpaceError, frameState); } function executeSkipTraversal(tileset, root, frameState) { var baseScreenSpaceError = Number.MAX_VALUE; var maximumScreenSpaceError = tileset._maximumScreenSpaceError; executeTraversal(tileset, root, baseScreenSpaceError, maximumScreenSpaceError, frameState); traverseAndSelect(tileset, root, frameState); } function executeBaseAndSkipTraversal(tileset, root, frameState) { var baseScreenSpaceError = Math.max(tileset.baseScreenSpaceError, tileset.maximumScreenSpaceError); var maximumScreenSpaceError = tileset.maximumScreenSpaceError; executeTraversal(tileset, root, baseScreenSpaceError, maximumScreenSpaceError, frameState); traverseAndSelect(tileset, root, frameState); } function skipLevelOfDetail(tileset) { return tileset._skipLevelOfDetail; } function addEmptyTile(tileset, tile) { tileset._emptyTiles.push(tile); } function selectTile(tileset, tile, frameState) { if (tile.contentVisibility(frameState) !== Intersect.OUTSIDE) { var tileContent = tile.content; if (tileContent.featurePropertiesDirty) { // A feature's property in this tile changed, the tile needs to be re-styled. tileContent.featurePropertiesDirty = false; tile.lastStyleTime = 0; // Force applying the style to this tile tileset._selectedTilesToStyle.push(tile); } else if ((tile._selectedFrame < frameState.frameNumber - 1)) { // Tile is newly selected; it is selected this frame, but was not selected last frame. tileset._selectedTilesToStyle.push(tile); } tile._selectedFrame = frameState.frameNumber; tileset._selectedTiles.push(tile); } } function selectDescendants(tileset, root, frameState) { var stack = descendantTraversal.stack; stack.push(root); while (stack.length > 0) { descendantTraversal.stackMaximumLength = Math.max(descendantTraversal.stackMaximumLength, stack.length); var tile = stack.pop(); var children = tile.children; var childrenLength = children.length; for (var i = 0; i < childrenLength; ++i) { var child = children[i]; if (isVisible(child)) { if (child.contentAvailable) { updateTile(tileset, child, frameState); touchTile(tileset, child, frameState); selectTile(tileset, child, frameState); } else if (child._depth - root._depth < descendantSelectionDepth) { // Continue traversing, but not too far stack.push(child); } } } } } function selectDesiredTile(tileset, tile, frameState) { if (!skipLevelOfDetail(tileset)) { if (tile.contentAvailable) { // The tile can be selected right away and does not require traverseAndSelect selectTile(tileset, tile, frameState); } return; } // If this tile is not loaded attempt to select its ancestor instead var loadedTile = tile.contentAvailable ? tile : tile._ancestorWithContentAvailable; if (defined(loadedTile)) { // Tiles will actually be selected in traverseAndSelect loadedTile._shouldSelect = true; } else { // If no ancestors are ready traverse down and select tiles to minimize empty regions. // This happens often for immediatelyLoadDesiredLevelOfDetail where parent tiles are not necessarily loaded before zooming out. selectDescendants(tileset, tile, frameState); } } function visitTile(tileset, tile, frameState) { ++tileset._statistics.visited; tile._visitedFrame = frameState.frameNumber; } function touchTile(tileset, tile, frameState) { if (tile._touchedFrame === frameState.frameNumber) { // Prevents another pass from touching the frame again return; } tileset._cache.touch(tile); tile._touchedFrame = frameState.frameNumber; } function updateMinimumMaximumPriority(tileset, tile) { tileset._maximumPriority.distance = Math.max(tile._priorityHolder._distanceToCamera, tileset._maximumPriority.distance); tileset._minimumPriority.distance = Math.min(tile._priorityHolder._distanceToCamera, tileset._minimumPriority.distance); tileset._maximumPriority.depth = Math.max(tile._depth, tileset._maximumPriority.depth); tileset._minimumPriority.depth = Math.min(tile._depth, tileset._minimumPriority.depth); tileset._maximumPriority.foveatedFactor = Math.max(tile._priorityHolder._foveatedFactor, tileset._maximumPriority.foveatedFactor); tileset._minimumPriority.foveatedFactor = Math.min(tile._priorityHolder._foveatedFactor, tileset._minimumPriority.foveatedFactor); tileset._maximumPriority.reverseScreenSpaceError = Math.max(tile._priorityReverseScreenSpaceError, tileset._maximumPriority.reverseScreenSpaceError); tileset._minimumPriority.reverseScreenSpaceError = Math.min(tile._priorityReverseScreenSpaceError, tileset._minimumPriority.reverseScreenSpaceError); } function isOnScreenLongEnough(tileset, tile, frameState) { // Prevent unnecessary loads while camera is moving by getting the ratio of travel distance to tile size. if (!tileset.cullRequestsWhileMoving) { return true; } var sphere = tile.boundingSphere; var diameter = Math.max(sphere.radius * 2.0, 1.0); var camera = frameState.camera; var deltaMagnitude = camera.positionWCDeltaMagnitude !== 0.0 ? camera.positionWCDeltaMagnitude : camera.positionWCDeltaMagnitudeLastFrame; var movementRatio = tileset.cullRequestsWhileMovingMultiplier * deltaMagnitude / diameter; // How do n frames of this movement compare to the tile's physical size. return movementRatio < 1.0; } function loadTile(tileset, tile, frameState) { if (tile._requestedFrame === frameState.frameNumber || (!hasUnloadedContent(tile) && !tile.contentExpired)) { return; } if (!isOnScreenLongEnough(tileset, tile, frameState)) { return; } var cameraHasNotStoppedMovingLongEnough = frameState.camera.timeSinceMoved < tileset.foveatedTimeDelay; if (tile.priorityDeferred && cameraHasNotStoppedMovingLongEnough) { return; } tile._requestedFrame = frameState.frameNumber; tileset._requestedTiles.push(tile); } function updateVisibility(tileset, tile, frameState) { if (tile._updatedVisibilityFrame === tileset._updatedVisibilityFrame) { // Return early if visibility has already been checked during the traversal. // The visibility may have already been checked if the cullWithChildrenBounds optimization is used. return; } tile.updateVisibility(frameState); tile._updatedVisibilityFrame = tileset._updatedVisibilityFrame; } function anyChildrenVisible(tileset, tile, frameState) { var anyVisible = false; var children = tile.children; var length = children.length; for (var i = 0; i < length; ++i) { var child = children[i]; updateVisibility(tileset, child, frameState); anyVisible = anyVisible || isVisible(child); } return anyVisible; } function meetsScreenSpaceErrorEarly(tileset, tile, frameState) { var parent = tile.parent; if (!defined(parent) || parent.hasTilesetContent || (parent.refine !== Cesium3DTileRefine.ADD)) { return false; } // Use parent's geometric error with child's box to see if the tile already meet the SSE return tile.getScreenSpaceError(frameState, true) <= tileset._maximumScreenSpaceError; } function updateTileVisibility(tileset, tile, frameState) { updateVisibility(tileset, tile, frameState); if (!isVisible(tile)) { return; } var hasChildren = tile.children.length > 0; if (tile.hasTilesetContent && hasChildren) { // Use the root tile's visibility instead of this tile's visibility. // The root tile may be culled by the children bounds optimization in which // case this tile should also be culled. var child = tile.children[0]; updateTileVisibility(tileset, child, frameState); tile._visible = child._visible; return; } if (meetsScreenSpaceErrorEarly(tileset, tile, frameState)) { tile._visible = false; return; } // Optimization - if none of the tile's children are visible then this tile isn't visible var replace = tile.refine === Cesium3DTileRefine.REPLACE; var useOptimization = tile._optimChildrenWithinParent === Cesium3DTileOptimizationHint.USE_OPTIMIZATION; if (replace && useOptimization && hasChildren) { if (!anyChildrenVisible(tileset, tile, frameState)) { ++tileset._statistics.numberOfTilesCulledWithChildrenUnion; tile._visible = false; return; } } } function updateTile(tileset, tile, frameState) { // Reset some of the tile's flags and re-evaluate visibility updateTileVisibility(tileset, tile, frameState); tile.updateExpiration(); // Request priority tile._wasMinPriorityChild = false; tile._priorityHolder = tile; updateMinimumMaximumPriority(tileset, tile); // SkipLOD tile._shouldSelect = false; tile._finalResolution = true; } function updateTileAncestorContentLinks(tile, frameState) { tile._ancestorWithContent = undefined; tile._ancestorWithContentAvailable = undefined; var parent = tile.parent; if (defined(parent)) { // ancestorWithContent is an ancestor that has content or has the potential to have // content. Used in conjunction with tileset.skipLevels to know when to skip a tile. // ancestorWithContentAvailable is an ancestor that is rendered if a desired tile is not loaded. var hasContent = !hasUnloadedContent(parent) || (parent._requestedFrame === frameState.frameNumber); tile._ancestorWithContent = hasContent ? parent : parent._ancestorWithContent; tile._ancestorWithContentAvailable = parent.contentAvailable ? parent : parent._ancestorWithContentAvailable; // Links a descendant up to its contentAvailable ancestor as the traversal progresses. } } function hasEmptyContent(tile) { return tile.hasEmptyContent || tile.hasTilesetContent; } function hasUnloadedContent(tile) { return !hasEmptyContent(tile) && tile.contentUnloaded; } function reachedSkippingThreshold(tileset, tile) { var ancestor = tile._ancestorWithContent; return !tileset.immediatelyLoadDesiredLevelOfDetail && (tile._priorityProgressiveResolutionScreenSpaceErrorLeaf || (defined(ancestor) && (tile._screenSpaceError < (ancestor._screenSpaceError / tileset.skipScreenSpaceErrorFactor)) && (tile._depth > (ancestor._depth + tileset.skipLevels)))); } function sortChildrenByDistanceToCamera(a, b) { // Sort by farthest child first since this is going on a stack if (b._distanceToCamera === 0 && a._distanceToCamera === 0) { return b._centerZDepth - a._centerZDepth; } return b._distanceToCamera - a._distanceToCamera; } function updateAndPushChildren(tileset, tile, stack, frameState) { var i; var replace = tile.refine === Cesium3DTileRefine.REPLACE; var children = tile.children; var length = children.length; for (i = 0; i < length; ++i) { updateTile(tileset, children[i], frameState); } // Sort by distance to take advantage of early Z and reduce artifacts for skipLevelOfDetail children.sort(sortChildrenByDistanceToCamera); // For traditional replacement refinement only refine if all children are loaded. // Empty tiles are exempt since it looks better if children stream in as they are loaded to fill the empty space. var checkRefines = !skipLevelOfDetail(tileset) && replace && !hasEmptyContent(tile); var refines = true; var anyChildrenVisible = false; // Determining min child var minIndex = -1; var minimumPriority = Number.MAX_VALUE; var child; for (i = 0; i < length; ++i) { child = children[i]; if (isVisible(child)) { stack.push(child); if (child._foveatedFactor < minimumPriority) { minIndex = i; minimumPriority = child._foveatedFactor; } anyChildrenVisible = true; } else if (checkRefines || tileset.loadSiblings) { // Keep non-visible children loaded since they are still needed before the parent can refine. // Or loadSiblings is true so always load tiles regardless of visibility. if (child._foveatedFactor < minimumPriority) { minIndex = i; minimumPriority = child._foveatedFactor; } loadTile(tileset, child, frameState); touchTile(tileset, child, frameState); } if (checkRefines) { var childRefines; if (!child._inRequestVolume) { childRefines = false; } else if (hasEmptyContent(child)) { childRefines = executeEmptyTraversal(tileset, child, frameState); } else { childRefines = child.contentAvailable; } refines = refines && childRefines; } } if (!anyChildrenVisible) { refines = false; } if (minIndex !== -1 && !skipLevelOfDetail(tileset) && replace) { // An ancestor will hold the _foveatedFactor and _distanceToCamera for descendants between itself and its highest priority descendant. Siblings of a min children along the way use this ancestor as their priority holder as well. // Priority of all tiles that refer to the _foveatedFactor and _distanceToCamera stored in the common ancestor will be differentiated based on their _depth. var minPriorityChild = children[minIndex]; minPriorityChild._wasMinPriorityChild = true; var priorityHolder = (tile._wasMinPriorityChild || tile === tileset.root) && minimumPriority <= tile._priorityHolder._foveatedFactor ? tile._priorityHolder : tile; // This is where priority dependency chains are wired up or started anew. priorityHolder._foveatedFactor = Math.min(minPriorityChild._foveatedFactor, priorityHolder._foveatedFactor); priorityHolder._distanceToCamera = Math.min(minPriorityChild._distanceToCamera, priorityHolder._distanceToCamera); for (i = 0; i < length; ++i) { child = children[i]; child._priorityHolder = priorityHolder; } } return refines; } function inBaseTraversal(tileset, tile, baseScreenSpaceError) { if (!skipLevelOfDetail(tileset)) { return true; } if (tileset.immediatelyLoadDesiredLevelOfDetail) { return false; } if (!defined(tile._ancestorWithContent)) { // Include root or near-root tiles in the base traversal so there is something to select up to return true; } if (tile._screenSpaceError === 0.0) { // If a leaf, use parent's SSE return tile.parent._screenSpaceError > baseScreenSpaceError; } return tile._screenSpaceError > baseScreenSpaceError; } function canTraverse(tileset, tile) { if (tile.children.length === 0) { return false; } if (tile.hasTilesetContent) { // Traverse external tileset to visit its root tile // Don't traverse if the subtree is expired because it will be destroyed return !tile.contentExpired; } return tile._screenSpaceError > tileset._maximumScreenSpaceError; } function executeTraversal(tileset, root, baseScreenSpaceError, maximumScreenSpaceError, frameState) { // Depth-first traversal that traverses all visible tiles and marks tiles for selection. // If skipLevelOfDetail is off then a tile does not refine until all children are loaded. // This is the traditional replacement refinement approach and is called the base traversal. // Tiles that have a greater screen space error than the base screen space error are part of the base traversal, // all other tiles are part of the skip traversal. The skip traversal allows for skipping levels of the tree // and rendering children and parent tiles simultaneously. var stack = traversal.stack; stack.push(root); while (stack.length > 0) { traversal.stackMaximumLength = Math.max(traversal.stackMaximumLength, stack.length); var tile = stack.pop(); updateTileAncestorContentLinks(tile, frameState); var baseTraversal = inBaseTraversal(tileset, tile, baseScreenSpaceError); var add = tile.refine === Cesium3DTileRefine.ADD; var replace = tile.refine === Cesium3DTileRefine.REPLACE; var parent = tile.parent; var parentRefines = !defined(parent) || parent._refines; var refines = false; if (canTraverse(tileset, tile)) { refines = updateAndPushChildren(tileset, tile, stack, frameState) && parentRefines; } var stoppedRefining = !refines && parentRefines; if (hasEmptyContent(tile)) { // Add empty tile just to show its debug bounding volume // If the tile has tileset content load the external tileset // If the tile cannot refine further select its nearest loaded ancestor addEmptyTile(tileset, tile, frameState); loadTile(tileset, tile, frameState); if (stoppedRefining) { selectDesiredTile(tileset, tile, frameState); } } else if (add) { // Additive tiles are always loaded and selected selectDesiredTile(tileset, tile, frameState); loadTile(tileset, tile, frameState); } else if (replace) { if (baseTraversal) { // Always load tiles in the base traversal // Select tiles that can't refine further loadTile(tileset, tile, frameState); if (stoppedRefining) { selectDesiredTile(tileset, tile, frameState); } } else if (stoppedRefining) { // In skip traversal, load and select tiles that can't refine further selectDesiredTile(tileset, tile, frameState); loadTile(tileset, tile, frameState); } else if (reachedSkippingThreshold(tileset, tile)) { // In skip traversal, load tiles that aren't skipped. In practice roughly half the tiles stay unloaded. loadTile(tileset, tile, frameState); } } visitTile(tileset, tile, frameState); touchTile(tileset, tile, frameState); tile._refines = refines; } } function executeEmptyTraversal(tileset, root, frameState) { // Depth-first traversal that checks if all nearest descendants with content are loaded. Ignores visibility. var allDescendantsLoaded = true; var stack = emptyTraversal.stack; stack.push(root); while (stack.length > 0) { emptyTraversal.stackMaximumLength = Math.max(emptyTraversal.stackMaximumLength, stack.length); var tile = stack.pop(); var children = tile.children; var childrenLength = children.length; // Only traverse if the tile is empty - traversal stop at descendants with content var traverse = hasEmptyContent(tile) && canTraverse(tileset, tile); // Traversal stops but the tile does not have content yet. // There will be holes if the parent tries to refine to its children, so don't refine. if (!traverse && !tile.contentAvailable) { allDescendantsLoaded = false; } updateTile(tileset, tile, frameState); if (!isVisible(tile)) { // Load tiles that aren't visible since they are still needed for the parent to refine loadTile(tileset, tile, frameState); touchTile(tileset, tile, frameState); } if (traverse) { for (var i = 0; i < childrenLength; ++i) { var child = children[i]; stack.push(child); } } } return allDescendantsLoaded; } /** * Traverse the tree and check if their selected frame is the current frame. If so, add it to a selection queue. * This is a preorder traversal so children tiles are selected before ancestor tiles. * * The reason for the preorder traversal is so that tiles can easily be marked with their * selection depth. A tile's _selectionDepth is its depth in the tree where all non-selected tiles are removed. * This property is important for use in the stencil test because we want to render deeper tiles on top of their * ancestors. If a tileset is very deep, the depth is unlikely to fit into the stencil buffer. * * We want to select children before their ancestors because there is no guarantee on the relationship between * the children's z-depth and the ancestor's z-depth. We cannot rely on Z because we want the child to appear on top * of ancestor regardless of true depth. The stencil tests used require children to be drawn first. * * NOTE: 3D Tiles uses 3 bits from the stencil buffer meaning this will not work when there is a chain of * selected tiles that is deeper than 7. This is not very likely. */ function traverseAndSelect(tileset, root, frameState) { var stack = selectionTraversal.stack; var ancestorStack = selectionTraversal.ancestorStack; var lastAncestor; stack.push(root); while (stack.length > 0 || ancestorStack.length > 0) { selectionTraversal.stackMaximumLength = Math.max(selectionTraversal.stackMaximumLength, stack.length); selectionTraversal.ancestorStackMaximumLength = Math.max(selectionTraversal.ancestorStackMaximumLength, ancestorStack.length); if (ancestorStack.length > 0) { var waitingTile = ancestorStack.peek(); if (waitingTile._stackLength === stack.length) { ancestorStack.pop(); if (waitingTile !== lastAncestor) { waitingTile._finalResolution = false; } selectTile(tileset, waitingTile, frameState); continue; } } var tile = stack.pop(); if (!defined(tile)) { // stack is empty but ancestorStack isn't continue; } var add = tile.refine === Cesium3DTileRefine.ADD; var shouldSelect = tile._shouldSelect; var children = tile.children; var childrenLength = children.length; var traverse = canTraverse(tileset, tile); if (shouldSelect) { if (add) { selectTile(tileset, tile, frameState); } else { tile._selectionDepth = ancestorStack.length; if (tile._selectionDepth > 0) { tileset._hasMixedContent = true; } lastAncestor = tile; if (!traverse) { selectTile(tileset, tile, frameState); continue; } ancestorStack.push(tile); tile._stackLength = stack.length; } } if (traverse) { for (var i = 0; i < childrenLength; ++i) { var child = children[i]; if (isVisible(child)) { stack.push(child); } } } } } return Cesium3DTilesetTraversal; });
geoscan/cesium
Source/Scene/Cesium3DTilesetTraversal.js
JavaScript
apache-2.0
28,819
var Main = function(){ this.domain = ''; this.pname = '免费版'; this.days = []; this.months = []; this.flowDayData = []; this.cacheDayData = []; this.flowMontyData = []; this.cacheMonthData = []; this.getInfo = function() { var that = this; $.ajax({ url : '/api/?c=record&a=getDomainInfo', dataType : 'json', success : function(a) { if (a.status.code != 1) { that.renderLoginError(); return; } that.domain = a.domain.name; that.pname = a.domain.pname; $("#domain_name_show").html(that.domain); $("#domain_pname_show").html(that.pname).parent('a').attr('href','?c=product&a=index&domain='+that.domain); that.getFlow(); //that.render(); if(a.domain['cdn_id'] == 0){ $("#popup").css('display','block'); $("#msg").html("<a href='?c=cdn&a=index&domain="+that.domain+"' style='color:red'>请先增加CDN站点</a>"); $("#msg").css("display","block"); } }, error : function(e) { that.showError('后台数据出错' + e.responseText); } }); } this.getFlow = function(){ var that = this; $.ajax({ url:'/api/?c=record&a=getCdnFlow', dataType:'json', success:function(a){ //alert('s'); if(a.status.code == 1){ that.days = a.days; that.months = a.months; that.render(); return; } that.render(); return; }, error:function(a){ alert('error'); } }); } this.render = function() { this.renderDay(); this.renderMonth(); } this.showError = function(msg){ alert(msg); } this.getDayRatio = function(index) { flowval = this.flowDayData[index]; cacheval = this.cacheDayData[index]; return Highcharts.numberFormat(cacheval*100/flowval,2); } this.getMonthRatio = function(index) { flowval = this.flowMonthData[index]; cacheval = this.cacheMonthData[index]; return Highcharts.numberFormat(cacheval*100/flowval,2); } this.renderDay = function() { var that = this; var data = this.days; var flow = {}; var cache = {}; var options = { chart : { defaultSeriesType : 'line', renderTo : 'query_day', inverted : false }, title : { text : '最近24小时流量(蓝色),缓存(绿色)统计图' }, subtitle : { text : '', x : 80 }, xAxis : { categories : [] }, yAxis : { title : { text : '流量' } }, credits:{ enabled: true, position: { align: 'right', x: -10, y: -10 }, href: "https://www.cdnbest.com", style: { color:'blue' }, text: "CDN贝" }, legend : { enabled : false }, tooltip : { valueSuffix:'{value}m', formatter : function() { var str = '流量:' + Highcharts.numberFormat(this.y, 1) + ' byte<br/>当前时间:' + this.x + '点'; str += ",缓存命中率:" + that.getDayRatio(this.point.x) + "%"; return str } }, series : [] }; flow.name = '流量'; //线条颜色 //flow.color = '#89A54E'; //显示方式,柱子还是线条或其它 //flow.type = 'spline'; flow.data = []; for ( var i in data.cate) { flow.data.push(data.nums[data.cate[i]]); } for ( var i in data.cate) { options.xAxis.categories.push(data.cate[i].substr(-2)); } this.flowDayData = flow.data; cache.name = "缓存"; //cache.color = 'red', //cache.type = 'spline'; cache.data = []; for ( var i in data.cate) { cache.data.push(data.cache[data.cate[i]]); } this.cacheDayData = cache.data; options.series.push(flow); options.series.push(cache); var chat = new Highcharts.Chart(options); } this.renderMonth = function() { var that = this; var data = this.months; var options = { chart : { defaultSeriesType : 'line', renderTo : 'query_month', inverted : false }, title : { text : '最近30天流量(蓝色),缓存(绿色)统计图' }, subtitle : { text : '', x : 80 }, credits:{ enabled: true, position: { align: 'right', x: -10, y: -10 }, href: "https://www.cdnbest.com", style: { color:'blue' }, text: "CDN贝" }, xAxis : { categories : [] }, yAxis : { title : { text : '流量' } }, legend : { enabled : false }, tooltip : { formatter : function() { var str = '流量:' + Highcharts.numberFormat(this.y, 1) + ' byte<br/>当前时间:' + this.x + '日'; str += ",缓存命中率:" + that.getMonthRatio(this.point.x) + "%"; return str } }, series : [] }; var flow = {}; flow.name = '流量'; flow.data = []; for ( var i in data.cate) { flow.data.push(data.nums[data.cate[i]]); } this.flowMonthData = flow.data; for ( var i in data.cate) { options.xAxis.categories.push(data.cate[i].substr(-2)); } options.series.push(flow); var cache = {}; cache.name = "缓存"; cache.data = []; for ( var i in data.cate) { cache.data.push(data.cache[data.cate[i]]); } this.cacheMonthData = cache.data; options.series.push(cache); var chat = new Highcharts.Chart(options); } this.renderLoginError = function() { var template = $("#site-nologin-template").html(); $("#h").append(template); } } $(document).ready(function(){ $("#record-operat").find('#cdnflow').find('a').addClass('cur'); $("#nav_domain").addClass("cur"); var main = new Main(); main.getInfo(); });
zdchao/php_demo
wwwroot/wwwroot/user/view/new0807/record/cdnflow.js
JavaScript
apache-2.0
5,652
/** * Copyright 2016 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 { is3pThrottled, getAmpAdRenderOutsideViewport, incrementLoadingAds, } from '../../amp-ad/0.1/concurrent-load'; import {adConfig} from '../../../ads/_config'; import {signingServerURLs} from '../../../ads/_a4a-config'; import { removeChildren, createElementWithAttributes, } from '../../../src/dom'; import {cancellation, isCancellation} from '../../../src/error'; import { installAnchorClickInterceptor, } from '../../../src/anchor-click-interceptor'; import { installFriendlyIframeEmbed, setFriendlyIframeEmbedVisible, } from '../../../src/friendly-iframe-embed'; import {isLayoutSizeDefined} from '../../../src/layout'; import {isAdPositionAllowed} from '../../../src/ad-helper'; import {dev, user} from '../../../src/log'; import {getMode} from '../../../src/mode'; import {isArray, isObject, isEnumValue} from '../../../src/types'; import {some} from '../../../src/utils/promise'; import {utf8Decode} from '../../../src/utils/bytes'; import {viewerForDoc} from '../../../src/viewer'; import {xhrFor} from '../../../src/xhr'; import {endsWith} from '../../../src/string'; import {platformFor} from '../../../src/platform'; import {cryptoFor} from '../../../src/crypto'; import {isExperimentOn} from '../../../src/experiments'; import {setStyle} from '../../../src/style'; import {handleClick} from '../../../ads/alp/handler'; import {AdDisplayState} from '../../../extensions/amp-ad/0.1/amp-ad-ui'; import { getDefaultBootstrapBaseUrl, generateSentinel, } from '../../../src/3p-frame'; import { installUrlReplacementsForEmbed, } from '../../../src/service/url-replacements-impl'; import {extensionsFor} from '../../../src/extensions'; import {A4AVariableSource} from './a4a-variable-source'; // TODO(tdrl): Temporary. Remove when we migrate to using amp-analytics. import {getTimingDataAsync} from '../../../src/service/variable-source'; import {getContextMetadata} from '../../../src/iframe-attributes'; /** @type {string} */ const METADATA_STRING = '<script type="application/json" amp-ad-metadata>'; /** @type {string} */ const METADATA_STRING_NO_QUOTES = '<script type=application/json amp-ad-metadata>'; // TODO(tdrl): Temporary, while we're verifying whether SafeFrame is an // acceptable solution to the 'Safari on iOS doesn't fetch iframe src from // cache' issue. See https://github.com/ampproject/amphtml/issues/5614 /** @type {string} */ const SAFEFRAME_VERSION = '1-0-5'; /** @type {string} @visibleForTesting */ export const SAFEFRAME_IMPL_PATH = 'https://tpc.googlesyndication.com/safeframe/' + SAFEFRAME_VERSION + '/html/container.html'; /** @type {string} @visibleForTesting */ export const RENDERING_TYPE_HEADER = 'X-AmpAdRender'; /** @type {string} */ const TAG = 'amp-a4a'; /** @type {string} */ const NO_CONTENT_RESPONSE = 'NO-CONTENT-RESPONSE'; /** @enum {string} */ export const XORIGIN_MODE = { CLIENT_CACHE: 'client_cache', SAFEFRAME: 'safeframe', NAMEFRAME: 'nameframe', }; /** @type {!Object} @private */ const SHARED_IFRAME_PROPERTIES = { frameborder: '0', allowfullscreen: '', allowtransparency: '', scrolling: 'no', marginwidth: '0', marginheight: '0', }; /** @typedef {{ * creative: ArrayBuffer, * signature: ?Uint8Array, * size: ?Array<number> * }} */ export let AdResponseDef; /** @typedef {{ minifiedCreative: string, customElementExtensions: !Array<string>, customStylesheets: !Array<{href: string}> }} */ let CreativeMetaDataDef; /** * A set of public keys for a single AMP signing service. A single service may * return more than one key if, e.g., they're rotating keys and they serve * the current and upcoming keys. A CryptoKeysDef stores one or more * (promises to) keys, in the order given by the return value from the * signing service. * * @typedef {{serviceName: string, keys: !Array<!Promise<!../../../src/crypto.PublicKeyInfoDef>>}} */ let CryptoKeysDef; /** * The public keys for all signing services. This is an array of promises, * one per signing service, in the order given by the array returned by * #getSigningServiceNames(). Each entry resolves to the keys returned by * that service, represented by a `CryptoKeysDef` object. * * @typedef {Array<!Promise<!CryptoKeysDef>>} */ let AllServicesCryptoKeysDef; /** @private */ export const LIFECYCLE_STAGES = { // Note: Use strings as values here, rather than numbers, so that "0" does // not test as `false` later. adSlotCleared: '-1', urlBuilt: '1', adRequestStart: '2', adRequestEnd: '3', extractCreativeAndSignature: '4', adResponseValidateStart: '5', renderFriendlyStart: '6', // TODO(dvoytenko): this signal and similar are actually "embed-create", not "render-start". renderCrossDomainStart: '7', renderFriendlyEnd: '8', renderCrossDomainEnd: '9', preAdThrottle: '10', renderSafeFrameStart: '11', throttled3p: '12', adResponseValidateEnd: '13', xDomIframeLoaded: '14', friendlyIframeLoaded: '15', adSlotCollapsed: '16', adSlotUnhidden: '17', layoutAdPromiseDelay: '18', signatureVerifySuccess: '19', networkError: '20', friendlyIframeIniLoad: '21', }; /** * Utility function that ensures any error thrown is handled by optional * onError handler (if none provided or handler throws, error is swallowed and * undefined is returned). * @param {!Function} fn to protect * @param {T=} inThis An optional object to use as the 'this' object * when calling the function. If not provided, undefined is bound as this * when calling function. * @param {function(this:T, !Error, ...*):?=} onError function given error * and arguments provided to function call. * @return {!Function} protected function * @template T * @visibleForTesting */ export function protectFunctionWrapper( fn, inThis = undefined, onError = undefined) { return (...fnArgs) => { try { return fn.apply(inThis, fnArgs); } catch (err) { if (onError) { try { // Ideally we could use [err, ...var_args] but linter disallows // spread so instead using unshift :( fnArgs.unshift(err); return onError.apply(inThis, fnArgs); } catch (captureErr) { // swallow error if error handler throws. } } // In the event of no optional on error function or its execution throws, // return undefined. return undefined; } }; }; export class AmpA4A extends AMP.BaseElement { // TODO: Add more error handling throughout code. // TODO: Handle creatives that do not fill. /** * @param {!Element} element */ constructor(element) { super(element); dev().assert(AMP.AmpAdUIHandler); dev().assert(AMP.AmpAdXOriginIframeHandler); /** @private {?Promise<?CreativeMetaDataDef>} */ this.adPromise_ = null; /** * @private {number} unique ID of the currently executing promise to allow * for cancellation. */ this.promiseId_ = 0; /** {?Object} */ this.config = null; /** @private {?string} */ this.adUrl_ = null; /** @private {?../../../src/friendly-iframe-embed.FriendlyIframeEmbed} */ this.friendlyIframeEmbed_ = null; /** {?AMP.AmpAdUIHandler} */ this.uiHandler = null; /** @private {?AMP.AmpAdXOriginIframeHandler} */ this.xOriginIframeHandler_ = null; /** @private {boolean} whether layoutMeasure has been executed. */ this.layoutMeasureExecuted_ = false; /** @const @private {!../../../src/service/vsync-impl.Vsync} */ this.vsync_ = this.getVsync(); /** @private {boolean} whether creative has been verified as AMP */ this.isVerifiedAmpCreative_ = false; /** @private @const {!../../../src/service/crypto-impl.Crypto} */ this.crypto_ = cryptoFor(this.win); if (!this.win.ampA4aValidationKeys) { // Without the following variable assignment, there's no way to apply a // type annotation to a win-scoped variable, so the type checker doesn't // catch type errors here. This no-op allows us to enforce some type // expectations. The const assignment will hopefully be optimized // away by the compiler. *fingers crossed* /** @type {!AllServicesCryptoKeysDef} */ const forTypeSafety = this.getKeyInfoSets_(); this.win.ampA4aValidationKeys = forTypeSafety; } /** @private {?ArrayBuffer} */ this.creativeBody_ = null; /** * Note(keithwrightbos) - ensure the default here is null so that ios * uses safeframe when response header is not specified. * @private {?XORIGIN_MODE} */ this.experimentalNonAmpCreativeRenderMethod_ = platformFor(this.win).isIos() ? XORIGIN_MODE.SAFEFRAME : null; /** * Gets a notion of current time, in ms. The value is not necessarily * absolute, so should be used only for computing deltas. When available, * the performance system will be used; otherwise Date.now() will be * returned. * * @const {function():number} * @private */ this.getNow_ = (this.win.performance && this.win.performance.now) ? this.win.performance.now.bind(this.win.performance) : Date.now; /** * Protected version of emitLifecycleEvent that ensures error does not * cause promise chain to reject. * @private {function(string, !Object=)} */ this.protectedEmitLifecycleEvent_ = protectFunctionWrapper( this.emitLifecycleEvent, this, (err, varArgs) => { dev().error(TAG, this.element.getAttribute('type'), 'Error on emitLifecycleEvent', err, varArgs) ; }); /** @const {string} */ this.sentinel = generateSentinel(window); /** * Used to indicate whether this slot should be collapsed or not. Marked * true if the ad response has status 204, is null, or has a null * arrayBuffer. * @private {boolean} */ this.isCollapsed_ = false; } /** @override */ getPriority() { // Priority used for scheduling preload and layout callback. Because // AMP creatives will be injected as part of the promise chain created // within onLayoutMeasure, this is only relevant to non-AMP creatives // therefore we want this to match the 3p priority. return 2; } /** @override */ isLayoutSupported(layout) { return isLayoutSizeDefined(layout); } /** @override */ buildCallback() { const adType = this.element.getAttribute('type'); this.config = adConfig[adType] || {}; this.uiHandler = new AMP.AmpAdUIHandler(this); this.uiHandler.init(); } /** @override */ renderOutsideViewport() { // Ensure non-verified AMP creatives are throttled. if (!this.isVerifiedAmpCreative_ && is3pThrottled(this.win)) { this.protectedEmitLifecycleEvent_('throttled3p'); return false; } // Otherwise the ad is good to go. const elementCheck = getAmpAdRenderOutsideViewport(this.element); return elementCheck !== null ? elementCheck : super.renderOutsideViewport(); } /** * To be overridden by network specific implementation indicating if element * (and environment generally) are valid for sending XHR queries. * @return {boolean} whether element is valid and ad request should be * sent. If false, no ad request is sent and slot will be collapsed if * possible. */ isValidElement() { return true; } /** * Returns true if this element was loaded from an amp-ad element. For use by * network-specific implementations that don't want to allow themselves to be * embedded directly into a page. * @return {boolean} */ isAmpAdElement() { return this.element.tagName == 'AMP-AD' || this.element.tagName == 'AMP-EMBED'; } /** * Prefetches and preconnects URLs related to the ad using adPreconnect * registration which assumes ad request domain used for 3p is applicable. * @param {boolean=} unusedOnLayout * @override */ preconnectCallback(unusedOnLayout) { this.preconnect.url(SAFEFRAME_IMPL_PATH); this.preconnect.url(getDefaultBootstrapBaseUrl(this.win, 'nameframe')); if (!this.config) { return; } const preconnect = this.config.preconnect; // NOTE(keithwrightbos): using onLayout to indicate if preconnect should be // given preferential treatment. Currently this would be false when // relevant (i.e. want to preconnect on or before onLayoutMeasure) which // causes preconnect to delay for 1 sec (see custom-element#preconnect) // therefore hard coding to true. // NOTE(keithwrightbos): Does not take isValidElement into account so could // preconnect unnecessarily, however it is assumed that isValidElement // matches amp-ad loader predicate such that A4A impl does not load. if (typeof preconnect == 'string') { this.preconnect.url(preconnect, true); } else if (preconnect) { preconnect.forEach(p => { this.preconnect.url(p, true); }); } } /** @override */ onLayoutMeasure() { if (this.xOriginIframeHandler_) { this.xOriginIframeHandler_.onLayoutMeasure(); } if (this.layoutMeasureExecuted_ || !this.crypto_.isCryptoAvailable()) { // onLayoutMeasure gets called multiple times. return; } const slotRect = this.getIntersectionElementLayoutBox(); if (slotRect.height == 0 || slotRect.width == 0) { dev().fine( TAG, 'onLayoutMeasure canceled due height/width 0', this.element); return; } user().assert(isAdPositionAllowed(this.element, this.win), '<%s> is not allowed to be placed in elements with ' + 'position:fixed: %s', this.element.tagName, this.element); this.layoutMeasureExecuted_ = true; // OnLayoutMeasure can be called when page is in prerender so delay until // visible. Assume that it is ok to call isValidElement as it should // only being looking at window, immutable properties (i.e. location) and // its element ancestry. if (!this.isValidElement()) { // TODO(kjwright): collapse? user().warn(TAG, this.element.getAttribute('type'), 'Amp ad element ignored as invalid', this.element); return; } // Increment unique promise ID so that if its value changes within the // promise chain due to cancel from unlayout, the promise will be rejected. this.promiseId_++; const promiseId = this.promiseId_; // Shorthand for: reject promise if current promise chain is out of date. const checkStillCurrent = promiseId => { if (promiseId != this.promiseId_) { throw cancellation(); } }; // If in localDev `type=fake` Ad specifies `force3p`, it will be forced // to go via 3p. if (getMode().localDev && this.element.getAttribute('type') == 'fake' && this.element.getAttribute('force3p') == 'true') { this.adUrl_ = this.getAdUrl(); this.adPromise_ = Promise.resolve(); return; } // Return value from this chain: True iff rendering was "successful" // (i.e., shouldn't try to render later via iframe); false iff should // try to render later in iframe. // Cases to handle in this chain: // - Everything ok => Render; return true // - Empty network response returned => Don't render; return true // - Can't parse creative out of response => Don't render; return false // - Can parse, but creative is empty => Don't render; return true // - Validation fails => return false // - Rendering fails => return false // - Chain cancelled => don't return; drop error // - Uncaught error otherwise => don't return; percolate error up this.adPromise_ = viewerForDoc(this.getAmpDoc()).whenFirstVisible() // This block returns the ad URL, if one is available. /** @return {!Promise<?string>} */ .then(() => { checkStillCurrent(promiseId); return /** @type {!Promise<?string>} */ (this.getAdUrl()); }) // This block returns the (possibly empty) response to the XHR request. /** @return {!Promise<?Response>} */ .then(adUrl => { checkStillCurrent(promiseId); this.adUrl_ = adUrl; this.protectedEmitLifecycleEvent_('urlBuilt'); return adUrl && this.sendXhrRequest_(adUrl); }) // The following block returns either the response (as a {bytes, headers} // object), or null if no response is available / response is empty. /** @return {?Promise<?{bytes: !ArrayBuffer, headers: !Headers}>} */ .then(fetchResponse => { checkStillCurrent(promiseId); this.protectedEmitLifecycleEvent_('adRequestEnd'); // If the response is null, we want to return null so that // unlayoutCallback will attempt to render via x-domain iframe, // assuming ad url or creative exist. if (!fetchResponse) { return null; } // If the response has response code 204, or arrayBuffer is null, // collapse it. if (!fetchResponse.arrayBuffer || fetchResponse.status == 204) { this.forceCollapse(); return Promise.reject(NO_CONTENT_RESPONSE); } // TODO(tdrl): Temporary, while we're verifying whether SafeFrame is // an acceptable solution to the 'Safari on iOS doesn't fetch // iframe src from cache' issue. See // https://github.com/ampproject/amphtml/issues/5614 const method = fetchResponse.headers.get(RENDERING_TYPE_HEADER) || this.experimentalNonAmpCreativeRenderMethod_; this.experimentalNonAmpCreativeRenderMethod_ = method; if (method && !isEnumValue(XORIGIN_MODE, method)) { dev().error('AMP-A4A', `cross-origin render mode header ${method}`); } // Note: Resolving a .then inside a .then because we need to capture // two fields of fetchResponse, one of which is, itself, a promise, // and one of which isn't. If we just return // fetchResponse.arrayBuffer(), the next step in the chain will // resolve it to a concrete value, but we'll lose track of // fetchResponse.headers. return fetchResponse.arrayBuffer().then(bytes => { if (bytes.byteLength == 0) { // The server returned no content. Instead of displaying a blank // rectangle, we collapse the slot instead. this.forceCollapse(); return Promise.reject(NO_CONTENT_RESPONSE); } return { bytes, headers: fetchResponse.headers, }; }); }) // This block returns the ad creative and signature, if available; null // otherwise. /** * @return {!Promise<?{creative: !ArrayBuffer, signature: !ArrayBuffer}>} */ .then(responseParts => { checkStillCurrent(promiseId); if (responseParts) { this.protectedEmitLifecycleEvent_('extractCreativeAndSignature'); } return responseParts && this.extractCreativeAndSignature( responseParts.bytes, responseParts.headers); }) // This block returns the ad creative if it exists and validates as AMP; // null otherwise. /** @return {!Promise<?ArrayBuffer>} */ .then(creativeParts => { checkStillCurrent(promiseId); // Keep a handle to the creative body so that we can render into // SafeFrame or NameFrame later, if necessary. TODO(tdrl): Temporary, // while we // assess whether this is the right solution to the Safari+iOS iframe // src cache issue. If we decide to keep a SafeFrame-like solution, // we should restructure the promise chain to pass this info along // more cleanly, without use of an object variable outside the chain. if (!creativeParts) { return Promise.resolve(); } if (this.experimentalNonAmpCreativeRenderMethod_ != XORIGIN_MODE.CLIENT_CACHE && creativeParts.creative) { this.creativeBody_ = creativeParts.creative; } if (creativeParts.size && creativeParts.size.length == 2) { this.handleResize(creativeParts.size[0], creativeParts.size[1]); } if (!creativeParts.signature) { return Promise.resolve(); } this.protectedEmitLifecycleEvent_('adResponseValidateStart'); return this.verifyCreativeSignature_( creativeParts.creative, creativeParts.signature) .then(creative => { if (creative) { return creative; } user().error(TAG, this.element.getAttribute('type'), 'Unable to validate AMP creative against key providers'); // Attempt to re-fetch the keys in case our locally cached // batch has expired. this.win.ampA4aValidationKeys = this.getKeyInfoSets_(); return this.verifyCreativeSignature_( creativeParts.creative, creativeParts.signature); }); }) .then(creative => { checkStillCurrent(promiseId); // Need to know if creative was verified as part of render outside // viewport but cannot wait on promise. Sadly, need a state a // variable. this.isVerifiedAmpCreative_ = !!creative; // TODO(levitzky) If creative comes back null, we should consider re- // fetching the signing server public keys and try the verification // step again. return creative && utf8Decode(creative); }) // This block returns CreativeMetaDataDef iff the creative was verified // as AMP and could be properly parsed for friendly iframe render. /** @return {?CreativeMetaDataDef} */ .then(creativeDecoded => { checkStillCurrent(promiseId); // Note: It's critical that #getAmpAdMetadata_ be called // on precisely the same creative that was validated // via #validateAdResponse_. See GitHub issue // https://github.com/ampproject/amphtml/issues/4187 let creativeMetaDataDef; if (!creativeDecoded || !(creativeMetaDataDef = this.getAmpAdMetadata_(creativeDecoded))) { return null; } // Update priority. this.updatePriority(0); // Load any extensions; do not wait on their promises as this // is just to prefetch. const extensions = extensionsFor(this.win); creativeMetaDataDef.customElementExtensions.forEach( extensionId => extensions.loadExtension(extensionId)); return creativeMetaDataDef; }) .catch(error => { if (error == NO_CONTENT_RESPONSE) { return { minifiedCreative: '', customElementExtensions: [], customStylesheets: [], }; } // If error in chain occurs, report it and return null so that // layoutCallback can render via cross domain iframe assuming ad // url or creative exist. this.promiseErrorHandler_(error); return null; }); } /** * Attempts to validate the creative signature against every key currently in * our possession. This should never be called before at least one key fetch * attempt is made. * * @param {!ArrayBuffer} creative * @param {!Uint8Array} signature * @return {!Promise<!ArrayBuffer>} The creative. */ verifyCreativeSignature_(creative, signature) { if (getMode().localDev) { // localDev mode allows "FAKESIG" signature for the "fake" network. if (signature == 'FAKESIG' && this.element.getAttribute('type') == 'fake') { return Promise.resolve(creative); } } // For each signing service, we have exactly one Promise, // keyInfoSetPromise, that holds an Array of Promises of signing keys. // So long as any one of these signing services can verify the // signature, then the creative is valid AMP. /** @type {!AllServicesCryptoKeysDef} */ const keyInfoSetPromises = this.win.ampA4aValidationKeys; // Track if verification found, as it will ensure that promises yet to // resolve will "cancel" as soon as possible saving unnecessary resource // allocation. let verified = false; return some(keyInfoSetPromises.map(keyInfoSetPromise => { // Resolve Promise into an object containing a 'keys' field, which // is an Array of Promises of signing keys. *whew* return keyInfoSetPromise.then(keyInfoSet => { // As long as any one individual key of a particular signing // service, keyInfoPromise, can verify the signature, then the // creative is valid AMP. if (verified) { return Promise.reject('noop'); } return some(keyInfoSet.keys.map(keyInfoPromise => { // Resolve Promise into signing key. return keyInfoPromise.then(keyInfo => { if (verified) { return Promise.reject('noop'); } if (!keyInfo) { return Promise.reject('Promise resolved to null key.'); } const signatureVerifyStartTime = this.getNow_(); // If the key exists, try verifying with it. return this.crypto_.verifySignature( new Uint8Array(creative), signature, keyInfo) .then(isValid => { if (isValid) { verified = true; this.protectedEmitLifecycleEvent_( 'signatureVerifySuccess', { 'met.delta.AD_SLOT_ID': Math.round( this.getNow_() - signatureVerifyStartTime), 'signingServiceName.AD_SLOT_ID': keyInfo.serviceName, }); return creative; } // Only report if signature is expected to match, given that // multiple key providers could have been specified. // Note: the 'keyInfo &&' check here is not strictly // necessary, because we checked that above. But // Closure type compiler can't seem to recognize that, so // this guarantees it to the compiler. if (keyInfo && this.crypto_.verifyHashVersion(signature, keyInfo)) { user().error(TAG, this.element.getAttribute('type'), 'Key failed to validate creative\'s signature', keyInfo.serviceName, keyInfo.cryptoKey); } // Reject to ensure the some operation waits for other // possible providers to properly verify and resolve. return Promise.reject( `${keyInfo.serviceName} key failed to verify`); }, err => { dev().error( TAG, this.element.getAttribute('type'), keyInfo.serviceName, err, this.element); }); }); })) // some() returns an array of which we only need a single value. .then(returnedArray => returnedArray[0], () => { // Rejection occurs if all keys for this provider fail to validate. return Promise.reject( `All keys for ${keyInfoSet.serviceName} failed to verify`); }); }); })) .then(returnedArray => { this.protectedEmitLifecycleEvent_('adResponseValidateEnd'); return returnedArray[0]; }, () => { // rejection occurs if all providers fail to verify. this.protectedEmitLifecycleEvent_('adResponseValidateEnd'); return Promise.reject('No validation service could verify this key'); }); } /** * Handles uncaught errors within promise flow. * @param {*} error * @private */ promiseErrorHandler_(error) { if (isCancellation(error)) { // Rethrow if cancellation. throw error; } if (!error || !error.message) { error = new Error('unknown error ' + error); } // Add `type` to the message. Ensure to preserve the original stack. const type = this.element.getAttribute('type') || 'notype'; error.message = `${TAG}: ${type}: ${error.message}`; // Additional arguments. const adQueryIdx = this.adUrl_ ? this.adUrl_.indexOf('?') : -1; error.args = { 'au': adQueryIdx < 0 ? '' : this.adUrl_.substring(adQueryIdx + 1, adQueryIdx + 251), }; if (getMode().development || getMode().localDev || getMode().log) { user().error(TAG, error); } else { user().warn(TAG, error); // Report with 1% sampling as an expected dev error. if (Math.random() < 0.01) { dev().expectedError(TAG, error); } } } /** @override */ layoutCallback() { // Promise may be null if element was determined to be invalid for A4A. if (!this.adPromise_) { return Promise.resolve(); } // There's no real throttling with A4A, but this is the signal that is // most comparable with the layout callback for 3p ads. this.protectedEmitLifecycleEvent_('preAdThrottle'); const layoutCallbackStart = this.getNow_(); // Promise chain will have determined if creative is valid AMP. return this.adPromise_.then(creativeMetaData => { const delta = this.getNow_() - layoutCallbackStart; this.protectedEmitLifecycleEvent_('layoutAdPromiseDelay', { layoutAdPromiseDelay: Math.round(delta), isAmpCreative: !!creativeMetaData, }); if (this.isCollapsed_) { return Promise.resolve(); } const protectedOnCreativeRender = protectFunctionWrapper(this.onCreativeRender, this, err => { dev().error(TAG, this.element.getAttribute('type'), 'Error executing onCreativeRender', err); }); if (!creativeMetaData) { // Non-AMP creative case, will verify ad url existence. return this.renderNonAmpCreative_() .then(() => protectedOnCreativeRender(false)); } // Must be an AMP creative. return this.renderAmpCreative_(creativeMetaData) .then(() => protectedOnCreativeRender(true)) .catch(err => { // Failed to render via AMP creative path so fallback to non-AMP // rendering within cross domain iframe. user().error(TAG, this.element.getAttribute('type'), 'Error injecting creative in friendly frame', err); this.promiseErrorHandler_(err); return this.renderNonAmpCreative_() .then(() => protectedOnCreativeRender(false)); }); }).catch(error => { this.promiseErrorHandler_(error); throw cancellation(); }); } /** @override */ unlayoutCallback() { this.protectedEmitLifecycleEvent_('adSlotCleared'); this.uiHandler.setDisplayState(AdDisplayState.NOT_LAID_OUT); this.isCollapsed_ = false; // Allow embed to release its resources. if (this.friendlyIframeEmbed_) { this.friendlyIframeEmbed_.destroy(); this.friendlyIframeEmbed_ = null; } // Remove creative and reset to allow for creation of new ad. if (!this.layoutMeasureExecuted_) { return true; } removeChildren(this.element); this.adPromise_ = null; this.adUrl_ = null; this.creativeBody_ = null; this.isVerifiedAmpCreative_ = false; this.experimentalNonAmpCreativeRenderMethod_ = platformFor(this.win).isIos() ? XORIGIN_MODE.SAFEFRAME : null; if (this.xOriginIframeHandler_) { this.xOriginIframeHandler_.freeXOriginIframe(); this.xOriginIframeHandler_ = null; } this.layoutMeasureExecuted_ = false; // Increment promiseId to cause any pending promise to cancel. this.promiseId_++; return true; } /** @override */ viewportCallback(inViewport) { if (this.friendlyIframeEmbed_) { setFriendlyIframeEmbedVisible(this.friendlyIframeEmbed_, inViewport); } if (this.xOriginIframeHandler_) { this.xOriginIframeHandler_.viewportCallback(inViewport); } } /** @override */ createPlaceholderCallback() { return this.uiHandler.createPlaceholderCallback(); } /** * Gets the Ad URL to send an XHR Request to. To be implemented * by network. * @return {!Promise<string>|string} */ getAdUrl() { throw new Error('getAdUrl not implemented!'); } /** * Extracts creative and verification signature (if present) from * XHR response body and header. To be implemented by network. * * In the returned value, the `creative` field should be an `ArrayBuffer` * containing the utf-8 encoded bytes of the creative itself, while the * `signature` field should be a `Uint8Array` containing the raw signature * bytes. The `signature` field may be null if no signature was available * for this creative / the creative is not valid AMP. * * @param {!ArrayBuffer} unusedResponseArrayBuffer content as array buffer * @param {!../../../src/service/xhr-impl.FetchResponseHeaders} unusedResponseHeaders * XHR service FetchResponseHeaders object containing the response * headers. * @return {!Promise<!AdResponseDef>} */ extractCreativeAndSignature(unusedResponseArrayBuffer, unusedResponseHeaders) { throw new Error('extractCreativeAndSignature not implemented!'); } /** * This function is called if the ad response contains a creative size header * indicating the size of the creative. It provides an opportunity to resize * the creative, if desired, before it is rendered. * * To be implemented by network. * * @param {number} width * @param {number} height * */ handleResize(width, height) { user().info('A4A', `Received creative with size ${width}x${height}.`); } /** * Forces the UI Handler to collapse this slot. * @visibleForTesting */ forceCollapse() { dev().assert(this.uiHandler); this.uiHandler.setDisplayState(AdDisplayState.LOADING); this.uiHandler.setDisplayState(AdDisplayState.LOADED_NO_CONTENT); this.isCollapsed_ = true; } /** * Callback executed when creative has successfully rendered within the * publisher page. To be overridden by network implementations as needed. * * @param {boolean} isVerifiedAmpCreative whether or not the creative was * verified as AMP and therefore given preferential treatment. */ onCreativeRender(isVerifiedAmpCreative) { if (isVerifiedAmpCreative) { this.protectedEmitLifecycleEvent_('renderFriendlyEnd'); } } /** * @param {!Element} iframe that was just created. To be overridden for * testing. * @visibleForTesting */ onCrossDomainIframeCreated(iframe) { dev().info(TAG, this.element.getAttribute('type'), `onCrossDomainIframeCreated ${iframe}`); } /** * Send ad request, extract the creative and signature from the response. * @param {string} adUrl Request URL to send XHR to. * @return {!Promise<?../../../src/service/xhr-impl.FetchResponse>} * @private */ sendXhrRequest_(adUrl) { this.protectedEmitLifecycleEvent_('adRequestStart'); const xhrInit = { mode: 'cors', method: 'GET', credentials: 'include', }; return xhrFor(this.win) .fetch(adUrl, xhrInit) .catch(unusedReason => { // If an error occurs, let the ad be rendered via iframe after delay. // TODO(taymonbeal): Figure out a more sophisticated test for deciding // whether to retry with an iframe after an ad request failure or just // give up and render the fallback content (or collapse the ad slot). this.protectedEmitLifecycleEvent_('networkError'); return null; }); } /** * To be overridden by network specific implementation indicating which * signing service(s) is to be used. * @return {!Array<string>} A list of signing services. */ getSigningServiceNames() { return getMode().localDev ? ['google', 'google-dev'] : ['google']; } /** * Retrieves all public keys, as specified in _a4a-config.js. * None of the (inner or outer) promises returned by this function can reject. * * @return {!AllServicesCryptoKeysDef} * @private */ getKeyInfoSets_() { if (!this.crypto_.isCryptoAvailable()) { return []; } return this.getSigningServiceNames().map(serviceName => { dev().assert(getMode().localDev || !endsWith(serviceName, '-dev')); const url = signingServerURLs[serviceName]; const currServiceName = serviceName; if (url) { // Set disableAmpSourceOrigin so that __amp_source_origin is not // included in XHR CORS request allowing for keyset to be cached // across pages. return xhrFor(this.win).fetchJson(url, { mode: 'cors', method: 'GET', ampCors: false, credentials: 'omit', }).then(jwkSetObj => { const result = {serviceName: currServiceName}; if (isObject(jwkSetObj) && Array.isArray(jwkSetObj.keys) && jwkSetObj.keys.every(isObject)) { result.keys = jwkSetObj.keys; } else { user().error(TAG, this.element.getAttribute('type'), `Invalid response from signing server ${currServiceName}`, this.element); result.keys = []; } return result; }).then(jwkSet => { return { serviceName: jwkSet.serviceName, keys: jwkSet.keys.map(jwk => this.crypto_.importPublicKey(jwkSet.serviceName, jwk) .catch(err => { user().error(TAG, this.element.getAttribute('type'), `error importing keys for service: ${jwkSet.serviceName}`, err, this.element); return null; })), }; }).catch(err => { user().error( TAG, this.element.getAttribute('type'), err, this.element); // TODO(a4a-team): This is a failure in the initial attempt to get // the keys, probably b/c of a network condition. We should // re-trigger key fetching later. return {serviceName: currServiceName, keys: []}; }); } else { // The given serviceName does not have a corresponding URL in // _a4a-config.js. const reason = `Signing service '${serviceName}' does not exist.`; user().error( TAG, this.element.getAttribute('type'), reason, this.element); return Promise.resolve({serviceName: currServiceName, keys: []}); } }); } /** * Render non-AMP creative within cross domain iframe. * @return {Promise<boolean>} Whether the creative was successfully rendered. * @private */ renderNonAmpCreative_() { this.promiseErrorHandler_(new Error('fallback to 3p')); this.protectedEmitLifecycleEvent_('preAdThrottle'); incrementLoadingAds(this.win); // Haven't rendered yet, so try rendering via one of our // cross-domain iframe solutions. const method = this.experimentalNonAmpCreativeRenderMethod_; if ((method == XORIGIN_MODE.SAFEFRAME || method == XORIGIN_MODE.NAMEFRAME) && this.creativeBody_) { const renderPromise = this.renderViaNameAttrOfXOriginIframe_( this.creativeBody_); this.creativeBody_ = null; // Free resources. return renderPromise; } else if (this.adUrl_) { return this.renderViaCachedContentIframe_(this.adUrl_); } else { // Ad URL may not exist if buildAdUrl throws error or returns empty. // If error occurred, it would have already been reported but let's // report to user in case of empty. user().warn(TAG, this.element.getAttribute('type'), 'No creative or URL available -- A4A can\'t render any ad'); return Promise.resolve(false); } } /** * Render a validated AMP creative directly in the parent page. * @param {!CreativeMetaDataDef} creativeMetaData Metadata required to render * AMP creative. * @return {!Promise} Whether the creative was successfully rendered. * @private */ renderAmpCreative_(creativeMetaData) { dev().assert(creativeMetaData.minifiedCreative, 'missing minified creative'); dev().assert(!!this.element.ownerDocument, 'missing owner document?!'); this.protectedEmitLifecycleEvent_('renderFriendlyStart'); // Create and setup friendly iframe. const iframe = /** @type {!HTMLIFrameElement} */( createElementWithAttributes( /** @type {!Document} */(this.element.ownerDocument), 'iframe', { frameborder: '0', allowfullscreen: '', allowtransparency: '', scrolling: 'no', })); this.applyFillContent(iframe); const fontsArray = []; if (creativeMetaData.customStylesheets) { creativeMetaData.customStylesheets.forEach(s => { const href = s['href']; if (href) { fontsArray.push(href); } }); } return installFriendlyIframeEmbed( iframe, this.element, { host: this.element, url: this.adUrl_, html: creativeMetaData.minifiedCreative, extensionIds: creativeMetaData.customElementExtensions || [], fonts: fontsArray, }, embedWin => { installUrlReplacementsForEmbed(this.getAmpDoc(), embedWin, new A4AVariableSource(this.getAmpDoc(), embedWin)); }).then(friendlyIframeEmbed => { this.friendlyIframeEmbed_ = friendlyIframeEmbed; setFriendlyIframeEmbedVisible( friendlyIframeEmbed, this.isInViewport()); // Ensure visibility hidden has been removed (set by boilerplate). const frameDoc = friendlyIframeEmbed.iframe.contentDocument || friendlyIframeEmbed.win.document; setStyle(frameDoc.body, 'visibility', 'visible'); // Capture phase click handlers on the ad. installAnchorClickInterceptor( this.getAmpDoc(), friendlyIframeEmbed.win); // Bubble phase click handlers on the ad. this.registerAlpHandler_(friendlyIframeEmbed.win); // Capture timing info for friendly iframe load completion. getTimingDataAsync(friendlyIframeEmbed.win, 'navigationStart', 'loadEventEnd').then(delta => { this.protectedEmitLifecycleEvent_('friendlyIframeLoaded', { 'navStartToLoadEndDelta.AD_SLOT_ID': Math.round(delta), }); }).catch(err => { dev().error(TAG, this.element.getAttribute('type'), 'getTimingDataAsync for renderFriendlyEnd failed: ', err); }); // It's enough to wait for "ini-load" signal because in a FIE case // we know that the embed no longer consumes significant resources // after the initial load. return friendlyIframeEmbed.whenIniLoaded(); }).then(() => { // Capture ini-load ping. this.protectedEmitLifecycleEvent_('friendlyIframeIniLoad'); }); } /** * Shared functionality for cross-domain iframe-based rendering methods. * @param {!Element} iframe Iframe to render. Should be fully configured * (all attributes set), but not yet attached to DOM. * @return {!Promise} awaiting load event for ad frame * @private */ iframeRenderHelper_(iframe) { // TODO(keithwrightbos): noContentCallback? this.xOriginIframeHandler_ = new AMP.AmpAdXOriginIframeHandler(this); return this.xOriginIframeHandler_.init(iframe, /* opt_isA4A */ true); } /** * Creates iframe whose src matches that of the ad URL. The response should * have been cached causing the browser to render without callout. However, * it is possible for cache miss to occur which can be detected server-side * by missing ORIGIN header. * * Note: As of 2016-10-18, the fill-from-cache assumption appears to fail on * Safari-on-iOS, which issues a fresh network request, even though the * content is already in cache. * * @param {string} adUrl Ad request URL, as sent to #sendXhrRequest_ (i.e., * before any modifications that XHR module does to it.) * @return {!Promise} awaiting ad completed insertion. * @private */ renderViaCachedContentIframe_(adUrl) { this.protectedEmitLifecycleEvent_('renderCrossDomainStart'); /** @const {!Element} */ const iframe = createElementWithAttributes( /** @type {!Document} */(this.element.ownerDocument), 'iframe', Object.assign({ 'height': this.element.getAttribute('height'), 'width': this.element.getAttribute('width'), // XHR request modifies URL by adding origin as parameter. Need to // append ad URL, otherwise cache will miss. // TODO: remove call to getCorsUrl and instead have fetch API return // modified url. 'src': xhrFor(this.win).getCorsUrl(this.win, adUrl), }, SHARED_IFRAME_PROPERTIES)); // Can't get the attributes until we have the iframe, then set it. const attributes = getContextMetadata( this.win, this.element, this.sentinel); iframe.setAttribute('name', JSON.stringify(attributes)); iframe.setAttribute('data-amp-3p-sentinel', this.sentinel); return this.iframeRenderHelper_(iframe); } /** * Render the creative via some "cross domain iframe that accepts the creative * in the name attribute". This could be SafeFrame or the AMP-native * NameFrame. * * @param {!ArrayBuffer} creativeBody * @return {!Promise} awaiting load event for ad frame * @private */ renderViaNameAttrOfXOriginIframe_(creativeBody) { const method = this.experimentalNonAmpCreativeRenderMethod_; dev().assert(method == XORIGIN_MODE.SAFEFRAME || method == XORIGIN_MODE.NAMEFRAME, 'Unrecognized A4A cross-domain rendering mode: %s', method); this.protectedEmitLifecycleEvent_('renderSafeFrameStart'); return utf8Decode(creativeBody).then(creative => { let srcPath; let nameData; switch (method) { case XORIGIN_MODE.SAFEFRAME: srcPath = SAFEFRAME_IMPL_PATH + '?n=0'; nameData = `${SAFEFRAME_VERSION};${creative.length};${creative}`; break; case XORIGIN_MODE.NAMEFRAME: srcPath = getDefaultBootstrapBaseUrl(this.win, 'nameframe'); nameData = ''; // Name will be set for real below in nameframe case. break; default: // Shouldn't be able to get here, but... Because of the assert, above, // we can only get here in non-dev mode, so give user feedback. user().error('A4A', 'A4A received unrecognized cross-domain name' + ' attribute iframe rendering mode request: %s. Unable to' + ' render a creative for' + ' slot %s.', method, this.element.getAttribute('id')); return Promise.reject('Unrecognized rendering mode request'); } /** @const {!Element} */ const iframe = createElementWithAttributes( /** @type {!Document} */(this.element.ownerDocument), 'iframe', Object.assign({ 'height': this.element.getAttribute('height'), 'width': this.element.getAttribute('width'), 'src': srcPath, 'name': nameData, }, SHARED_IFRAME_PROPERTIES)); if (method == XORIGIN_MODE.NAMEFRAME) { // TODO(bradfrizzell): change name of function and var const attributes = getContextMetadata( this.win, this.element, this.sentinel); attributes['creative'] = creative; const name = JSON.stringify(attributes); // Need to reassign the name once we've generated the context // attributes off of the iframe. Need the iframe to generate. iframe.setAttribute('name', name); iframe.setAttribute('data-amp-3p-sentinel', this.sentinel); } return this.iframeRenderHelper_(iframe); }); } /** * * Throws {@code SyntaxError} if the metadata block delimiters are missing * or corrupted or if the metadata content doesn't parse as JSON. * @param {string} creative from which CSS is extracted * @return {?CreativeMetaDataDef} Object result of parsing JSON data blob inside * the metadata markers on the ad text, or null if no metadata markers are * found. * @private * TODO(keithwrightbos@): report error cases */ getAmpAdMetadata_(creative) { let metadataString = METADATA_STRING; let metadataStart = creative.lastIndexOf(METADATA_STRING); if (metadataStart < 0) { metadataString = METADATA_STRING_NO_QUOTES; metadataStart = creative.lastIndexOf(METADATA_STRING_NO_QUOTES); } if (metadataStart < 0) { // Couldn't find a metadata blob. dev().warn(TAG, this.element.getAttribute('type'), 'Could not locate start index for amp meta data in: %s', creative); return null; } const metadataEnd = creative.lastIndexOf('</script>'); if (metadataEnd < 0) { // Couldn't find a metadata blob. dev().warn(TAG, this.element.getAttribute('type'), 'Could not locate closing script tag for amp meta data in: %s', creative); return null; } try { const metaDataObj = JSON.parse( creative.slice(metadataStart + metadataString.length, metadataEnd)); const ampRuntimeUtf16CharOffsets = metaDataObj['ampRuntimeUtf16CharOffsets']; if (!isArray(ampRuntimeUtf16CharOffsets) || ampRuntimeUtf16CharOffsets.length != 2 || typeof ampRuntimeUtf16CharOffsets[0] !== 'number' || typeof ampRuntimeUtf16CharOffsets[1] !== 'number') { throw new Error('Invalid runtime offsets'); } const metaData = {}; if (metaDataObj['customElementExtensions']) { metaData.customElementExtensions = metaDataObj['customElementExtensions']; if (!isArray(metaData.customElementExtensions)) { throw new Error( 'Invalid extensions', metaData.customElementExtensions); } } else { metaData.customElementExtensions = []; } if (metaDataObj['customStylesheets']) { // Expect array of objects with at least one key being 'href' whose // value is URL. metaData.customStylesheets = metaDataObj['customStylesheets']; const errorMsg = 'Invalid custom stylesheets'; if (!isArray(metaData.customStylesheets)) { throw new Error(errorMsg); } metaData.customStylesheets.forEach(stylesheet => { if (!isObject(stylesheet) || !stylesheet['href'] || typeof stylesheet['href'] !== 'string' || !/^https:\/\//i.test(stylesheet['href'])) { throw new Error(errorMsg); } }); } // TODO(keithwrightbos): OK to assume ampRuntimeUtf16CharOffsets is before // metadata as its in the head? metaData.minifiedCreative = creative.slice(0, ampRuntimeUtf16CharOffsets[0]) + creative.slice(ampRuntimeUtf16CharOffsets[1], metadataStart) + creative.slice(metadataEnd + '</script>'.length); return metaData; } catch (err) { dev().warn( TAG, this.element.getAttribute('type'), 'Invalid amp metadata: %s', creative.slice(metadataStart + METADATA_STRING.length, metadataEnd)); return null; } } /** * Registers a click handler for "A2A" (AMP-to-AMP navigation where the AMP * viewer navigates to an AMP destination on our behalf. * @param {!Window} iframeWin */ registerAlpHandler_(iframeWin) { if (!isExperimentOn(this.win, 'alp-for-a4a')) { return; } iframeWin.document.documentElement.addEventListener('click', event => { handleClick(event, url => { viewerForDoc(this.getAmpDoc()).navigateTo(url, 'a4a'); }); }); } /** * Receive collapse notifications and record lifecycle events for them. * * @param unusedElement {!AmpElement} * @override */ collapsedCallback(unusedElement) { this.protectedEmitLifecycleEvent_('adSlotCollapsed'); } /** * To be overriden by network specific implementation. * This function will be called for each lifecycle event as specified in the * LIFECYCLE_STAGES enum declaration. It may additionally pass extra * variables of the form { name: val }. It is up to the subclass what to * do with those variables. * * @param {string} unusedEventName * @param {!Object<string, string|number>=} opt_extraVariables */ emitLifecycleEvent(unusedEventName, opt_extraVariables) {} }
Adtoma/amphtml
extensions/amp-a4a/0.1/amp-a4a.js
JavaScript
apache-2.0
54,093
/* * Copyright 2012 Amadeus s.a.s. * 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. */ Aria.classDefinition({ $classpath : "test.aria.html.HTMLTestSuite", $extends : "aria.jsunit.TestSuite", $constructor : function () { this.$TestSuite.constructor.call(this); this.addTests("test.aria.html.element.ElementTestSuite"); this.addTests("test.aria.html.controllers.suggestions.ResourcesHandlerTest"); this.addTests("test.aria.html.textinput.TextInputTestSuite"); this.addTests("test.aria.html.checkbox.CheckBoxTest"); this.addTests("test.aria.html.template.basic.HtmlTemplateTestCase"); this.addTests("test.aria.html.template.submodule.SubModuleTestCase"); this.addTests("test.aria.html.radioButton.RadioButtonTest"); this.addTests("test.aria.html.select.SelectTest"); this.addTests("test.aria.html.select.bodycontent.BodyContentTestCase"); this.addTests("test.aria.html.select.onchange.DataModelOnChangeTestCase"); this.addTests("test.aria.html.DisabledTraitTest"); this.addTests("test.aria.html.radioButton.ieBug.RadioButtonTestCase"); this.addTests("test.aria.html.textarea.TextAreaTestSuite"); this.addTests("test.aria.html.template.prematureDisposal.PrematureDisposalTest"); this.addTests("test.aria.html.radioButton.listenerAfterDestruction.ListenerCalledAfterDestructionTest"); this.addTests("test.aria.html.radioButton.disabled.DisabledStateTest"); } });
mlaval/ariatemplates
test/aria/html/HTMLTestSuite.js
JavaScript
apache-2.0
2,019
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview The default renderer for a goog.dom.DimensionPicker. A * dimension picker allows the user to visually select a row and column count. * It looks like a palette but in order to minimize DOM load it is rendered. * using CSS background tiling instead of as a grid of nodes. * * @author [email protected] (Robby Walker) */ goog.provide('goog.ui.DimensionPickerRenderer'); goog.require('goog.a11y.aria.Announcer'); goog.require('goog.a11y.aria.LivePriority'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.i18n.bidi'); goog.require('goog.style'); goog.require('goog.ui.ControlRenderer'); goog.require('goog.userAgent'); goog.forwardDeclare('goog.ui.DimensionPicker'); /** * Default renderer for {@link goog.ui.DimensionPicker}s. Renders the * palette as two divs, one with the un-highlighted background, and one with the * highlighted background. * * @constructor * @extends {goog.ui.ControlRenderer} */ goog.ui.DimensionPickerRenderer = function() { goog.ui.ControlRenderer.call(this); /** @private {goog.a11y.aria.Announcer} */ this.announcer_ = new goog.a11y.aria.Announcer(); }; goog.inherits(goog.ui.DimensionPickerRenderer, goog.ui.ControlRenderer); goog.addSingletonGetter(goog.ui.DimensionPickerRenderer); /** * Default CSS class to be applied to the root element of components rendered * by this renderer. * @type {string} */ goog.ui.DimensionPickerRenderer.CSS_CLASS = goog.getCssName('goog-dimension-picker'); /** * Return the underlying div for the given outer element. * @param {Element} element The root element. * @return {Element} The underlying div. * @private */ goog.ui.DimensionPickerRenderer.prototype.getUnderlyingDiv_ = function( element) { return /** @type {Element} */ (element.firstChild.childNodes[1]); }; /** * Return the highlight div for the given outer element. * @param {Element} element The root element. * @return {Element} The highlight div. * @private */ goog.ui.DimensionPickerRenderer.prototype.getHighlightDiv_ = function(element) { return /** @type {Element} */ (element.firstChild.lastChild); }; /** * Return the status message div for the given outer element. * @param {Element} element The root element. * @return {Element} The status message div. * @private */ goog.ui.DimensionPickerRenderer.prototype.getStatusDiv_ = function(element) { return /** @type {Element} */ (element.lastChild); }; /** * Return the invisible mouse catching div for the given outer element. * @param {Element} element The root element. * @return {Element} The invisible mouse catching div. * @private */ goog.ui.DimensionPickerRenderer.prototype.getMouseCatcher_ = function(element) { return /** @type {Element} */ (element.firstChild.firstChild); }; /** * Overrides {@link goog.ui.ControlRenderer#canDecorate} to allow decorating * empty DIVs only. * @param {Element} element The element to check. * @return {boolean} Whether if the element is an empty div. * @override */ goog.ui.DimensionPickerRenderer.prototype.canDecorate = function(element) { return element.tagName == goog.dom.TagName.DIV && !element.firstChild; }; /** * Overrides {@link goog.ui.ControlRenderer#decorate} to decorate empty DIVs. * @param {goog.ui.Control} control goog.ui.DimensionPicker to decorate. * @param {Element} element The element to decorate. * @return {Element} The decorated element. * @override */ goog.ui.DimensionPickerRenderer.prototype.decorate = function( control, element) { var palette = /** @type {goog.ui.DimensionPicker} */ (control); goog.ui.DimensionPickerRenderer.superClass_.decorate.call( this, palette, element); this.addElementContents_(palette, element); this.updateSize(palette, element); return element; }; /** * Scales various elements in order to update the palette's size. * @param {goog.ui.DimensionPicker} palette The palette object. * @param {Element} element The element to set the style of. */ goog.ui.DimensionPickerRenderer.prototype.updateSize = function( palette, element) { var size = palette.getSize(); element.style.width = size.width + 'em'; var underlyingDiv = this.getUnderlyingDiv_(element); underlyingDiv.style.width = size.width + 'em'; underlyingDiv.style.height = size.height + 'em'; if (palette.isRightToLeft()) { this.adjustParentDirection_(palette, element); } }; /** * Adds the appropriate content elements to the given outer DIV. * @param {goog.ui.DimensionPicker} palette The palette object. * @param {Element} element The element to decorate. * @private */ goog.ui.DimensionPickerRenderer.prototype.addElementContents_ = function( palette, element) { // First we create a single div containing three stacked divs. The bottom div // catches mouse events. We can't use document level mouse move detection as // we could lose events to iframes. This is especially important in Firefox 2 // in which TrogEdit creates iframes. The middle div uses a css tiled // background image to represent deselected tiles. The top div uses a // different css tiled background image to represent selected tiles. var mouseCatcherDiv = palette.getDomHelper().createDom( goog.dom.TagName.DIV, goog.getCssName(this.getCssClass(), 'mousecatcher')); var unhighlightedDiv = palette.getDomHelper().createDom(goog.dom.TagName.DIV, { 'class': goog.getCssName(this.getCssClass(), 'unhighlighted'), 'style': 'width:100%;height:100%' }); var highlightedDiv = palette.getDomHelper().createDom( goog.dom.TagName.DIV, goog.getCssName(this.getCssClass(), 'highlighted')); element.appendChild( palette.getDomHelper().createDom( goog.dom.TagName.DIV, { 'style': 'width:100%;height:100%;touch-action:none;' }, mouseCatcherDiv, unhighlightedDiv, highlightedDiv)); // Lastly we add a div to store the text version of the current state. element.appendChild( palette.getDomHelper().createDom( goog.dom.TagName.DIV, goog.getCssName(this.getCssClass(), 'status'))); }; /** * Creates a div and adds the appropriate contents to it. * @param {goog.ui.Control} control Picker to render. * @return {!Element} Root element for the palette. * @override */ goog.ui.DimensionPickerRenderer.prototype.createDom = function(control) { var palette = /** @type {goog.ui.DimensionPicker} */ (control); var classNames = this.getClassNames(palette); // Hide the element from screen readers so they don't announce "1 of 1" for // the perceived number of items in the palette. var element = palette.getDomHelper().createDom( goog.dom.TagName.DIV, {'class': classNames ? classNames.join(' ') : '', 'aria-hidden': 'true'}); this.addElementContents_(palette, element); this.updateSize(palette, element); return element; }; /** * Initializes the control's DOM when the control enters the document. Called * from {@link goog.ui.Control#enterDocument}. * @param {goog.ui.Control} control Palette whose DOM is to be * initialized as it enters the document. * @override */ goog.ui.DimensionPickerRenderer.prototype.initializeDom = function(control) { var palette = /** @type {goog.ui.DimensionPicker} */ (control); goog.ui.DimensionPickerRenderer.superClass_.initializeDom.call(this, palette); // Make the displayed highlighted size match the dimension picker's value. var highlightedSize = palette.getValue(); this.setHighlightedSize( palette, highlightedSize.width, highlightedSize.height); this.positionMouseCatcher(palette); }; /** * Get the element to listen for mouse move events on. * @param {goog.ui.DimensionPicker} palette The palette to listen on. * @return {Element} The element to listen for mouse move events on. */ goog.ui.DimensionPickerRenderer.prototype.getMouseMoveElement = function( palette) { return /** @type {Element} */ (palette.getElement().firstChild); }; /** * Returns the x offset in to the grid for the given mouse x position. * @param {goog.ui.DimensionPicker} palette The table size palette. * @param {number} x The mouse event x position. * @return {number} The x offset in to the grid. */ goog.ui.DimensionPickerRenderer.prototype.getGridOffsetX = function( palette, x) { // TODO(robbyw): Don't rely on magic 18 - measure each palette's em size. return Math.min(palette.maxColumns, Math.ceil(x / 18)); }; /** * Returns the y offset in to the grid for the given mouse y position. * @param {goog.ui.DimensionPicker} palette The table size palette. * @param {number} y The mouse event y position. * @return {number} The y offset in to the grid. */ goog.ui.DimensionPickerRenderer.prototype.getGridOffsetY = function( palette, y) { return Math.min(palette.maxRows, Math.ceil(y / 18)); }; /** * Sets the highlighted size. Does nothing if the palette hasn't been rendered. * @param {goog.ui.DimensionPicker} palette The table size palette. * @param {number} columns The number of columns to highlight. * @param {number} rows The number of rows to highlight. */ goog.ui.DimensionPickerRenderer.prototype.setHighlightedSize = function( palette, columns, rows) { var element = palette.getElement(); // Can't update anything if DimensionPicker hasn't been rendered. if (!element) { return; } // Style the highlight div. var style = this.getHighlightDiv_(element).style; style.width = columns + 'em'; style.height = rows + 'em'; // Explicitly set style.right so the element grows to the left when increase // in width. if (palette.isRightToLeft()) { style.right = '0'; } /** * @desc The dimension of the columns and rows currently selected in the * dimension picker, as text that can be spoken by a screen reader. */ var MSG_DIMENSION_PICKER_HIGHLIGHTED_DIMENSIONS = goog.getMsg( '{$numCols} by {$numRows}', {'numCols': String(columns), 'numRows': String(rows)}); this.announcer_.say( MSG_DIMENSION_PICKER_HIGHLIGHTED_DIMENSIONS, goog.a11y.aria.LivePriority.ASSERTIVE); // Update the size text. goog.dom.setTextContent( this.getStatusDiv_(element), goog.i18n.bidi.enforceLtrInText(columns + ' x ' + rows)); }; /** * Position the mouse catcher such that it receives mouse events past the * selectedsize up to the maximum size. Takes care to not introduce scrollbars. * Should be called on enter document and when the window changes size. * @param {goog.ui.DimensionPicker} palette The table size palette. */ goog.ui.DimensionPickerRenderer.prototype.positionMouseCatcher = function( palette) { var mouseCatcher = this.getMouseCatcher_(palette.getElement()); var doc = goog.dom.getOwnerDocument(mouseCatcher); var body = doc.body; var position = goog.style.getRelativePosition(mouseCatcher, body); // Hide the mouse catcher so it doesn't affect the body's scroll size. mouseCatcher.style.display = 'none'; // Compute the maximum size the catcher can be without introducing scrolling. var xAvailableEm = (palette.isRightToLeft() && position.x > 0) ? Math.floor(position.x / 18) : Math.floor((body.scrollWidth - position.x) / 18); // Computing available height is more complicated - we need to check the // window's inner height. var height; if (goog.userAgent.IE) { // Offset 20px to make up for scrollbar size. height = goog.style.getClientViewportElement(body).scrollHeight - 20; } else { var win = goog.dom.getWindow(doc); // Offset 20px to make up for scrollbar size. height = Math.max(win.innerHeight, body.scrollHeight) - 20; } var yAvailableEm = Math.floor((height - position.y) / 18); // Resize and display the mouse catcher. mouseCatcher.style.width = Math.min(palette.maxColumns, xAvailableEm) + 'em'; mouseCatcher.style.height = Math.min(palette.maxRows, yAvailableEm) + 'em'; mouseCatcher.style.display = ''; // Explicitly set style.right so the mouse catcher is positioned on the left // side instead of right. if (palette.isRightToLeft()) { mouseCatcher.style.right = '0'; } }; /** * Returns the CSS class to be applied to the root element of components * rendered using this renderer. * @return {string} Renderer-specific CSS class. * @override */ goog.ui.DimensionPickerRenderer.prototype.getCssClass = function() { return goog.ui.DimensionPickerRenderer.CSS_CLASS; }; /** * This function adjusts the positioning from 'left' and 'top' to 'right' and * 'top' as appropriate for RTL control. This is so when the dimensionpicker * grow in width, the containing element grow to the left instead of right. * This won't be necessary if goog.ui.SubMenu rendering code would position RTL * control with 'right' and 'top'. * @private * * @param {goog.ui.DimensionPicker} palette The palette object. * @param {Element} element The palette's element. */ goog.ui.DimensionPickerRenderer.prototype.adjustParentDirection_ = function( palette, element) { var parent = palette.getParent(); if (parent) { var parentElement = parent.getElement(); // Anchors the containing element to the right so it grows to the left // when it increase in width. var right = goog.style.getStyle(parentElement, 'right'); if (right == '') { var parentPos = goog.style.getPosition(parentElement); var parentSize = goog.style.getSize(parentElement); if (parentSize.width != 0 && parentPos.x != 0) { var visibleRect = goog.style.getBounds(goog.style.getClientViewportElement()); var visibleWidth = visibleRect.width; right = visibleWidth - parentPos.x - parentSize.width; goog.style.setStyle(parentElement, 'right', right + 'px'); } } // When a table is inserted, the containing elemet's position is // recalculated the next time it shows, set left back to '' to prevent // extra white space on the left. var left = goog.style.getStyle(parentElement, 'left'); if (left != '') { goog.style.setStyle(parentElement, 'left', ''); } } else { goog.style.setStyle(element, 'right', '0px'); } };
teppeis/closure-library
closure/goog/ui/dimensionpickerrenderer.js
JavaScript
apache-2.0
14,821
goog.provide('ol.test.format.WFS'); describe('ol.format.WFS', function() { describe('when parsing TOPP states GML from WFS', function() { var features, feature, xml; var config = { 'featureNS': 'http://www.openplans.org/topp', 'featureType': 'states' }; before(function(done) { proj4.defs('urn:x-ogc:def:crs:EPSG:4326', proj4.defs('EPSG:4326')); afterLoadText('spec/ol/format/wfs/topp-states-wfs.xml', function(data) { try { xml = data; features = new ol.format.WFS(config).readFeatures(xml); } catch (e) { done(e); } done(); }); }); it('creates 3 features', function() { expect(features).to.have.length(3); }); it('creates a polygon for Illinois', function() { feature = features[0]; expect(feature.getId()).to.equal('states.1'); expect(feature.get('STATE_NAME')).to.equal('Illinois'); expect(feature.getGeometry()).to.be.an(ol.geom.MultiPolygon); }); it('transforms and creates a polygon for Illinois', function() { features = new ol.format.WFS(config).readFeatures(xml, { featureProjection: 'EPSG:3857' }); feature = features[0]; expect(feature.getId()).to.equal('states.1'); expect(feature.get('STATE_NAME')).to.equal('Illinois'); var geom = feature.getGeometry(); expect(geom).to.be.an(ol.geom.MultiPolygon); var p = ol.proj.transform([-88.071, 37.511], 'EPSG:4326', 'EPSG:3857'); p.push(0); expect(geom.getFirstCoordinate()).to.eql(p); }); }); describe('when parsing mapserver GML2 polygon', function() { var features, feature, xml; var config = { 'featureNS': 'http://mapserver.gis.umn.edu/mapserver', 'featureType': 'polygon', 'gmlFormat': new ol.format.GML2() }; before(function(done) { proj4.defs('urn:x-ogc:def:crs:EPSG:4326', proj4.defs('EPSG:4326')); afterLoadText('spec/ol/format/wfs/polygonv2.xml', function(data) { try { xml = data; features = new ol.format.WFS(config).readFeatures(xml); } catch (e) { done(e); } done(); }); }); it('creates 3 features', function() { expect(features).to.have.length(3); }); it('creates a polygon for My Polygon with hole', function() { feature = features[0]; expect(feature.getId()).to.equal('1'); expect(feature.get('name')).to.equal('My Polygon with hole'); expect(feature.get('boundedBy')).to.eql( [47.003018, -0.768746, 47.925567, 0.532597]); expect(feature.getGeometry()).to.be.an(ol.geom.MultiPolygon); expect(feature.getGeometry().getFlatCoordinates()). to.have.length(60); }); }); describe('when parsing FeatureCollection', function() { var xml; before(function(done) { afterLoadText('spec/ol/format/wfs/EmptyFeatureCollection.xml', function(_xml) { xml = _xml; done(); }); }); it('returns an empty array of features when none exist', function() { var result = new ol.format.WFS().readFeatures(xml); expect(result).to.have.length(0); }); }); describe('when parsing FeatureCollection', function() { var response; before(function(done) { afterLoadText('spec/ol/format/wfs/NumberOfFeatures.xml', function(xml) { try { response = new ol.format.WFS().readFeatureCollectionMetadata(xml); } catch (e) { done(e); } done(); }); }); it('returns the correct number of features', function() { expect(response.numberOfFeatures).to.equal(625); }); }); describe('when parsing FeatureCollection', function() { var response; before(function(done) { proj4.defs('EPSG:28992', '+proj=sterea +lat_0=52.15616055555555 ' + '+lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 ' + '+ellps=bessel +towgs84=565.417,50.3319,465.552,-0.398957,0.343988,' + '-1.8774,4.0725 +units=m +no_defs'); afterLoadText('spec/ol/format/wfs/boundedBy.xml', function(xml) { try { response = new ol.format.WFS().readFeatureCollectionMetadata(xml); } catch (e) { done(e); } done(); }); }); it('returns the correct bounds', function() { expect(response.bounds).to.eql([3197.88, 306457.313, 280339.156, 613850.438]); }); }); describe('when parsing TransactionResponse', function() { var response; before(function(done) { afterLoadText('spec/ol/format/wfs/TransactionResponse.xml', function(xml) { try { response = new ol.format.WFS().readTransactionResponse(xml); } catch (e) { done(e); } done(); }); }); it('returns the correct TransactionResponse object', function() { expect(response.transactionSummary.totalDeleted).to.equal(0); expect(response.transactionSummary.totalInserted).to.equal(0); expect(response.transactionSummary.totalUpdated).to.equal(1); expect(response.insertIds).to.have.length(2); expect(response.insertIds[0]).to.equal('parcelle.40'); }); }); describe('when writing out a GetFeature request', function() { it('creates the expected output', function() { var text = '<wfs:GetFeature service="WFS" version="1.1.0" resultType="hits" ' + ' xmlns:topp="http://www.openplans.org/topp"' + ' xmlns:wfs="http://www.opengis.net/wfs"' + ' xmlns:ogc="http://www.opengis.net/ogc"' + ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' + ' xsi:schemaLocation="http://www.opengis.net/wfs ' + 'http://schemas.opengis.net/wfs/1.1.0/wfs.xsd">' + ' <wfs:Query xmlns:wfs="http://www.opengis.net/wfs" ' + ' typeName="topp:states" srsName="urn:ogc:def:crs:EPSG::4326" ' + ' xmlns:topp="http://www.openplans.org/topp">' + ' <wfs:PropertyName>STATE_NAME</wfs:PropertyName>' + ' <wfs:PropertyName>STATE_FIPS</wfs:PropertyName>' + ' <wfs:PropertyName>STATE_ABBR</wfs:PropertyName>' + ' </wfs:Query>' + '</wfs:GetFeature>'; var serialized = new ol.format.WFS().writeGetFeature({ resultType: 'hits', featureTypes: ['states'], featureNS: 'http://www.openplans.org/topp', featurePrefix: 'topp', srsName: 'urn:ogc:def:crs:EPSG::4326', propertyNames: ['STATE_NAME', 'STATE_FIPS', 'STATE_ABBR'] }); expect(serialized).to.xmleql(ol.xml.parse(text)); }); it('creates paging headers', function() { var text = '<wfs:GetFeature service="WFS" version="1.1.0" startIndex="20" ' + ' count="10" xmlns:topp="http://www.openplans.org/topp"' + ' xmlns:wfs="http://www.opengis.net/wfs"' + ' xmlns:ogc="http://www.opengis.net/ogc"' + ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' + ' xsi:schemaLocation="http://www.opengis.net/wfs ' + 'http://schemas.opengis.net/wfs/1.1.0/wfs.xsd">' + ' <wfs:Query xmlns:wfs="http://www.opengis.net/wfs" ' + ' typeName="topp:states" srsName="urn:ogc:def:crs:EPSG::4326"' + ' xmlns:topp="http://www.openplans.org/topp">' + ' </wfs:Query>' + '</wfs:GetFeature>'; var serialized = new ol.format.WFS().writeGetFeature({ count: 10, startIndex: 20, srsName: 'urn:ogc:def:crs:EPSG::4326', featureNS: 'http://www.openplans.org/topp', featurePrefix: 'topp', featureTypes: ['states'] }); expect(serialized).to.xmleql(ol.xml.parse(text)); }); it('creates a BBOX filter', function() { var text = '<wfs:Query xmlns:wfs="http://www.opengis.net/wfs" ' + ' typeName="topp:states" srsName="urn:ogc:def:crs:EPSG::4326" ' + ' xmlns:topp="http://www.openplans.org/topp">' + ' <ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">' + ' <ogc:BBOX>' + ' <ogc:PropertyName>the_geom</ogc:PropertyName>' + ' <gml:Envelope xmlns:gml="http://www.opengis.net/gml" ' + ' srsName="urn:ogc:def:crs:EPSG::4326">' + ' <gml:lowerCorner>1 2</gml:lowerCorner>' + ' <gml:upperCorner>3 4</gml:upperCorner>' + ' </gml:Envelope>' + ' </ogc:BBOX>' + ' </ogc:Filter>' + '</wfs:Query>'; var serialized = new ol.format.WFS().writeGetFeature({ srsName: 'urn:ogc:def:crs:EPSG::4326', featureNS: 'http://www.openplans.org/topp', featurePrefix: 'topp', featureTypes: ['states'], geometryName: 'the_geom', bbox: [1, 2, 3, 4] }); expect(serialized.firstElementChild).to.xmleql(ol.xml.parse(text)); }); }); describe('when writing out a Transaction request', function() { it('creates a handle', function() { var text = '<wfs:Transaction xmlns:wfs="http://www.opengis.net/wfs" ' + 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' + 'service="WFS" version="1.1.0" handle="handle_t" ' + 'xsi:schemaLocation="http://www.opengis.net/wfs ' + 'http://schemas.opengis.net/wfs/1.1.0/wfs.xsd"/>'; var serialized = new ol.format.WFS().writeTransaction(null, null, null, {handle: 'handle_t'}); expect(serialized).to.xmleql(ol.xml.parse(text)); }); }); describe('when writing out a Transaction request', function() { var text; before(function(done) { afterLoadText('spec/ol/format/wfs/TransactionSrs.xml', function(xml) { text = xml; done(); }); }); it('creates the correct srsName', function() { var format = new ol.format.WFS(); var insertFeature = new ol.Feature({ the_geom: new ol.geom.MultiLineString([[ [-5178372.1885436, 1992365.7775042], [-4434792.7774889, 1601008.1927386], [-4043435.1927233, 2148908.8114105] ]]), TYPE: 'xyz' }); insertFeature.setGeometryName('the_geom'); var inserts = [insertFeature]; var serialized = format.writeTransaction(inserts, null, null, { featureNS: 'http://foo', featureType: 'FAULTS', featurePrefix: 'feature', gmlOptions: {multiCurve: true, srsName: 'EPSG:900913'} }); expect(serialized).to.xmleql(ol.xml.parse(text)); }); }); describe('when writing out a Transaction request', function() { var text; before(function(done) { afterLoadText('spec/ol/format/wfs/TransactionUpdate.xml', function(xml) { text = xml; done(); }); }); it('creates the correct update', function() { var format = new ol.format.WFS(); var updateFeature = new ol.Feature(); updateFeature.setGeometryName('the_geom'); updateFeature.setGeometry(new ol.geom.MultiLineString([[ [-12279454, 6741885], [-12064207, 6732101], [-11941908, 6595126], [-12240318, 6507071], [-12416429, 6604910] ]])); updateFeature.setId('FAULTS.4455'); var serialized = format.writeTransaction(null, [updateFeature], null, { featureNS: 'http://foo', featureType: 'FAULTS', featurePrefix: 'foo', gmlOptions: {srsName: 'EPSG:900913'} }); expect(serialized).to.xmleql(ol.xml.parse(text)); }); }); describe('when writing out a Transaction request', function() { it('does not create an update if no fid', function() { var format = new ol.format.WFS(); var updateFeature = new ol.Feature(); updateFeature.setGeometryName('the_geom'); updateFeature.setGeometry(new ol.geom.MultiLineString([[ [-12279454, 6741885], [-12064207, 6732101], [-11941908, 6595126], [-12240318, 6507071], [-12416429, 6604910] ]])); var error = false; try { format.writeTransaction(null, [updateFeature], null, { featureNS: 'http://foo', featureType: 'FAULTS', featurePrefix: 'foo', gmlOptions: {srsName: 'EPSG:900913'} }); } catch (e) { error = true; } expect(error).to.be(true); }); }); describe('when writing out a Transaction request', function() { var text, filename = 'spec/ol/format/wfs/TransactionUpdateMultiGeoms.xml'; before(function(done) { afterLoadText(filename, function(xml) { text = xml; done(); } ); }); it('handles multiple geometries', function() { var format = new ol.format.WFS(); var updateFeature = new ol.Feature(); updateFeature.setGeometryName('the_geom'); updateFeature.setGeometry(new ol.geom.MultiLineString([[ [-12279454, 6741885], [-12064207, 6732101], [-11941908, 6595126], [-12240318, 6507071], [-12416429, 6604910] ]])); updateFeature.set('geom2', new ol.geom.MultiLineString([[ [-12000000, 6700000], [-12000001, 6700001], [-12000002, 6700002] ]])); var serialized = format.writeTransaction([updateFeature], [], null, { featureNS: 'http://foo', featureType: 'FAULTS', featurePrefix: 'foo', gmlOptions: {srsName: 'EPSG:900913'} }); expect(serialized).to.xmleql(ol.xml.parse(text)); }); }); describe('when writing out a Transaction request', function() { var text; before(function(done) { afterLoadText('spec/ol/format/wfs/TransactionMulti.xml', function(xml) { text = xml; done(); }); }); it('creates the correct transaction body', function() { var format = new ol.format.WFS(); var insertFeature = new ol.Feature({ the_geom: new ol.geom.MultiPoint([[1, 2]]), foo: 'bar', nul: null }); insertFeature.setGeometryName('the_geom'); var inserts = [insertFeature]; var updateFeature = new ol.Feature({ the_geom: new ol.geom.MultiPoint([[1, 2]]), foo: 'bar', // null value gets Property element with no Value nul: null, // undefined value means don't create a Property element unwritten: undefined }); updateFeature.setId('fid.42'); var updates = [updateFeature]; var deleteFeature = new ol.Feature(); deleteFeature.setId('fid.37'); var deletes = [deleteFeature]; var serialized = format.writeTransaction(inserts, updates, deletes, { featureNS: 'http://www.openplans.org/topp', featureType: 'states', featurePrefix: 'topp' }); expect(serialized).to.xmleql(ol.xml.parse(text)); }); }); describe('when writing out a Transaction request', function() { var text; before(function(done) { afterLoadText('spec/ol/format/wfs/Native.xml', function(xml) { text = xml; done(); }); }); it('handles writing out Native', function() { var format = new ol.format.WFS(); var serialized = format.writeTransaction(null, null, null, { nativeElements: [{ vendorId: 'ORACLE', safeToIgnore: true, value: 'ALTER SESSION ENABLE PARALLEL DML' }, { vendorId: 'ORACLE', safeToIgnore: false, value: 'Another native line goes here' }] }); expect(serialized).to.xmleql(ol.xml.parse(text)); }); }); describe('when writing out a GetFeature request', function() { var text; before(function(done) { afterLoadText('spec/ol/format/wfs/GetFeatureMultiple.xml', function(xml) { text = xml; done(); }); }); it('handles writing multiple Query elements', function() { var format = new ol.format.WFS(); var serialized = format.writeGetFeature({ featureNS: 'http://www.openplans.org/topp', featureTypes: ['states', 'cities'], featurePrefix: 'topp' }); expect(serialized).to.xmleql(ol.xml.parse(text)); }); }); describe('when parsing GML from MapServer', function() { var features, feature; before(function(done) { afterLoadText('spec/ol/format/wfs/mapserver.xml', function(xml) { try { var config = { 'featureNS': 'http://mapserver.gis.umn.edu/mapserver', 'featureType': 'Historische_Messtischblaetter_WFS' }; features = new ol.format.WFS(config).readFeatures(xml); } catch (e) { done(e); } done(); }); }); it('creates 7 features', function() { expect(features).to.have.length(7); }); it('creates a polygon for Arnstadt', function() { feature = features[0]; var fid = 'Historische_Messtischblaetter_WFS.71055885'; expect(feature.getId()).to.equal(fid); expect(feature.get('titel')).to.equal('Arnstadt'); expect(feature.getGeometry()).to.be.an(ol.geom.Polygon); }); }); describe('when parsing multiple feature types', function() { var features; before(function(done) { afterLoadText('spec/ol/format/gml/multiple-typenames.xml', function(xml) { try { features = new ol.format.WFS({ featureNS: 'http://localhost:8080/official', featureType: ['planet_osm_polygon', 'planet_osm_line'] }).readFeatures(xml); } catch (e) { done(e); } done(); }); }); it('reads all features', function() { expect(features.length).to.be(12); }); }); describe('when parsing multiple feature types', function() { var features; before(function(done) { afterLoadText('spec/ol/format/gml/multiple-typenames.xml', function(xml) { try { features = new ol.format.WFS().readFeatures(xml); } catch (e) { done(e); } done(); }); }); it('reads all features with autoconfigure', function() { expect(features.length).to.be(12); }); }); }); goog.require('ol.xml'); goog.require('ol.Feature'); goog.require('ol.geom.MultiLineString'); goog.require('ol.geom.MultiPoint'); goog.require('ol.geom.MultiPolygon'); goog.require('ol.geom.Polygon'); goog.require('ol.format.GML2'); goog.require('ol.format.WFS'); goog.require('ol.proj');
NOAA-ORR-ERD/ol3
test/spec/ol/format/wfsformat.test.js
JavaScript
bsd-2-clause
18,764
var http = require('http'); // check against public file to see if this is the current version of Mapbox Studio Classic module.exports = function (opts, callback) { var update = false; http.request({ host: opts.host, port: opts.port || 80, path: opts.path, method: 'GET' }, function(response){ var latest = ''; response.on('data', function (chunk) { latest += chunk; }); response.on('end', function () { var current = opts.pckge.version.replace(/^\s+|\s+$/g, ''); latest = latest.replace(/^\s+|\s+$/g, ''); if (latest !== current) { update = true; } return callback(update, current, latest); }); }) .on('error', function(err){ return callback(false); }) .end(); };
mapbox/mapbox-studio
lib/version-check.js
JavaScript
bsd-3-clause
862
var analytics = require('analytics') var d3 = require('d3') var hogan = require('hogan.js') var log = require('./client/log')('help-me-choose') var modal = require('./client/modal') var RouteModal = require('route-modal') var routeResource = require('route-resource') var routeSummarySegments = require('route-summary-segments') var session = require('session') var toCapitalCase = require('to-capital-case') var optionTemplate = hogan.compile(require('./option.html')) var routeTemplate = hogan.compile(require('./route.html')) var primaryFilter = 'totalCost' var secondaryFilter = 'productiveTime' var filters = { travelTime: function (a) { return a.time }, totalCost: function (a) { return a.cost }, walkDistance: function (a) { return a.walkDistance }, calories: function (a) { return -a.calories }, productiveTime: function (a) { return -a.productiveTime }, none: function (a) { return 0 } } /** * Expose `Modal` */ var Modal = module.exports = modal({ closable: true, width: '768px', template: require('./template.html') }, function (view, routes) { view.primaryFilter = view.find('#primary-filter') view.secondaryFilter = view.find('#secondary-filter') view.primaryFilter.querySelector('[value="none"]').remove() view.primaryFilter.value = primaryFilter view.secondaryFilter.value = secondaryFilter view.oneWay = true view.daily = true view.refresh() }) /** * Refresh */ Modal.prototype.refresh = function (e) { if (e) e.preventDefault() log('refreshing') primaryFilter = this.primaryFilter.value secondaryFilter = this.secondaryFilter.value var i var thead = this.find('thead') var tbody = this.find('tbody') // Remove rows tbody.innerHTML = '' // Remove all colors var headers = thead.querySelectorAll('th') for (i = 0; i < headers.length; i++) { headers[i].classList.remove('primaryFilter') headers[i].classList.remove('secondaryFilter') } var phead = thead.querySelector('.' + primaryFilter) if (phead) phead.classList.add('primaryFilter') var shead = thead.querySelector('.' + secondaryFilter) if (shead) shead.classList.add('secondaryFilter') // Get the indexes var primaryFn = filters[primaryFilter] var secondaryFn = filters[secondaryFilter] // Get the multiplier var multiplier = this.oneWay ? 1 : 2 multiplier *= this.daily ? 1 : 365 // Get the route data var routes = this.model.map(function (r, index) { return getRouteData(r, multiplier, index) }) // Sort by secondary first routes = rankRoutes(routes, primaryFn, secondaryFn) // Render for (i = 0; i < routes.length; i++) { var route = routes[i] tbody.innerHTML += this.renderRoute(route) var row = tbody.childNodes[i] var pcell = row.querySelector('.' + primaryFilter) var scell = row.querySelector('.' + secondaryFilter) if (pcell) pcell.style.backgroundColor = toRGBA(route.primaryColor, 0.25) if (scell) scell.style.backgroundColor = toRGBA(route.secondaryColor, 0.25) } // Track the results analytics.track('Viewed "Help Me Choose"', { plan: session.plan().generateQuery(), primaryFilter: primaryFilter, secondaryFilter: secondaryFilter, multiplier: multiplier }) } /** * Append option */ Modal.prototype.renderRoute = function (data) { data.calories = data.calories ? parseInt(data.calories, 10).toLocaleString() + ' cals' : 'None' data.cost = data.cost ? '$' + data.cost.toFixed(2) : 'Free' data.emissions = data.emissions ? parseInt(data.emissions, 10) : 'None' data.walkDistance = data.walkDistance ? data.walkDistance + ' mi' : 'None' if (data.productiveTime) { if (data.productiveTime > 120) { data.productiveTime = parseInt(data.productiveTime / 60, 10).toLocaleString() + ' hrs' } else { data.productiveTime = parseInt(data.productiveTime, 10).toLocaleString() + ' min' } } else { data.productiveTime = 'None' } return routeTemplate.render(data) } /** * Filters */ Modal.prototype.filters = function () { var options = '' for (var f in filters) { options += optionTemplate.render({ name: toCapitalCase(f).toLowerCase(), value: f }) } return options } /** * Select this option */ Modal.prototype.selectRoute = function (e) { e.preventDefault() if (e.target.tagName !== 'BUTTON') return var index = e.target.getAttribute('data-index') var route = this.model[index] var plan = session.plan() var tags = route.tags(plan) var self = this routeResource.findByTags(tags, function (err, resources) { if (err) log.error(err) var routeModal = new RouteModal(route, null, { context: 'help-me-choose', resources: resources }) self.hide() routeModal.show() routeModal.on('next', function () { routeModal.hide() }) }) } /** * Multipliers */ Modal.prototype.setOneWay = function (e) { this.oneWay = true this.setMultiplier(e) } Modal.prototype.setRoundTrip = function (e) { this.oneWay = false this.setMultiplier(e) } Modal.prototype.setDaily = function (e) { this.daily = true this.setMultiplier(e) } Modal.prototype.setYearly = function (e) { this.daily = false this.setMultiplier(e) } Modal.prototype.setMultiplier = function (e) { e.preventDefault() var button = e.target var parent = button.parentNode var buttons = parent.getElementsByTagName('button') for (var i = 0; i < buttons.length; i++) { buttons[i].classList.remove('active') } button.classList.add('active') this.refresh() } /** * Rank & sort the routes */ function rankRoutes (routes, primary, secondary) { var primaryDomain = [d3.min(routes, primary), d3.max(routes, primary)] var secondaryDomain = [d3.min(routes, secondary), d3.max(routes, secondary)] var primaryScale = d3.scale.linear() .domain(primaryDomain) .range([0, routes.length * 2]) var secondaryScale = d3.scale.linear() .domain(secondaryDomain) .range([1, routes.length]) var primaryColor = d3.scale.linear() .domain(primaryDomain) .range(['#f5a81c', '#fff']) var secondaryColor = d3.scale.linear() .domain(secondaryDomain) .range(['#8ec449', '#fff']) routes = routes.map(function (r) { r.primaryRank = primaryScale(primary(r)) r.primaryColor = primaryColor(primary(r)) r.secondaryRank = secondaryScale(secondary(r)) r.secondaryColor = secondaryColor(secondary(r)) r.rank = r.primaryRank + r.secondaryRank return r }) routes.sort(function (a, b) { return a.rank - b.rank }) // lowest number first return routes } /** * RGB to transparent */ function toRGBA (rgb, opacity) { var c = d3.rgb(rgb) return 'rgba(' + c.r + ',' + c.g + ',' + c.b + ',' + opacity + ')' } /** * Get route data */ function getRouteData (route, multiplier, index) { var data = { segments: routeSummarySegments(route, { inline: true }), index: index, time: route.average(), frequency: 0, cost: route.cost(), walkDistance: route.walkDistances(), calories: route.totalCalories(), productiveTime: route.timeInTransit(), emissions: route.emissions(), score: route.score(), rank: 0 } if (multiplier > 1) { ['cost', 'calories', 'productiveTime', 'emissions'].forEach(function (type) { data[type] = data[type] * multiplier }) } return data }
miraculixx/modeify
client/help-me-choose-view/index.js
JavaScript
bsd-3-clause
7,412
goog.provide('goog.testing.PseudoRandom'); goog.require('goog.Disposable'); goog.testing.PseudoRandom = function(opt_seed, opt_install) { goog.Disposable.call(this); this.seed_ = opt_seed || goog.testing.PseudoRandom.seedUniquifier_ ++ + goog.now(); if(opt_install) { this.install(); } }; goog.inherits(goog.testing.PseudoRandom, goog.Disposable); goog.testing.PseudoRandom.seedUniquifier_ = 0; goog.testing.PseudoRandom.A = 48271; goog.testing.PseudoRandom.M = 2147483647; goog.testing.PseudoRandom.Q = 44488; goog.testing.PseudoRandom.R = 3399; goog.testing.PseudoRandom.ONE_OVER_M = 1.0 / goog.testing.PseudoRandom.M; goog.testing.PseudoRandom.prototype.installed_; goog.testing.PseudoRandom.prototype.mathRandom_; goog.testing.PseudoRandom.prototype.install = function() { if(! this.installed_) { this.mathRandom_ = Math.random; Math.random = goog.bind(this.random, this); this.installed_ = true; } }; goog.testing.PseudoRandom.prototype.disposeInternal = function() { goog.testing.PseudoRandom.superClass_.disposeInternal.call(this); this.uninstall(); }; goog.testing.PseudoRandom.prototype.uninstall = function() { if(this.installed_) { Math.random = this.mathRandom_; this.installed_ = false; } }; goog.testing.PseudoRandom.prototype.random = function() { var hi = this.seed_ / goog.testing.PseudoRandom.Q; var lo = this.seed_ % goog.testing.PseudoRandom.Q; var test = goog.testing.PseudoRandom.A * lo - goog.testing.PseudoRandom.R * hi; if(test > 0) { this.seed_ = test; } else { this.seed_ = test + goog.testing.PseudoRandom.M; } return this.seed_ * goog.testing.PseudoRandom.ONE_OVER_M; };
johnjbarton/qpp
traceur/test/closurebaseline/third_party/closure-library/closure/goog/testing/pseudorandom.js
JavaScript
bsd-3-clause
1,713
(function(e){"use strict";e.extend(e.fn.select2.defaults,{formatNoMatches:function(){return"Nu a fost găsit nimic"},formatInputTooShort:function(e,t){var i=t-e.length;return"Vă rugăm să introduceți incă "+i+" caracter"+(1==i?"":"e")},formatInputTooLong:function(e,t){var i=e.length-t;return"Vă rugăm să introduceți mai puțin de "+i+" caracter"+(1==i?"":"e")},formatSelectionTooBig:function(e){return"Aveți voie să selectați cel mult "+e+" element"+(1==e?"":"e")},formatLoadMore:function(){return"Se încarcă..."},formatSearching:function(){return"Căutare..."}})})(jQuery);
xuminready/baiducdnstatic
libs/select2/3.3.2/select2_locale_ro.min.js
JavaScript
mit
588
/// <reference path="../../defs/tsd.d.ts"/> /// <reference path="./interfaces.d.ts"/> var path = require('path'); var fs = require('fs'); var _ = require('lodash'); var utils = require('./utils'); var cache = require('./cacheUtils'); var Promise = require('es6-promise').Promise; exports.grunt = require('grunt'); /////////////////////////// // Helper /////////////////////////// function executeNode(args) { return new Promise(function (resolve, reject) { exports.grunt.util.spawn({ cmd: process.execPath, args: args }, function (error, result, code) { var ret = { code: code, // New TypeScript compiler uses stdout for user code errors. Old one used stderr. output: result.stdout || result.stderr }; resolve(ret); }); }); } ///////////////////////////////////////////////////////////////// // Fast Compilation ///////////////////////////////////////////////////////////////// // Map to store if the cache was cleared after the gruntfile was parsed var cacheClearedOnce = {}; function getChangedFiles(files, targetName) { files = cache.getNewFilesForTarget(files, targetName); _.forEach(files, function (file) { exports.grunt.log.writeln(('### Fast Compile >>' + file).cyan); }); return files; } function resetChangedFiles(files, targetName) { cache.compileSuccessfull(files, targetName); } function clearCache(targetName) { cache.clearCache(targetName); cacheClearedOnce[targetName] = true; } ///////////////////////////////////////////////////////////////////// // tsc handling //////////////////////////////////////////////////////////////////// function resolveTypeScriptBinPath() { var ownRoot = path.resolve(path.dirname((module).filename), '../..'); var userRoot = path.resolve(ownRoot, '..', '..'); var binSub = path.join('node_modules', 'typescript', 'bin'); if (fs.existsSync(path.join(userRoot, binSub))) { // Using project override return path.join(userRoot, binSub); } return path.join(ownRoot, binSub); } function getTsc(binPath) { var pkg = JSON.parse(fs.readFileSync(path.resolve(binPath, '..', 'package.json')).toString()); exports.grunt.log.writeln('Using tsc v' + pkg.version); return path.join(binPath, 'tsc'); } function compileAllFiles(targetFiles, target, task, targetName) { // Make a local copy so we can modify files without having external side effects var files = _.map(targetFiles, function (file) { return file; }); var newFiles = files; if (task.fast === 'watch') { // if this is the first time its running after this file was loaded if (cacheClearedOnce[exports.grunt.task.current.target] === undefined) { // Then clear the cache for this target clearCache(targetName); } } if (task.fast !== 'never') { if (target.out) { exports.grunt.log.writeln('Fast compile will not work when --out is specified. Ignoring fast compilation'.cyan); } else { newFiles = getChangedFiles(files, targetName); if (newFiles.length !== 0) { files = newFiles; // If outDir is specified but no baseDir is specified we need to determine one if (target.outDir && !target.baseDir) { target.baseDir = utils.findCommonPath(files, '/'); } } else { exports.grunt.log.writeln('No file changes were detected. Skipping Compile'.green); return new Promise(function (resolve) { var ret = { code: 0, fileCount: 0, output: 'No files compiled as no change detected' }; resolve(ret); }); } } } // Transform files as needed. Currently all of this logic in is one module // transformers.transformFiles(newFiles, targetFiles, target, task); // If baseDir is specified create a temp tsc file to make sure that `--outDir` works fine // see https://github.com/grunt-ts/grunt-ts/issues/77 var baseDirFile = '.baseDir.ts'; var baseDirFilePath; if (target.outDir && target.baseDir && files.length > 0) { baseDirFilePath = path.join(target.baseDir, baseDirFile); if (!fs.existsSync(baseDirFilePath)) { exports.grunt.file.write(baseDirFilePath, '// Ignore this file. See https://github.com/grunt-ts/grunt-ts/issues/77'); } files.push(baseDirFilePath); } // If reference and out are both specified. // Then only compile the updated reference file as that contains the correct order if (target.reference && target.out) { var referenceFile = path.resolve(target.reference); files = [referenceFile]; } // Quote the files to compile. Needed for command line parsing by tsc files = _.map(files, function (item) { return '"' + path.resolve(item) + '"'; }); var args = files.slice(0); // boolean options if (task.sourceMap) { args.push('--sourcemap'); } if (task.declaration) { args.push('--declaration'); } if (task.removeComments) { args.push('--removeComments'); } if (task.noImplicitAny) { args.push('--noImplicitAny'); } if (task.noResolve) { args.push('--noResolve'); } if (task.noEmitOnError) { args.push('--noEmitOnError'); } if (task.preserveConstEnums) { args.push('--preserveConstEnums'); } if (task.suppressImplicitAnyIndexErrors) { args.push('--suppressImplicitAnyIndexErrors'); } // string options args.push('--target', task.target.toUpperCase()); // check the module compile option if (task.module) { var moduleOptionString = task.module.toLowerCase(); if (moduleOptionString === 'amd' || moduleOptionString === 'commonjs') { args.push('--module', moduleOptionString); } else { console.warn('WARNING: Option "module" does only support "amd" | "commonjs"'.magenta); } } // Target options: if (target.out) { args.push('--out', target.out); } if (target.outDir) { if (target.out) { console.warn('WARNING: Option "out" and "outDir" should not be used together'.magenta); } args.push('--outDir', target.outDir); } if (target.dest && (!target.out) && (!target.outDir)) { if (utils.isJavaScriptFile(target.dest)) { args.push('--out', target.dest); } else { if (target.dest === 'src') { console.warn(('WARNING: Destination for target "' + targetName + '" is "src", which is the default. If you have' + ' forgotten to specify a "dest" parameter, please add it. If this is correct, you may wish' + ' to change the "dest" parameter to "src/" or just ignore this warning.').magenta); } if (Array.isArray(target.dest)) { if (target.dest.length === 0) { } else if (target.dest.length > 0) { console.warn((('WARNING: "dest" for target "' + targetName + '" is an array. This is not supported by the' + ' TypeScript compiler or grunt-ts.' + ((target.dest.length > 1) ? ' Only the first "dest" will be used. The' + ' remaining items will be truncated.' : ''))).magenta); args.push('--outDir', target.dest[0]); } } else { args.push('--outDir', target.dest); } } } if (task.sourceRoot) { args.push('--sourceRoot', task.sourceRoot); } if (task.mapRoot) { args.push('--mapRoot', task.mapRoot); } // Locate a compiler var tsc; if (task.compiler) { exports.grunt.log.writeln('Using the custom compiler : ' + task.compiler); tsc = task.compiler; } else { tsc = getTsc(resolveTypeScriptBinPath()); } // To debug the tsc command if (task.verbose) { console.log(args.join(' ').yellow); } else { exports.grunt.log.verbose.writeln(args.join(' ').yellow); } // Create a temp last command file and use that to guide tsc. // Reason: passing all the files on the command line causes TSC to go in an infinite loop. var tempfilename = utils.getTempFile('tscommand'); if (!tempfilename) { throw (new Error('cannot create temp file')); } fs.writeFileSync(tempfilename, args.join(' ')); // Execute command return executeNode([tsc, '@' + tempfilename]).then(function (result) { if (task.fast !== 'never' && result.code === 0) { resetChangedFiles(newFiles, targetName); } result.fileCount = files.length; fs.unlinkSync(tempfilename); exports.grunt.log.writeln(result.output); return Promise.cast(result); }, function (err) { fs.unlinkSync(tempfilename); throw err; }); } exports.compileAllFiles = compileAllFiles; //# sourceMappingURL=compile.js.map
Softpagehomeware/grunt-ts
tasks/modules/compile.js
JavaScript
mit
9,276
/* Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.help.console"]){ dojo._hasResource["dojox.help.console"]=true; dojo.provide("dojox.help.console"); dojo.require("dojox.help._base"); dojo.mixin(dojox.help,{_plainText:function(_1){ return _1.replace(/(<[^>]*>|&[^;]{2,6};)/g,""); },_displayLocated:function(_2){ var _3={}; dojo.forEach(_2,function(_4){ _3[_4[0]]=dojo.isMoz?{toString:function(){ return "Click to view"; },item:_4[1]}:_4[1]; }); },_displayHelp:function(_5,_6){ if(_5){ var _7="Help for: "+_6.name; var _8=""; for(var i=0;i<_7.length;i++){ _8+="="; } }else{ if(!_6){ }else{ var _9=false; for(var _a in _6){ var _b=_6[_a]; if(_a=="returns"&&_6.type!="Function"&&_6.type!="Constructor"){ continue; } if(_b&&(!dojo.isArray(_b)||_b.length)){ _9=true; _b=dojo.isString(_b)?dojox.help._plainText(_b):_b; if(_a=="returns"){ var _c=dojo.map(_b.types||[],"return item.title;").join("|"); if(_b.summary){ if(_c){ _c+=": "; } _c+=dojox.help._plainText(_b.summary); } }else{ if(_a=="parameters"){ for(var j=0,_d;_d=_b[j];j++){ var _e=dojo.map(_d.types,"return item.title").join("|"); var _f=""; if(_d.optional){ _f+="Optional. "; } if(_d.repating){ _f+="Repeating. "; } _f+=dojox.help._plainText(_d.summary); if(_f){ _f=" - "+_f; for(var k=0;k<_d.name.length;k++){ _f=" "+_f; } } } }else{ } } } } if(!_9){ } } } }}); dojox.help.init(); }
bjorns/logger
src/main/webapp/js/dojox/help/console.js
JavaScript
mit
1,517
version https://git-lfs.github.com/spec/v1 oid sha256:b386bb4d8bf9eb9e8099152a3eb963073051fb960b30cd512b6a07bd1f751d3d size 734
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.2.0/datatype/lang/datatype_it-IT.js
JavaScript
mit
128
var fs = require('fs') var path = require('path') var util = require('util') var semver = require('semver') exports.checkEngine = checkEngine function checkEngine (target, npmVer, nodeVer, force, strict, cb) { var nodev = force ? null : nodeVer var eng = target.engines var opt = { includePrerelease: true } if (!eng) return cb() if (nodev && eng.node && !semver.satisfies(nodev, eng.node, opt) || eng.npm && !semver.satisfies(npmVer, eng.npm, opt)) { var er = new Error(util.format('Unsupported engine for %s: wanted: %j (current: %j)', target._id, eng, {node: nodev, npm: npmVer})) er.code = 'ENOTSUP' er.required = eng er.pkgid = target._id if (strict) { return cb(er) } else { return cb(null, er) } } return cb() } exports.checkPlatform = checkPlatform function checkPlatform (target, force, cb) { var platform = process.platform var arch = process.arch var osOk = true var cpuOk = true if (force) { return cb() } if (target.os) { osOk = checkList(platform, target.os) } if (target.cpu) { cpuOk = checkList(arch, target.cpu) } if (!osOk || !cpuOk) { var er = new Error(util.format('Unsupported platform for %s: wanted %j (current: %j)', target._id, target, {os: platform, cpu: arch})) er.code = 'EBADPLATFORM' er.os = target.os || ['any'] er.cpu = target.cpu || ['any'] er.pkgid = target._id return cb(er) } return cb() } function checkList (value, list) { var tmp var match = false var blc = 0 if (typeof list === 'string') { list = [list] } if (list.length === 1 && list[0] === 'any') { return true } for (var i = 0; i < list.length; ++i) { tmp = list[i] if (tmp[0] === '!') { tmp = tmp.slice(1) if (tmp === value) { return false } ++blc } else { match = match || tmp === value } } return match || blc === list.length } exports.checkCycle = checkCycle function checkCycle (target, ancestors, cb) { // there are some very rare and pathological edge-cases where // a cycle can cause npm to try to install a never-ending tree // of stuff. // Simplest: // // A -> B -> A' -> B' -> A -> B -> A' -> B' -> A -> ... // // Solution: Simply flat-out refuse to install any name@version // that is already in the prototype tree of the ancestors object. // A more correct, but more complex, solution would be to symlink // the deeper thing into the new location. // Will do that if anyone whines about this irl. // // Note: `npm install foo` inside of the `foo` package will abort // earlier if `--force` is not set. However, if it IS set, then // we need to still fail here, but just skip the first level. Of // course, it'll still fail eventually if it's a true cycle, and // leave things in an undefined state, but that's what is to be // expected when `--force` is used. That is why getPrototypeOf // is used *twice* here: to skip the first level of repetition. var p = Object.getPrototypeOf(Object.getPrototypeOf(ancestors)) var name = target.name var version = target.version while (p && p !== Object.prototype && p[name] !== version) { p = Object.getPrototypeOf(p) } if (p[name] !== version) return cb() var er = new Error(target._id + ': Unresolvable cycle detected') var tree = [target._id, JSON.parse(JSON.stringify(ancestors))] var t = Object.getPrototypeOf(ancestors) while (t && t !== Object.prototype) { if (t === p) t.THIS_IS_P = true tree.push(JSON.parse(JSON.stringify(t))) t = Object.getPrototypeOf(t) } er.pkgid = target._id er.code = 'ECYCLE' return cb(er) } exports.checkGit = checkGit function checkGit (folder, cb) { // if it's a git repo then don't touch it! fs.lstat(folder, function (er, s) { if (er || !s.isDirectory()) return cb() else checkGit_(folder, cb) }) } function checkGit_ (folder, cb) { fs.stat(path.resolve(folder, '.git'), function (er, s) { if (!er && s.isDirectory()) { var e = new Error(folder + ': Appears to be a git repo or submodule.') e.path = folder e.code = 'EISGIT' return cb(e) } cb() }) }
giovannic/giovannic.github.com
node_modules/npm/node_modules/npm-install-checks/index.js
JavaScript
mit
4,201
define(["bin/core/naviPageView"], function(Base) { var Class = {}; Class.onViewPush = function(pushFrom, pushData) { this._config = pushData; } Class.genHTML = function() { Base.prototype.genHTML.call(this); this.setTitle("示例 "+this._config.name); } return Base.extend(Class); });
weizhiwu/BIN
demo/common/demoView.js
JavaScript
mit
316
/* * Websock: high-performance binary WebSockets * Copyright (C) 2012 Joel Martin * Licensed under MPL 2.0 (see LICENSE.txt) * * Websock is similar to the standard WebSocket object but Websock * enables communication with raw TCP sockets (i.e. the binary stream) * via websockify. This is accomplished by base64 encoding the data * stream between Websock and websockify. * * Websock has built-in receive queue buffering; the message event * does not contain actual data but is simply a notification that * there is new data available. Several rQ* methods are available to * read binary data off of the receive queue. */ /*jslint browser: true, bitwise: true */ /*global Util*/ // Load Flash WebSocket emulator if needed // To force WebSocket emulator even when native WebSocket available //window.WEB_SOCKET_FORCE_FLASH = true; // To enable WebSocket emulator debug: //window.WEB_SOCKET_DEBUG=1; if (window.WebSocket && !window.WEB_SOCKET_FORCE_FLASH) { Websock_native = true; } else if (window.MozWebSocket && !window.WEB_SOCKET_FORCE_FLASH) { Websock_native = true; window.WebSocket = window.MozWebSocket; } else { /* no builtin WebSocket so load web_socket.js */ Websock_native = false; } function Websock() { "use strict"; this._websocket = null; // WebSocket object this._rQi = 0; // Receive queue index this._rQlen = 0; // Next write position in the receive queue this._rQbufferSize = 1024 * 1024 * 4; // Receive queue buffer size (4 MiB) this._rQmax = this._rQbufferSize / 8; // called in init: this._rQ = new Uint8Array(this._rQbufferSize); this._rQ = null; // Receive queue this._sQbufferSize = 1024 * 10; // 10 KiB // called in init: this._sQ = new Uint8Array(this._sQbufferSize); this._sQlen = 0; this._sQ = null; // Send queue this._mode = 'binary'; // Current WebSocket mode: 'binary', 'base64' this.maxBufferedAmount = 200; this._eventHandlers = { 'message': function () {}, 'open': function () {}, 'close': function () {}, 'error': function () {} }; } (function () { "use strict"; // this has performance issues in some versions Chromium, and // doesn't gain a tremendous amount of performance increase in Firefox // at the moment. It may be valuable to turn it on in the future. var ENABLE_COPYWITHIN = false; var MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB var typedArrayToString = (function () { // This is only for PhantomJS, which doesn't like apply-ing // with Typed Arrays try { var arr = new Uint8Array([1, 2, 3]); String.fromCharCode.apply(null, arr); return function (a) { return String.fromCharCode.apply(null, a); }; } catch (ex) { return function (a) { return String.fromCharCode.apply( null, Array.prototype.slice.call(a)); }; } })(); Websock.prototype = { // Getters and Setters get_sQ: function () { return this._sQ; }, get_rQ: function () { return this._rQ; }, get_rQi: function () { return this._rQi; }, set_rQi: function (val) { this._rQi = val; }, // Receive Queue rQlen: function () { return this._rQlen - this._rQi; }, rQpeek8: function () { return this._rQ[this._rQi]; }, rQshift8: function () { return this._rQ[this._rQi++]; }, rQskip8: function () { this._rQi++; }, rQskipBytes: function (num) { this._rQi += num; }, // TODO(directxman12): test performance with these vs a DataView rQshift16: function () { return (this._rQ[this._rQi++] << 8) + this._rQ[this._rQi++]; }, rQshift32: function () { return (this._rQ[this._rQi++] << 24) + (this._rQ[this._rQi++] << 16) + (this._rQ[this._rQi++] << 8) + this._rQ[this._rQi++]; }, rQshiftStr: function (len) { if (typeof(len) === 'undefined') { len = this.rQlen(); } var arr = new Uint8Array(this._rQ.buffer, this._rQi, len); this._rQi += len; return typedArrayToString(arr); }, rQshiftBytes: function (len) { if (typeof(len) === 'undefined') { len = this.rQlen(); } this._rQi += len; return new Uint8Array(this._rQ.buffer, this._rQi - len, len); }, rQshiftTo: function (target, len) { if (len === undefined) { len = this.rQlen(); } // TODO: make this just use set with views when using a ArrayBuffer to store the rQ target.set(new Uint8Array(this._rQ.buffer, this._rQi, len)); this._rQi += len; }, rQwhole: function () { return new Uint8Array(this._rQ.buffer, 0, this._rQlen); }, rQslice: function (start, end) { if (end) { return new Uint8Array(this._rQ.buffer, this._rQi + start, end - start); } else { return new Uint8Array(this._rQ.buffer, this._rQi + start, this._rQlen - this._rQi - start); } }, // Check to see if we must wait for 'num' bytes (default to FBU.bytes) // to be available in the receive queue. Return true if we need to // wait (and possibly print a debug message), otherwise false. rQwait: function (msg, num, goback) { var rQlen = this._rQlen - this._rQi; // Skip rQlen() function call if (rQlen < num) { if (goback) { if (this._rQi < goback) { throw new Error("rQwait cannot backup " + goback + " bytes"); } this._rQi -= goback; } return true; // true means need more data } return false; }, // Send Queue flush: function () { if (this._websocket.bufferedAmount !== 0) { Util.Debug("bufferedAmount: " + this._websocket.bufferedAmount); } if (this._websocket.bufferedAmount < this.maxBufferedAmount) { if (this._sQlen > 0 && this._websocket.readyState === WebSocket.OPEN) { this._websocket.send(this._encode_message()); this._sQlen = 0; } return true; } else { Util.Info("Delaying send, bufferedAmount: " + this._websocket.bufferedAmount); return false; } }, send: function (arr) { this._sQ.set(arr, this._sQlen); this._sQlen += arr.length; return this.flush(); }, send_string: function (str) { this.send(str.split('').map(function (chr) { return chr.charCodeAt(0); })); }, // Event Handlers off: function (evt) { this._eventHandlers[evt] = function () {}; }, on: function (evt, handler) { this._eventHandlers[evt] = handler; }, _allocate_buffers: function () { this._rQ = new Uint8Array(this._rQbufferSize); this._sQ = new Uint8Array(this._sQbufferSize); }, init: function (protocols, ws_schema) { this._allocate_buffers(); this._rQi = 0; this._websocket = null; // Check for full typed array support var bt = false; if (('Uint8Array' in window) && ('set' in Uint8Array.prototype)) { bt = true; } // Check for full binary type support in WebSockets // Inspired by: // https://github.com/Modernizr/Modernizr/issues/370 // https://github.com/Modernizr/Modernizr/blob/master/feature-detects/websockets/binary.js var wsbt = false; try { if (bt && ('binaryType' in WebSocket.prototype || !!(new WebSocket(ws_schema + '://.').binaryType))) { Util.Info("Detected binaryType support in WebSockets"); wsbt = true; } } catch (exc) { // Just ignore failed test localhost connection } // Default protocols if not specified if (typeof(protocols) === "undefined") { protocols = 'binary'; } if (Array.isArray(protocols) && protocols.indexOf('binary') > -1) { protocols = 'binary'; } if (!wsbt) { throw new Error("noVNC no longer supports base64 WebSockets. " + "Please use a browser which supports binary WebSockets."); } if (protocols != 'binary') { throw new Error("noVNC no longer supports base64 WebSockets. Please " + "use the binary subprotocol instead."); } return protocols; }, open: function (uri, protocols) { var ws_schema = uri.match(/^([a-z]+):\/\//)[1]; protocols = this.init(protocols, ws_schema); this._websocket = new WebSocket(uri, protocols); if (protocols.indexOf('binary') >= 0) { this._websocket.binaryType = 'arraybuffer'; } this._websocket.onmessage = this._recv_message.bind(this); this._websocket.onopen = (function () { Util.Debug('>> WebSock.onopen'); if (this._websocket.protocol) { this._mode = this._websocket.protocol; Util.Info("Server choose sub-protocol: " + this._websocket.protocol); } else { this._mode = 'binary'; Util.Error('Server select no sub-protocol!: ' + this._websocket.protocol); } if (this._mode != 'binary') { throw new Error("noVNC no longer supports base64 WebSockets. Please " + "use the binary subprotocol instead."); } this._eventHandlers.open(); Util.Debug("<< WebSock.onopen"); }).bind(this); this._websocket.onclose = (function (e) { Util.Debug(">> WebSock.onclose"); this._eventHandlers.close(e); Util.Debug("<< WebSock.onclose"); }).bind(this); this._websocket.onerror = (function (e) { Util.Debug(">> WebSock.onerror: " + e); this._eventHandlers.error(e); Util.Debug("<< WebSock.onerror: " + e); }).bind(this); }, close: function () { if (this._websocket) { if ((this._websocket.readyState === WebSocket.OPEN) || (this._websocket.readyState === WebSocket.CONNECTING)) { Util.Info("Closing WebSocket connection"); this._websocket.close(); } this._websocket.onmessage = function (e) { return; }; } }, // private methods _encode_message: function () { // Put in a binary arraybuffer // according to the spec, you can send ArrayBufferViews with the send method return new Uint8Array(this._sQ.buffer, 0, this._sQlen); }, _expand_compact_rQ: function (min_fit) { var resizeNeeded = min_fit || this._rQlen - this._rQi > this._rQbufferSize / 2; if (resizeNeeded) { if (!min_fit) { // just double the size if we need to do compaction this._rQbufferSize *= 2; } else { // otherwise, make sure we satisy rQlen - rQi + min_fit < rQbufferSize / 8 this._rQbufferSize = (this._rQlen - this._rQi + min_fit) * 8; } } // we don't want to grow unboundedly if (this._rQbufferSize > MAX_RQ_GROW_SIZE) { this._rQbufferSize = MAX_RQ_GROW_SIZE; if (this._rQbufferSize - this._rQlen - this._rQi < min_fit) { throw new Exception("Receive Queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit"); } } if (resizeNeeded) { var old_rQbuffer = this._rQ.buffer; this._rQmax = this._rQbufferSize / 8; this._rQ = new Uint8Array(this._rQbufferSize); this._rQ.set(new Uint8Array(old_rQbuffer, this._rQi)); } else { if (ENABLE_COPYWITHIN) { this._rQ.copyWithin(0, this._rQi); } else { this._rQ.set(new Uint8Array(this._rQ.buffer, this._rQi)); } } this._rQlen = this._rQlen - this._rQi; this._rQi = 0; }, _decode_message: function (data) { // push arraybuffer values onto the end var u8 = new Uint8Array(data); if (u8.length > this._rQbufferSize - this._rQlen) { this._expand_compact_rQ(u8.length); } this._rQ.set(u8, this._rQlen); this._rQlen += u8.length; }, _recv_message: function (e) { try { this._decode_message(e.data); if (this.rQlen() > 0) { this._eventHandlers.message(); // Compact the receive queue if (this._rQlen == this._rQi) { this._rQlen = 0; this._rQi = 0; } else if (this._rQlen > this._rQmax) { this._expand_compact_rQ(); } } else { Util.Debug("Ignoring empty message"); } } catch (exc) { var exception_str = ""; if (exc.name) { exception_str += "\n name: " + exc.name + "\n"; exception_str += " message: " + exc.message + "\n"; } if (typeof exc.description !== 'undefined') { exception_str += " description: " + exc.description + "\n"; } if (typeof exc.stack !== 'undefined') { exception_str += exc.stack; } if (exception_str.length > 0) { Util.Error("recv_message, caught exception: " + exception_str); } else { Util.Error("recv_message, caught exception: " + exc); } if (typeof exc.name !== 'undefined') { this._eventHandlers.error(exc.name + ": " + exc.message); } else { this._eventHandlers.error(exc); } } } }; })();
jerry-0824/017_stone
web/vnc/include/websock.js
JavaScript
mit
15,502
'use strict'; var dynamoose = require('../'); dynamoose.AWS.config.update({ accessKeyId: 'AKID', secretAccessKey: 'SECRET', region: 'us-east-1' }); dynamoose.local(); var should = require('should'); var Cat, Cat2; describe('Model', function (){ this.timeout(5000); before(function(done) { this.timeout(12000); dynamoose.setDefaults({ prefix: 'test-' }); Cat = dynamoose.model('Cat', { id: Number, name: String, owner: String, age: { type: Number }, vet:{ name: String, address: String }, ears:[{ name: String }], legs: [String], more: Object, array: Array }, {useDocumentTypes: true}); // Create a model with a range key Cat2 = dynamoose.model('Cat2', { ownerId: { type: Number, hashKey: true }, name: { type: String, rangeKey: true } }); done(); }); after(function (done) { delete dynamoose.models['test-Cat']; done(); }); it('Create simple model', function (done) { this.timeout(12000); Cat.should.have.property('$__'); Cat.$__.name.should.eql('test-Cat'); Cat.$__.options.should.have.property('create', true); var schema = Cat.$__.schema; should.exist(schema); schema.attributes.id.type.name.should.eql('number'); should(schema.attributes.id.isSet).not.be.ok; should.not.exist(schema.attributes.id.default); should.not.exist(schema.attributes.id.validator); should(schema.attributes.id.required).not.be.ok; schema.attributes.name.type.name.should.eql('string'); schema.attributes.name.isSet.should.not.be.ok; should.not.exist(schema.attributes.name.default); should.not.exist(schema.attributes.name.validator); should(schema.attributes.name.required).not.be.ok; schema.hashKey.should.equal(schema.attributes.id); // should be same object should.not.exist(schema.rangeKey); var kitten = new Cat( { id: 1, name: 'Fluffy', vet:{name:'theVet', address:'12 somewhere'}, ears:[{name:'left'}, {name:'right'}], legs: ['front right', 'front left', 'back right', 'back left'], more: {fovorites: {food: 'fish'}}, array: [{one: '1'}] } ); kitten.id.should.eql(1); kitten.name.should.eql('Fluffy'); var dynamoObj = schema.toDynamo(kitten); dynamoObj.should.eql( { ears: { L: [ { M: { name: { S: 'left' } } }, { M: { name: { S: 'right' } } } ] }, id: { N: '1' }, name: { S: 'Fluffy' }, vet: { M: { address: { S: '12 somewhere' }, name: { S: 'theVet' } } }, legs: { SS: ['front right', 'front left', 'back right', 'back left']}, more: { S: '{"fovorites":{"food":"fish"}}' }, array: { S: '[{"one":"1"}]' } }); kitten.save(done); }); it('Create simple model with range key', function () { Cat2.should.have.property('$__'); Cat2.$__.name.should.eql('test-Cat2'); Cat2.$__.options.should.have.property('create', true); var schema = Cat2.$__.schema; should.exist(schema); schema.attributes.ownerId.type.name.should.eql('number'); should(schema.attributes.ownerId.isSet).not.be.ok; should.not.exist(schema.attributes.ownerId.default); should.not.exist(schema.attributes.ownerId.validator); should(schema.attributes.ownerId.required).not.be.ok; schema.attributes.name.type.name.should.eql('string'); schema.attributes.name.isSet.should.not.be.ok; should.not.exist(schema.attributes.name.default); should.not.exist(schema.attributes.name.validator); should(schema.attributes.name.required).not.be.ok; schema.hashKey.should.equal(schema.attributes.ownerId); // should be same object schema.rangeKey.should.equal(schema.attributes.name); }); it('Get item for model', function (done) { Cat.get(1, function(err, model) { should.not.exist(err); should.exist(model); model.should.have.property('id', 1); model.should.have.property('name', 'Fluffy'); model.should.have.property('vet', { address: '12 somewhere', name: 'theVet' }); model.should.have.property('$__'); done(); }); }); it('Save existing item', function (done) { Cat.get(1, function(err, model) { should.not.exist(err); should.exist(model); model.name.should.eql('Fluffy'); model.name = 'Bad Cat'; model.vet.name = 'Tough Vet'; model.ears[0].name = 'right'; model.save(function (err) { should.not.exist(err); Cat.get({id: 1}, {consistent: true}, function(err, badCat) { should.not.exist(err); badCat.name.should.eql('Bad Cat'); badCat.vet.name.should.eql('Tough Vet'); badCat.ears[0].name.should.eql('right'); badCat.ears[1].name.should.eql('right'); done(); }); }); }); }); it('Save existing item with a false condition', function (done) { Cat.get(1, function(err, model) { should.not.exist(err); should.exist(model); model.name.should.eql('Bad Cat'); model.name = 'Whiskers'; model.save({ condition: '#name = :name', conditionNames: { name: 'name' }, conditionValues: { name: 'Muffin' } }, function (err) { should.exist(err); err.code.should.eql('ConditionalCheckFailedException'); Cat.get({id: 1}, {consistent: true}, function(err, badCat) { should.not.exist(err); badCat.name.should.eql('Bad Cat'); done(); }); }); }); }); it('Save existing item with a true condition', function (done) { Cat.get(1, function(err, model) { should.not.exist(err); should.exist(model); model.name.should.eql('Bad Cat'); model.name = 'Whiskers'; model.save({ condition: '#name = :name', conditionNames: { name: 'name' }, conditionValues: { name: 'Bad Cat' } }, function (err) { should.not.exist(err); Cat.get({id: 1}, {consistent: true}, function(err, whiskers) { should.not.exist(err); whiskers.name.should.eql('Whiskers'); done(); }); }); }); }); it('Save with a pre hook', function (done) { var flag = false; Cat.pre('save', function (next) { flag = true; next(); }); Cat.get(1, function(err, model) { should.not.exist(err); should.exist(model); model.name.should.eql('Whiskers'); model.name = 'Fluffy'; model.vet.name = 'Nice Guy'; model.save(function (err) { should.not.exist(err); Cat.get({id: 1}, {consistent: true}, function(err, badCat) { should.not.exist(err); badCat.name.should.eql('Fluffy'); badCat.vet.name.should.eql('Nice Guy'); flag.should.be.true; Cat.removePre('save'); done(); }); }); }); }); it('Deletes item', function (done) { var cat = new Cat({id: 1}); cat.delete(done); }); it('Get missing item', function (done) { Cat.get(1, function(err, model) { should.not.exist(err); should.not.exist(model); done(); }); }); it('Static Creates new item', function (done) { Cat.create({id: 666, name: 'Garfield'}, function (err, garfield) { should.not.exist(err); should.exist(garfield); garfield.id.should.eql(666); done(); }); }); it('Static Creates new item with range key', function (done) { Cat2.create({ownerId: 666, name: 'Garfield'}, function (err, garfield) { should.not.exist(err); should.exist(garfield); garfield.ownerId.should.eql(666); done(); }); }); it('Prevent duplicate create', function (done) { Cat.create({id: 666, name: 'Garfield'}, function (err, garfield) { should.exist(err); should.not.exist(garfield); done(); }); }); it('Prevent duplicate create with range key', function (done) { Cat2.create({ownerId: 666, name: 'Garfield'}, function (err, garfield) { should.exist(err); should.not.exist(garfield); done(); }); }); it('Static Creates second item', function (done) { Cat.create({id: 777, name: 'Catbert'}, function (err, catbert) { should.not.exist(err); should.exist(catbert); catbert.id.should.eql(777); done(); }); }); it('BatchGet items', function (done) { Cat.batchGet([{id: 666}, {id: 777}], function (err, cats) { cats.length.should.eql(2); done(); }); }); it('Static Delete', function (done) { Cat.delete(666, function (err) { should.not.exist(err); Cat.get(666, function (err, delCat) { should.not.exist(err); should.not.exist(delCat); Cat.delete(777, done); }); }); }); it('Static Delete with range key', function (done) { Cat2.delete({ ownerId: 666, name: 'Garfield' }, function (err) { should.not.exist(err); Cat2.get({ ownerId: 666, name: 'Garfield' }, function (err, delCat) { should.not.exist(err); should.not.exist(delCat); done(); }); }); }); it('Static Creates new item', function (done) { Cat.create({id: 666, name: 'Garfield'}, function (err, garfield) { should.not.exist(err); should.exist(garfield); garfield.id.should.eql(666); done(); }); }); it('Static Delete with update', function (done) { Cat.delete(666, { update: true }, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(666); data.name.should.eql('Garfield'); Cat.get(666, function (err, delCat) { should.not.exist(err); should.not.exist(delCat); done(); }); }); }); it('Static Delete with update failure', function (done) { Cat.delete(666, { update: true }, function (err) { should.exist(err); err.statusCode.should.eql(400); err.code.should.eql('ConditionalCheckFailedException'); done(); }); }); describe('Model.update', function (){ before(function (done) { var stray = new Cat({id: 999, name: 'Tom'}); stray.save(done); }); it('False condition', function (done) { Cat.update({id: 999}, {name: 'Oliver'}, { condition: '#name = :name', conditionNames: { name: 'name' }, conditionValues: { name: 'Muffin' } }, function (err) { should.exist(err); Cat.get(999, function (err, tomcat) { should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); tomcat.name.should.eql('Tom'); should.not.exist(tomcat.owner); should.not.exist(tomcat.age); done(); }); }); }); it('True condition', function (done) { Cat.update({id: 999}, {name: 'Oliver'}, { condition: '#name = :name', conditionNames: { name: 'name' }, conditionValues: { name: 'Tom' } }, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(999); data.name.should.equal('Oliver'); Cat.get(999, function (err, oliver) { should.not.exist(err); should.exist(oliver); oliver.id.should.eql(999); oliver.name.should.eql('Oliver'); should.not.exist(oliver.owner); should.not.exist(oliver.age); done(); }); }); }); it('Default puts attribute', function (done) { Cat.update({id: 999}, {name: 'Tom'}, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(999); data.name.should.equal('Tom'); Cat.get(999, function (err, tomcat){ should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); tomcat.name.should.eql('Tom'); should.not.exist(tomcat.owner); should.not.exist(tomcat.age); done(); }); }); }); it('Manual puts attribute with removal', function (done) { Cat.update({id: 999}, {$PUT: {name: null}}, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(999); should.not.exist(data.name); Cat.get(999, function (err, tomcat){ should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); should.not.exist(tomcat.name); done(); }); }); }); it('Manual puts attribute', function (done) { Cat.update({id: 999}, {$PUT: {name: 'Tom', owner: 'Jerry', age: 3}}, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(999); data.owner.should.equal('Jerry'); Cat.get(999, function (err, tomcat){ should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); tomcat.name.should.eql('Tom'); tomcat.owner.should.eql('Jerry'); tomcat.age.should.eql(3); done(); }); }); }); it('Add attribute', function (done) { Cat.update({id: 999}, {$ADD: {age: 1}}, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(999); data.age.should.equal(4); Cat.get(999, function (err, tomcat){ should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); tomcat.name.should.eql('Tom'); tomcat.owner.should.eql('Jerry'); tomcat.age.should.eql(4); done(); }); }); }); it('Delete attribute', function (done) { Cat.update({id: 999}, {$DELETE: {owner: null}}, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(999); should.not.exist(data.owner); Cat.get(999, function (err, tomcat){ should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); tomcat.name.should.eql('Tom'); should.not.exist(tomcat.owner); tomcat.age.should.eql(4); done(); }); }); }); }); describe('Model.batchPut', function (){ it('Put new', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat({id: 10+i, name: 'Tom_'+i})); } Cat.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); Object.getOwnPropertyNames(result.UnprocessedItems).length.should.eql(0); for (var i=0 ; i<10 ; ++i) { delete cats[i].name; } Cat.batchGet(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); result2.length.should.eql(cats.length); done(); }); }); }); it('Put lots of new items', function (done) { var cats = []; for (var i=0 ; i<100 ; ++i) { cats.push(new Cat({id: 100+i, name: 'Tom_'+i})); } Cat.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); Object.getOwnPropertyNames(result.UnprocessedItems).length.should.eql(0); for (var i=0 ; i<100 ; ++i) { delete cats[i].name; } Cat.batchGet(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); result2.length.should.eql(cats.length); done(); }); }); }); it('Put new with range key', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat2({ownerId: 10+i, name: 'Tom_'+i})); } Cat2.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); Object.getOwnPropertyNames(result.UnprocessedItems).length.should.eql(0); Cat2.batchGet(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); result2.length.should.eql(cats.length); done(); }); }); }); it('Put new without range key', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat2({ownerId: 10+i})); } Cat2.batchPut(cats, function (err, result) { should.exist(err); should.not.exist(result); done(); }); }); it('Update items', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat({id: 20+i, name: 'Tom_'+i})); } Cat.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); for (var i=0 ; i<10 ; ++i) { var cat = cats[i]; cat.name = 'John_' + (cat.id + 100); } Cat.batchPut(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); for (var i=0 ; i<10 ; ++i) { delete cats[i].name; } Cat.batchGet(cats, function (err3, result3) { should.not.exist(err3); should.exist(result3); result3.length.should.eql(cats.length); done(); }); }); }); }); it('Update with range key', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat2({ownerId: 20+i, name: 'Tom_'+i})); } Cat2.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); for (var i=0 ; i<10 ; ++i) { var cat = cats[i]; cat.name = 'John_' + (cat.ownerId + 100); } Cat2.batchPut(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); Cat2.batchGet(cats, function (err3, result3) { should.not.exist(err3); should.exist(result3); result3.length.should.eql(cats.length); done(); }); }); }); }); it('Update without range key', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat2({ownerId: 20+i, name: 'Tom_'+i})); } Cat2.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); for (var i=0 ; i<10 ; ++i) { cats[i].name = null; } Cat2.batchPut(cats, function (err2, result2) { should.exist(err2); should.not.exist(result2); done(); }); }); }); }); describe('Model.batchDelete', function (){ it('Simple delete', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat({id: 30+i, name: 'Tom_'+i})); } Cat.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); Cat.batchDelete(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); Cat.batchGet(cats, function (err3, result3) { should.not.exist(err3); should.exist(result3); result3.length.should.eql(0); done(); }); }); }); }); it('Delete with range key', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat2({ownerId: 30+i, name: 'Tom_'+i})); } Cat2.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); Cat2.batchDelete(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); Cat2.batchGet(cats, function (err3, result3) { should.not.exist(err3); should.exist(result3); result3.length.should.eql(0); done(); }); }); }); }); it('Delete without range key', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat2({ownerId: 30+i, name: 'Tom_'+i})); } Cat2.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); for (var i=0 ; i<10 ; ++i) { delete cats[i].name; } Cat2.batchDelete(cats, function (err2, result2) { should.exist(err2); should.not.exist(result2); done(); }); }); }); }); });
benjcooley/dynamoose
test/Model.js
JavaScript
mit
21,235
import _curry3 from './internal/_curry3.js'; /** * Move an item, at index `from`, to index `to`, in a list of elements. * A new list will be created containing the new elements order. * * @func * @memberOf R * @since v0.27.1 * @category List * @sig Number -> Number -> [a] -> [a] * @param {Number} from The source index * @param {Number} to The destination index * @param {Array} list The list which will serve to realise the move * @return {Array} The new list reordered * @example * * R.move(0, 2, ['a', 'b', 'c', 'd', 'e', 'f']); //=> ['b', 'c', 'a', 'd', 'e', 'f'] * R.move(-1, 0, ['a', 'b', 'c', 'd', 'e', 'f']); //=> ['f', 'a', 'b', 'c', 'd', 'e'] list rotation */ var move = _curry3(function(from, to, list) { var length = list.length; var result = list.slice(); var positiveFrom = from < 0 ? length + from : from; var positiveTo = to < 0 ? length + to : to; var item = result.splice(positiveFrom, 1); return positiveFrom < 0 || positiveFrom >= list.length || positiveTo < 0 || positiveTo >= list.length ? list : [] .concat(result.slice(0, positiveTo)) .concat(item) .concat(result.slice(positiveTo, list.length)); }); export default move;
CrossEye/ramda
source/move.js
JavaScript
mit
1,225
/** @type {import("../../../../").Configuration} */ module.exports = { entry: { a: "./a", b: "./b" }, output: { filename: "[name].js", libraryTarget: "commonjs2" }, optimization: { chunkIds: "named", splitChunks: { cacheGroups: { shared: { chunks: "all", test: /shared/, filename: "shared-[name].js", enforce: true }, common: { chunks: "all", test: /common/, enforce: true } } } } };
webpack/webpack
test/configCases/split-chunks/custom-filename/webpack.config.js
JavaScript
mit
461
(function () { 'use strict'; angular.module('mPlatform.directives') .directive('ngTextChange', function () { return { restrict: 'A', replace: 'ngModel', link: function (scope, element, attr) { element.on('change', function () { scope.$apply(function () { scope.$eval(attr.ngTextChange); }); }); } }; }); })();
michaelmarriott/LabyrinthRipper.Mobile
www/scripts/ang/directives.js
JavaScript
mit
540
Astro.createValidator = function(validatorDefinition) { var definition = new ValidatorDefinition(validatorDefinition); var validatorGenerator = function(options, userMessage) { var validator = function(fieldValue, fieldName) { return validator.definition.validate.call( this, fieldValue, fieldName, options, // Validator options passed by user. validator // Parent validator. ); }; _.extend(validator, { definition: definition, options: options, message: userMessage }); return validator; }; // Validator is just a function with the "definition" property where all the // validator definition is stored. Validators[definition.name] = validatorGenerator; // We also return created validator if someone would like not to use long // default namespace which is e.g. `Validators.isString`. return validatorGenerator; };
ribbedcrown/meteor-astronomy-validators
lib/module/validator.js
JavaScript
mit
929
import _Object$getOwnPropertySymbols from "../../core-js/object/get-own-property-symbols"; import _Object$keys from "../../core-js/object/keys"; export default function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = _Object$keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } if (_Object$getOwnPropertySymbols) { var sourceSymbolKeys = _Object$getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
Skillupco/babel
packages/babel-runtime/helpers/es6/objectWithoutProperties.js
JavaScript
mit
854
import test from 'ava'; import fn from './'; test('title', t => { t.is(fn('unicorns'), 'unicorns & rainbows'); });
kokujin/sails-nedb
test.js
JavaScript
mit
117
'use strict'; import $ from 'jquery'; import { Keyboard } from './foundation.util.keyboard'; import { GetYoDigits } from './foundation.util.core'; import { Positionable } from './foundation.positionable'; import { Triggers } from './foundation.util.triggers'; /** * Dropdown module. * @module foundation.dropdown * @requires foundation.util.keyboard * @requires foundation.util.box * @requires foundation.util.triggers */ class Dropdown extends Positionable { /** * Creates a new instance of a dropdown. * @class * @name Dropdown * @param {jQuery} element - jQuery object to make into a dropdown. * Object should be of the dropdown panel, rather than its anchor. * @param {Object} options - Overrides to the default plugin settings. */ _setup(element, options) { this.$element = element; this.options = $.extend({}, Dropdown.defaults, this.$element.data(), options); this.className = 'Dropdown'; // ie9 back compat // Triggers init is idempotent, just need to make sure it is initialized Triggers.init($); this._init(); Keyboard.register('Dropdown', { 'ENTER': 'open', 'SPACE': 'open', 'ESCAPE': 'close' }); } /** * Initializes the plugin by setting/checking options and attributes, adding helper variables, and saving the anchor. * @function * @private */ _init() { var $id = this.$element.attr('id'); this.$anchors = $(`[data-toggle="${$id}"]`).length ? $(`[data-toggle="${$id}"]`) : $(`[data-open="${$id}"]`); this.$anchors.attr({ 'aria-controls': $id, 'data-is-focus': false, 'data-yeti-box': $id, 'aria-haspopup': true, 'aria-expanded': false }); this._setCurrentAnchor(this.$anchors.first()); if(this.options.parentClass){ this.$parent = this.$element.parents('.' + this.options.parentClass); }else{ this.$parent = null; } this.$element.attr({ 'aria-hidden': 'true', 'data-yeti-box': $id, 'data-resize': $id, 'aria-labelledby': this.$currentAnchor.id || GetYoDigits(6, 'dd-anchor') }); super._init(); this._events(); } _getDefaultPosition() { // handle legacy classnames var position = this.$element[0].className.match(/(top|left|right|bottom)/g); if(position) { return position[0]; } else { return 'bottom' } } _getDefaultAlignment() { // handle legacy float approach var horizontalPosition = /float-(\S+)/.exec(this.$currentAnchor.className); if(horizontalPosition) { return horizontalPosition[1]; } return super._getDefaultAlignment(); } /** * Sets the position and orientation of the dropdown pane, checks for collisions if allow-overlap is not true. * Recursively calls itself if a collision is detected, with a new position class. * @function * @private */ _setPosition() { this.$element.removeClass(`has-position-${this.position} has-alignment-${this.alignment}`); super._setPosition(this.$currentAnchor, this.$element, this.$parent); this.$element.addClass(`has-position-${this.position} has-alignment-${this.alignment}`); } /** * Make it a current anchor. * Current anchor as the reference for the position of Dropdown panes. * @param {HTML} el - DOM element of the anchor. * @function * @private */ _setCurrentAnchor(el) { this.$currentAnchor = $(el); } /** * Adds event listeners to the element utilizing the triggers utility library. * @function * @private */ _events() { var _this = this; this.$element.on({ 'open.zf.trigger': this.open.bind(this), 'close.zf.trigger': this.close.bind(this), 'toggle.zf.trigger': this.toggle.bind(this), 'resizeme.zf.trigger': this._setPosition.bind(this) }); this.$anchors.off('click.zf.trigger') .on('click.zf.trigger', function() { _this._setCurrentAnchor(this); }); if(this.options.hover){ this.$anchors.off('mouseenter.zf.dropdown mouseleave.zf.dropdown') .on('mouseenter.zf.dropdown', function(){ _this._setCurrentAnchor(this); var bodyData = $('body').data(); if(typeof(bodyData.whatinput) === 'undefined' || bodyData.whatinput === 'mouse') { clearTimeout(_this.timeout); _this.timeout = setTimeout(function(){ _this.open(); _this.$anchors.data('hover', true); }, _this.options.hoverDelay); } }).on('mouseleave.zf.dropdown', function(){ clearTimeout(_this.timeout); _this.timeout = setTimeout(function(){ _this.close(); _this.$anchors.data('hover', false); }, _this.options.hoverDelay); }); if(this.options.hoverPane){ this.$element.off('mouseenter.zf.dropdown mouseleave.zf.dropdown') .on('mouseenter.zf.dropdown', function(){ clearTimeout(_this.timeout); }).on('mouseleave.zf.dropdown', function(){ clearTimeout(_this.timeout); _this.timeout = setTimeout(function(){ _this.close(); _this.$anchors.data('hover', false); }, _this.options.hoverDelay); }); } } this.$anchors.add(this.$element).on('keydown.zf.dropdown', function(e) { var $target = $(this), visibleFocusableElements = Keyboard.findFocusable(_this.$element); Keyboard.handleKey(e, 'Dropdown', { open: function() { if ($target.is(_this.$anchors)) { _this.open(); _this.$element.attr('tabindex', -1).focus(); e.preventDefault(); } }, close: function() { _this.close(); _this.$anchors.focus(); } }); }); } /** * Adds an event handler to the body to close any dropdowns on a click. * @function * @private */ _addBodyHandler() { var $body = $(document.body).not(this.$element), _this = this; $body.off('click.zf.dropdown') .on('click.zf.dropdown', function(e){ if(_this.$anchors.is(e.target) || _this.$anchors.find(e.target).length) { return; } if(_this.$element.is(e.target) || _this.$element.find(e.target).length) { return; } _this.close(); $body.off('click.zf.dropdown'); }); } /** * Opens the dropdown pane, and fires a bubbling event to close other dropdowns. * @function * @fires Dropdown#closeme * @fires Dropdown#show */ open() { // var _this = this; /** * Fires to close other open dropdowns, typically when dropdown is opening * @event Dropdown#closeme */ this.$element.trigger('closeme.zf.dropdown', this.$element.attr('id')); this.$anchors.addClass('hover') .attr({'aria-expanded': true}); // this.$element/*.show()*/; this.$element.addClass('is-opening'); this._setPosition(); this.$element.removeClass('is-opening').addClass('is-open') .attr({'aria-hidden': false}); if(this.options.autoFocus){ var $focusable = Keyboard.findFocusable(this.$element); if($focusable.length){ $focusable.eq(0).focus(); } } if(this.options.closeOnClick){ this._addBodyHandler(); } if (this.options.trapFocus) { Keyboard.trapFocus(this.$element); } /** * Fires once the dropdown is visible. * @event Dropdown#show */ this.$element.trigger('show.zf.dropdown', [this.$element]); } /** * Closes the open dropdown pane. * @function * @fires Dropdown#hide */ close() { if(!this.$element.hasClass('is-open')){ return false; } this.$element.removeClass('is-open') .attr({'aria-hidden': true}); this.$anchors.removeClass('hover') .attr('aria-expanded', false); /** * Fires once the dropdown is no longer visible. * @event Dropdown#hide */ this.$element.trigger('hide.zf.dropdown', [this.$element]); if (this.options.trapFocus) { Keyboard.releaseFocus(this.$element); } } /** * Toggles the dropdown pane's visibility. * @function */ toggle() { if(this.$element.hasClass('is-open')){ if(this.$anchors.data('hover')) return; this.close(); }else{ this.open(); } } /** * Destroys the dropdown. * @function */ _destroy() { this.$element.off('.zf.trigger').hide(); this.$anchors.off('.zf.dropdown'); $(document.body).off('click.zf.dropdown'); } } Dropdown.defaults = { /** * Class that designates bounding container of Dropdown (default: window) * @option * @type {?string} * @default null */ parentClass: null, /** * Amount of time to delay opening a submenu on hover event. * @option * @type {number} * @default 250 */ hoverDelay: 250, /** * Allow submenus to open on hover events * @option * @type {boolean} * @default false */ hover: false, /** * Don't close dropdown when hovering over dropdown pane * @option * @type {boolean} * @default false */ hoverPane: false, /** * Number of pixels between the dropdown pane and the triggering element on open. * @option * @type {number} * @default 0 */ vOffset: 0, /** * Number of pixels between the dropdown pane and the triggering element on open. * @option * @type {number} * @default 0 */ hOffset: 0, /** * DEPRECATED: Class applied to adjust open position. * @option * @type {string} * @default '' */ positionClass: '', /** * Position of dropdown. Can be left, right, bottom, top, or auto. * @option * @type {string} * @default 'auto' */ position: 'auto', /** * Alignment of dropdown relative to anchor. Can be left, right, bottom, top, center, or auto. * @option * @type {string} * @default 'auto' */ alignment: 'auto', /** * Allow overlap of container/window. If false, dropdown will first try to position as defined by data-position and data-alignment, but reposition if it would cause an overflow. * @option * @type {boolean} * @default false */ allowOverlap: false, /** * Allow overlap of only the bottom of the container. This is the most common * behavior for dropdowns, allowing the dropdown to extend the bottom of the * screen but not otherwise influence or break out of the container. * @option * @type {boolean} * @default true */ allowBottomOverlap: true, /** * Allow the plugin to trap focus to the dropdown pane if opened with keyboard commands. * @option * @type {boolean} * @default false */ trapFocus: false, /** * Allow the plugin to set focus to the first focusable element within the pane, regardless of method of opening. * @option * @type {boolean} * @default false */ autoFocus: false, /** * Allows a click on the body to close the dropdown. * @option * @type {boolean} * @default false */ closeOnClick: false } export {Dropdown};
robertgraleigh/supreme-journey
node_modules/foundation-sites/js/foundation.dropdown.js
JavaScript
mit
11,158
// import { createAction } from 'redux-actions'; //Actions: //Simulate loading
dgilroy77/Car.ly
src/actions/loadActions.js
JavaScript
mit
80
'use strict'; const common = require('../common'); if (!common.hasIPv6) common.skip('no IPv6 support'); const assert = require('assert'); const cluster = require('cluster'); const net = require('net'); // This test ensures that the `ipv6Only` option in `net.Server.listen()` // works as expected when we use cluster with `SCHED_RR` schedulingPolicy. cluster.schedulingPolicy = cluster.SCHED_RR; const host = '::'; const WORKER_ACCOUNT = 3; if (cluster.isMaster) { const workers = []; let address; for (let i = 0; i < WORKER_ACCOUNT; i += 1) { const myWorker = new Promise((resolve) => { const worker = cluster.fork().on('exit', common.mustCall((statusCode) => { assert.strictEqual(statusCode, 0); })).on('listening', common.mustCall((workerAddress) => { if (!address) { address = workerAddress; } else { assert.deepStrictEqual(workerAddress, address); } resolve(worker); })); }); workers.push(myWorker); } Promise.all(workers).then(common.mustCall((resolvedWorkers) => { // Make sure the `ipv6Only` option works. Should be able to use the port on // IPv4. const server = net.createServer().listen({ host: '0.0.0.0', port: address.port, }, common.mustCall(() => { // Exit. server.close(); resolvedWorkers.forEach((resolvedWorker) => { resolvedWorker.disconnect(); }); })); })); } else { // As the cluster member has the potential to grab any port // from the environment, this can cause collision when master // obtains the port from cluster member and tries to listen on. // So move this to sequential, and provide a static port. // Refs: https://github.com/nodejs/node/issues/25813 net.createServer().listen({ host: host, port: common.PORT, ipv6Only: true, }, common.mustCall()); }
enclose-io/compiler
lts/test/sequential/test-cluster-net-listen-ipv6only-rr.js
JavaScript
mit
1,884
import Vue from 'vue'; import closedComponent from '~/vue_merge_request_widget/components/states/mr_widget_closed.vue'; import mountComponent from 'spec/helpers/vue_mount_component_helper'; describe('MRWidgetClosed', () => { let vm; beforeEach(() => { const Component = Vue.extend(closedComponent); vm = mountComponent(Component, { mr: { metrics: { mergedBy: {}, closedBy: { name: 'Administrator', username: 'root', webUrl: 'http://localhost:3000/root', avatarUrl: 'http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon', }, mergedAt: 'Jan 24, 2018 1:02pm GMT+0000', closedAt: 'Jan 24, 2018 1:02pm GMT+0000', readableMergedAt: '', readableClosedAt: 'less than a minute ago', }, targetBranchPath: '/twitter/flight/commits/so_long_jquery', targetBranch: 'so_long_jquery', }, }); }); afterEach(() => { vm.$destroy(); }); it('renders warning icon', () => { expect(vm.$el.querySelector('.js-ci-status-icon-warning')).not.toBeNull(); }); it('renders closed by information with author and time', () => { expect( vm.$el .querySelector('.js-mr-widget-author') .textContent.trim() .replace(/\s\s+/g, ' '), ).toContain('Closed by Administrator less than a minute ago'); }); it('links to the user that closed the MR', () => { expect(vm.$el.querySelector('.author-link').getAttribute('href')).toEqual( 'http://localhost:3000/root', ); }); it('renders information about the changes not being merged', () => { expect( vm.$el .querySelector('.mr-info-list') .textContent.trim() .replace(/\s\s+/g, ' '), ).toContain('The changes were not merged into so_long_jquery'); }); it('renders link for target branch', () => { expect(vm.$el.querySelector('.label-branch').getAttribute('href')).toEqual( '/twitter/flight/commits/so_long_jquery', ); }); });
stoplightio/gitlabhq
spec/javascripts/vue_mr_widget/components/states/mr_widget_closed_spec.js
JavaScript
mit
2,094
'use strict'; import React from 'react'; import PlaylistHeader from './PlaylistHeader'; import PlaylistVideos from './PlaylistVideos'; const PureRenderMixin = React.addons.PureRenderMixin; export default React.createClass({ propTypes: { playlist: React.PropTypes.array.isRequired, }, mixins: [PureRenderMixin], renderPlaylists(playlist){ return ( <div key={playlist.get('id')} className="playlist-items"> <PlaylistHeader title={playlist.get('title')} playlist={playlist.get('id')} /> <PlaylistVideos videos={playlist.get('videos')} /> </div> ); }, render() { let nodes = this.props.playlist.map(this.renderPlaylists); return ( <div className="playlist-items-container"> {nodes} </div> ); } });
whoisandie/yoda
src/scripts/Playlist.js
JavaScript
mit
785
'use strict'; /* global google */ function cdDojoDetailCtrl($scope, $state, $location, cdDojoService, cdUsersService, alertService, usSpinnerService, auth, dojo, gmap, $translate, currentUser) { $scope.dojo = dojo; $scope.model = {}; $scope.markers = []; $scope.requestInvite = {}; $scope.userMemberCheckComplete = false; currentUser = currentUser.data; var approvalRequired = ['mentor', 'champion']; var latitude, longitude; if(!_.isEmpty(currentUser)) { if(!dojo || !dojo.id){ return $state.go('error-404-no-headers'); } if(!dojo.verified && dojo.creator !== currentUser.id && !_.contains(currentUser.roles, 'cdf-admin')){ return $state.go('error-404-no-headers'); } //Check if user is a member of this Dojo var query = {dojoId:dojo.id, userId: currentUser.id}; cdDojoService.getUsersDojos(query, function (response) { $scope.dojoMember = !_.isEmpty(response); $scope.dojoOwner = false; if($scope.dojoMember) $scope.dojoOwner = (response[0].owner === 1) ? true : false; $scope.userMemberCheckComplete = true; }); } else { if(!dojo || !dojo.id || !dojo.verified) return $state.go('error-404-no-headers'); $scope.userMemberCheckComplete = true; } cdUsersService.getInitUserTypes(function (response) { var userTypes = _.filter(response, function(type) { return type.name.indexOf('u13') === -1; }); $scope.initUserTypes = userTypes; }); cdDojoService.getDojoConfig(function(json){ $scope.dojoStages = _.map(json.dojoStages, function(item){ return { value: item.value, label: $translate.instant(item.label) }; }); $scope.dojo.stage = _.find($scope.dojoStages, function(obj) { return obj.value === $scope.dojo.stage }) }); $scope.$watch('model.map', function(map){ if(map) { if(latitude && longitude) { var marker = new google.maps.Marker({ map: $scope.model.map, position: new google.maps.LatLng(latitude, longitude) }); $scope.markers.push(marker); } } }); if(gmap) { if($scope.dojo.coordinates) { var coordinates = $scope.dojo.coordinates.split(','); latitude = coordinates[0]; longitude = coordinates[1]; $scope.mapOptions = { center: new google.maps.LatLng(latitude, longitude), zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP }; $scope.mapLoaded = true; } else { var countryCoordinates; cdDojoService.loadCountriesLatLongData(function (response) { countryCoordinates = response[$scope.dojo.alpha2]; $scope.mapOptions = { center: new google.maps.LatLng(countryCoordinates[0], countryCoordinates[1]), zoom: 5, mapTypeId: google.maps.MapTypeId.ROADMAP }; $scope.mapLoaded = true; }); } } $scope.userTypeSelected = function ($item) { if(_.contains(approvalRequired, $item)) return $scope.approvalRequired = true; return $scope.approvalRequired = false; }; $scope.requestToJoin = function (requestInvite) { if(!$scope.requestInvite.userType) { $scope.requestInvite.validate="false"; return } else { var userType = requestInvite.userType.name; auth.get_loggedin_user(function (user) { usSpinnerService.spin('dojo-detail-spinner'); var data = {user:user, dojoId:dojo.id, userType:userType, emailSubject: $translate.instant('New Request to join your Dojo')}; if(_.contains(approvalRequired, userType)) { cdDojoService.requestInvite(data, function (response) { usSpinnerService.stop('dojo-detail-spinner'); if(!response.error) { alertService.showAlert($translate.instant('Join Request Sent!')); } else { alertService.showError($translate.instant(response.error)); } }); } else { //Check if user is already a member of this Dojo var query = {userId:user.id, dojoId:dojo.id}; var userDojo = {}; cdDojoService.getUsersDojos(query, function (response) { if(_.isEmpty(response)) { //Save userDojo.owner = 0; userDojo.userId = user.id; userDojo.dojoId = dojo.id; userDojo.userTypes = [userType]; cdDojoService.saveUsersDojos(userDojo, function (response) { usSpinnerService.stop('dojo-detail-spinner'); $state.go($state.current, {}, {reload: true}); alertService.showAlert($translate.instant('Successfully Joined Dojo')); }); } else { //Update userDojo = response[0]; if(!userDojo.userTypes) userDojo.userTypes = []; userDojo.userTypes.push(userType); cdDojoService.saveUsersDojos(userDojo, function (response) { usSpinnerService.stop('dojo-detail-spinner'); $state.go($state.current, {}, {reload: true}); alertService.showAlert($translate.instant('Successfully Joined Dojo')); }); } }); } }, function () { //Not logged in $state.go('register-account', {referer:$location.url()}); }); } }; $scope.leaveDojo = function () { usSpinnerService.spin('dojo-detail-spinner'); cdDojoService.removeUsersDojosLink({userId: currentUser.id, dojoId: dojo.id, emailSubject: $translate.instant('A user has left your Dojo')}, function (response) { usSpinnerService.stop('dojo-detail-spinner'); $state.go($state.current, {}, {reload: true}); }, function (err) { alertService.showError($translate.instant('Error leaving Dojo')); }); } } angular.module('cpZenPlatform') .controller('dojo-detail-controller', ['$scope', '$state', '$location', 'cdDojoService', 'cdUsersService', 'alertService', 'usSpinnerService', 'auth', 'dojo', 'gmap', '$translate', 'currentUser', cdDojoDetailCtrl]);
Aryess/cp-zen-platform
web/public/js/controllers/dojo-detail-controller.js
JavaScript
mit
6,054
#!/usr/bin/env node const os = require('os') const {spawn} = require('child_process') if (os.platform() === 'win32' || os.platform() === 'windows') console.log('skipping on windows') else spawn('yarn bats test/integration/*.bats', {stdio: 'inherit', shell: true})
heroku/heroku-cli
packages/run/bin/bats-test-runner.js
JavaScript
mit
266
var searchData= [ ['label',['Label',['../classLabel.html',1,'']]], ['labeliterator',['LabelIterator',['../classLabelIterator.html',1,'']]], ['labelsegment',['LabelSegment',['../structLabelSegment.html',1,'']]] ];
chabbimilind/cctlib
docs/html/search/classes_6c.js
JavaScript
mit
219
/**! * Sortable * @author RubaXa <[email protected]> * @author owenm <[email protected]> * @license MIT */ (function sortableModule(factory) { "use strict"; if (typeof define === "function" && define.amd) { define(factory); } else if (typeof module != "undefined" && typeof module.exports != "undefined") { module.exports = factory(); } else { /* jshint sub:true */ window["Sortable"] = factory(); } })(function sortableFactory() { "use strict"; if (typeof window === "undefined" || !window.document) { return function sortableError() { throw new Error("Sortable.js requires a window with a document"); }; } var dragEl, parentEl, ghostEl, cloneEl, rootEl, nextEl, lastDownEl, scrollEl, scrollParentEl, scrollCustomFn, oldIndex, newIndex, activeGroup, putSortable, autoScrolls = [], scrolling = false, pointerElemChangedInterval, lastPointerElemX, lastPointerElemY, tapEvt, touchEvt, moved, lastTarget, lastDirection, pastFirstInvertThresh = false, isCircumstantialInvert = false, forRepaintDummy, realDragElRect, // dragEl rect after current animation /** @const */ R_SPACE = /\s+/g, expando = 'Sortable' + (new Date).getTime(), win = window, document = win.document, parseInt = win.parseInt, setTimeout = win.setTimeout, $ = win.jQuery || win.Zepto, Polymer = win.Polymer, captureMode = { capture: false, passive: false }, supportDraggable = ('draggable' in document.createElement('div')), supportCssPointerEvents = (function (el) { // false when IE11 if (!!navigator.userAgent.match(/(?:Trident.*rv[ :]?11\.|msie)/i)) { return false; } el = document.createElement('x'); el.style.cssText = 'pointer-events:auto'; return el.style.pointerEvents === 'auto'; })(), _silent = false, _alignedSilent = false, abs = Math.abs, min = Math.min, savedInputChecked = [], touchDragOverListeners = [], alwaysFalse = function () { return false; }, _detectDirection = function(el, options) { var elCSS = _css(el), elWidth = parseInt(elCSS.width), child1 = _getChild(el, 0, options), child2 = _getChild(el, 1, options), firstChildCSS = child1 && _css(child1), secondChildCSS = child2 && _css(child2), firstChildWidth = firstChildCSS && parseInt(firstChildCSS.marginLeft) + parseInt(firstChildCSS.marginRight) + child1.getBoundingClientRect().width, secondChildWidth = secondChildCSS && parseInt(secondChildCSS.marginLeft) + parseInt(secondChildCSS.marginRight) + child2.getBoundingClientRect().width ; if (elCSS.display === 'flex') { return elCSS.flexDirection === 'column' || elCSS.flexDirection === 'column-reverse' ? 'vertical' : 'horizontal'; } return (child1 && ( firstChildCSS.display === 'block' || firstChildCSS.display === 'grid' || firstChildWidth >= elWidth && elCSS.float === 'none' || child2 && elCSS.float === 'none' && firstChildWidth + secondChildWidth > elWidth ) ? 'vertical' : 'horizontal' ); }, _isInRowColumn = function(x, y, el, axis, options) { var targetRect = realDragElRect || dragEl.getBoundingClientRect(), targetS1Opp = axis === 'vertical' ? targetRect.left : targetRect.top, targetS2Opp = axis === 'vertical' ? targetRect.right : targetRect.bottom, mouseOnOppAxis = axis === 'vertical' ? x : y ; return targetS1Opp < mouseOnOppAxis && mouseOnOppAxis < targetS2Opp; }, _getParentAutoScrollElement = function(el, includeSelf) { // skip to window if (!el || !el.getBoundingClientRect) return win; var elem = el; var gotSelf = false; do { // we don't need to get elem css if it isn't even overflowing in the first place (performance) if (elem.clientWidth < elem.scrollWidth || elem.clientHeight < elem.scrollHeight) { var elemCSS = _css(elem); if ( elem.clientWidth < elem.scrollWidth && (elemCSS.overflowX == 'auto' || elemCSS.overflowX == 'scroll') || elem.clientHeight < elem.scrollHeight && (elemCSS.overflowY == 'auto' || elemCSS.overflowY == 'scroll') ) { if (!elem || !elem.getBoundingClientRect || elem === document.body) return win; if (gotSelf || includeSelf) return elem; gotSelf = true; } } /* jshint boss:true */ } while (elem = elem.parentNode); return win; }, _autoScroll = _throttle(function (/**Event*/evt, /**Object*/options, /**HTMLElement*/rootEl, /**Boolean*/isFallback) { // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521 if (options.scroll) { var _this = rootEl ? rootEl[expando] : window, rect, css, sens = options.scrollSensitivity, speed = options.scrollSpeed, x = evt.clientX, y = evt.clientY, winWidth = window.innerWidth, winHeight = window.innerHeight, vx, vy, scrollThisInstance = false ; // Detect scrollEl if (scrollParentEl !== rootEl) { _clearAutoScrolls(); scrollEl = options.scroll; scrollCustomFn = options.scrollFn; if (scrollEl === true) { scrollEl = _getParentAutoScrollElement(rootEl, true); scrollParentEl = scrollEl; } } var layersOut = 0; var currentParent = scrollEl; do { var el; if (currentParent && currentParent !== win) { el = currentParent; css = _css(el); rect = currentParent.getBoundingClientRect(); vx = el.clientWidth < el.scrollWidth && (css.overflowX == 'auto' || css.overflowX == 'scroll') && ((abs(rect.right - x) <= sens) - (abs(rect.left - x) <= sens)); vy = el.clientHeight < el.scrollHeight && (css.overflowY == 'auto' || css.overflowY == 'scroll') && ((abs(rect.bottom - y) <= sens) - (abs(rect.top - y) <= sens)); } else if (currentParent === win) { el = win; vx = (winWidth - x <= sens) - (x <= sens); vy = (winHeight - y <= sens) - (y <= sens); } if (!autoScrolls[layersOut]) { for (var i = 0; i <= layersOut; i++) { if (!autoScrolls[i]) { autoScrolls[i] = {}; } } } if (autoScrolls[layersOut].vx != vx || autoScrolls[layersOut].vy != vy || autoScrolls[layersOut].el !== el) { autoScrolls[layersOut].el = el; autoScrolls[layersOut].vx = vx; autoScrolls[layersOut].vy = vy; clearInterval(autoScrolls[layersOut].pid); if (el && (vx != 0 || vy != 0)) { scrollThisInstance = true; /* jshint loopfunc:true */ autoScrolls[layersOut].pid = setInterval((function () { // emulate drag over during autoscroll (fallback), emulating native DnD behaviour if (isFallback && this.layer === 0) { Sortable.active._emulateDragOver(true); } var scrollOffsetY = autoScrolls[this.layer].vy ? autoScrolls[this.layer].vy * speed : 0; var scrollOffsetX = autoScrolls[this.layer].vx ? autoScrolls[this.layer].vx * speed : 0; if ('function' === typeof(scrollCustomFn)) { if (scrollCustomFn.call(_this, scrollOffsetX, scrollOffsetY, evt, touchEvt, autoScrolls[this.layer].el) !== 'continue') { return; } } if (autoScrolls[this.layer].el === win) { win.scrollTo(win.pageXOffset + scrollOffsetX, win.pageYOffset + scrollOffsetY); } else { autoScrolls[this.layer].el.scrollTop += scrollOffsetY; autoScrolls[this.layer].el.scrollLeft += scrollOffsetX; } }).bind({layer: layersOut}), 24); } } layersOut++; } while (options.bubbleScroll && currentParent !== win && (currentParent = _getParentAutoScrollElement(currentParent, false))); scrolling = scrollThisInstance; // in case another function catches scrolling as false in between when it is not } }, 30), _clearAutoScrolls = function () { autoScrolls.forEach(function(autoScroll) { clearInterval(autoScroll.pid); }); autoScrolls = []; }, _prepareGroup = function (options) { function toFn(value, pull) { return function(to, from, dragEl, evt) { var ret; if (value == null && pull) { ret = true; // default pull value: true (backwards compatibility) } else if (value == null || value === false) { ret = false; } else if (pull && value === 'clone') { ret = value; } else if (typeof value === 'function') { ret = value(to, from, dragEl, evt); } else { var otherGroup = (pull ? to : from).options.group.name; ret = (value === true || (typeof value === 'string' && value === otherGroup) || (value.join && value.indexOf(otherGroup) > -1)); } return ret || (to.options.group.name && from.options.group.name && to.options.group.name === from.options.group.name); }; } var group = {}; var originalGroup = options.group; if (!originalGroup || typeof originalGroup != 'object') { originalGroup = {name: originalGroup}; } group.name = originalGroup.name; group.checkPull = toFn(originalGroup.pull, true); group.checkPut = toFn(originalGroup.put); group.revertClone = originalGroup.revertClone; options.group = group; }, _checkAlignment = function(evt) { if (!dragEl) return; dragEl.parentNode[expando] && dragEl.parentNode[expando]._computeIsAligned(evt); } ; /** * @class Sortable * @param {HTMLElement} el * @param {Object} [options] */ function Sortable(el, options) { if (!(el && el.nodeType && el.nodeType === 1)) { throw 'Sortable: `el` must be HTMLElement, and not ' + {}.toString.call(el); } this.el = el; // root element this.options = options = _extend({}, options); // Export instance el[expando] = this; // Default options var defaults = { group: null, sort: true, disabled: false, store: null, handle: null, scroll: true, scrollSensitivity: 30, scrollSpeed: 10, bubbleScroll: true, draggable: /[uo]l/i.test(el.nodeName) ? 'li' : '>*', swapThreshold: 1, // percentage; 0 <= x <= 1 invertSwap: false, // invert always invertedSwapThreshold: null, // will be set to same as swapThreshold if default ghostClass: 'sortable-ghost', chosenClass: 'sortable-chosen', dragClass: 'sortable-drag', ignore: 'a, img', filter: null, preventOnFilter: true, animation: 0, setData: function (dataTransfer, dragEl) { dataTransfer.setData('Text', dragEl.textContent); }, dropBubble: false, dragoverBubble: false, dataIdAttr: 'data-id', delay: 0, touchStartThreshold: parseInt(window.devicePixelRatio, 10) || 1, forceFallback: false, fallbackClass: 'sortable-fallback', fallbackOnBody: false, fallbackTolerance: 0, fallbackOffset: {x: 0, y: 0}, supportPointer: Sortable.supportPointer !== false && ( ('PointerEvent' in window) || window.navigator && ('msPointerEnabled' in window.navigator) // microsoft ) }; // Set default options for (var name in defaults) { !(name in options) && (options[name] = defaults[name]); } if (!('direction' in options)) { options.direction = function() { return _detectDirection(el, options); }; } _prepareGroup(options); options.invertedSwapThreshold == null && (options.invertedSwapThreshold = options.swapThreshold); // Bind all private methods for (var fn in this) { if (fn.charAt(0) === '_' && typeof this[fn] === 'function') { this[fn] = this[fn].bind(this); } } // Setup drag mode this.nativeDraggable = options.forceFallback ? false : supportDraggable; // Bind events _on(el, 'mousedown', this._onTapStart); _on(el, 'touchstart', this._onTapStart); options.supportPointer && _on(el, 'pointerdown', this._onTapStart); if (this.nativeDraggable) { _on(el, 'dragover', this); _on(el, 'dragenter', this); } touchDragOverListeners.push(this._onDragOver); // Restore sorting options.store && options.store.get && this.sort(options.store.get(this) || []); } Sortable.prototype = /** @lends Sortable.prototype */ { constructor: Sortable, // is mouse aligned with dragEl? _isAligned: true, _computeIsAligned: function(evt, isDragEl) { if (_alignedSilent) return; if (!dragEl || dragEl.parentNode !== this.el) return; if (isDragEl !== true && isDragEl !== false) { isDragEl = !!_closest(evt.target, null, dragEl, true); } this._isAligned = !scrolling && (isDragEl || this._isAligned && _isInRowColumn(evt.clientX, evt.clientY, this.el, this._getDirection(evt, null), this.options)); _alignedSilent = true; setTimeout(function() { _alignedSilent = false; }, 30); }, _getDirection: function(evt, target) { return (typeof this.options.direction === 'function') ? this.options.direction.call(this, evt, target, dragEl) : this.options.direction; }, _onTapStart: function (/** Event|TouchEvent */evt) { var _this = this, el = this.el, options = this.options, preventOnFilter = options.preventOnFilter, type = evt.type, touch = evt.touches && evt.touches[0], target = (touch || evt).target, originalTarget = evt.target.shadowRoot && ((evt.path && evt.path[0]) || (evt.composedPath && evt.composedPath()[0])) || target, filter = options.filter, startIndex; _saveInputCheckedState(el); // Don't trigger start event when an element is been dragged, otherwise the evt.oldindex always wrong when set option.group. if (dragEl) { return; } if (/mousedown|pointerdown/.test(type) && evt.button !== 0 || options.disabled) { return; // only left button or enabled } // cancel dnd if original target is content editable if (originalTarget.isContentEditable) { return; } target = _closest(target, options.draggable, el, true); if (!target) { return; } if (lastDownEl === target) { // Ignoring duplicate `down` return; } // Get the index of the dragged element within its parent startIndex = _index(target, options.draggable); // Check filter if (typeof filter === 'function') { if (filter.call(this, evt, target, this)) { _dispatchEvent(_this, originalTarget, 'filter', target, el, el, startIndex); preventOnFilter && evt.cancelable && evt.preventDefault(); return; // cancel dnd } } else if (filter) { filter = filter.split(',').some(function (criteria) { criteria = _closest(originalTarget, criteria.trim(), el, false); if (criteria) { _dispatchEvent(_this, criteria, 'filter', target, el, el, startIndex); return true; } }); if (filter) { preventOnFilter && evt.cancelable && evt.preventDefault(); return; // cancel dnd } } if (options.handle && !_closest(originalTarget, options.handle, el, false)) { return; } // Prepare `dragstart` this._prepareDragStart(evt, touch, target, startIndex); }, _handleAutoScroll: function(evt, fallback) { if (!dragEl || !this.options.scroll) return; var x = evt.clientX, y = evt.clientY, elem = document.elementFromPoint(x, y), _this = this ; // firefox does not have native autoscroll if (fallback || (window.navigator && window.navigator.userAgent.toLowerCase().indexOf('firefox') > -1)) { _autoScroll(evt, _this.options, elem, true); // Listener for pointer element change var ogElemScroller = _getParentAutoScrollElement(elem, true); if ( scrolling && ( !pointerElemChangedInterval || x !== lastPointerElemX || y !== lastPointerElemY ) ) { pointerElemChangedInterval && clearInterval(pointerElemChangedInterval); // Detect for pointer elem change, emulating native DnD behaviour pointerElemChangedInterval = setInterval(function() { if (!dragEl) return; // could also check if scroll direction on newElem changes due to parent autoscrolling var newElem = _getParentAutoScrollElement(document.elementFromPoint(x, y), true); if (newElem !== ogElemScroller) { ogElemScroller = newElem; _clearAutoScrolls(); _autoScroll(evt, _this.options, ogElemScroller, true); } }, 10); lastPointerElemX = x; lastPointerElemY = y; } } else { // if DnD is enabled (not on firefox), first autoscroll will already scroll, so get parent autoscroll of first autoscroll if (!_this.options.bubbleScroll || _getParentAutoScrollElement(elem, true) === window) { _clearAutoScrolls(); return; } _autoScroll(evt, _this.options, _getParentAutoScrollElement(elem, false)); } }, _prepareDragStart: function (/** Event */evt, /** Touch */touch, /** HTMLElement */target, /** Number */startIndex) { var _this = this, el = _this.el, options = _this.options, ownerDocument = el.ownerDocument, dragStartFn; if (target && !dragEl && (target.parentNode === el)) { tapEvt = evt; rootEl = el; dragEl = target; parentEl = dragEl.parentNode; nextEl = dragEl.nextSibling; lastDownEl = target; activeGroup = options.group; oldIndex = startIndex; this._lastX = (touch || evt).clientX; this._lastY = (touch || evt).clientY; dragEl.style['will-change'] = 'all'; dragStartFn = function () { // Delayed drag has been triggered // we can re-enable the events: touchmove/mousemove _this._disableDelayedDrag(); // Make the element draggable dragEl.draggable = _this.nativeDraggable; // Bind the events: dragstart/dragend _this._triggerDragStart(evt, touch); // Drag start event _dispatchEvent(_this, rootEl, 'choose', dragEl, rootEl, rootEl, oldIndex); // Chosen item _toggleClass(dragEl, options.chosenClass, true); }; // Disable "draggable" options.ignore.split(',').forEach(function (criteria) { _find(dragEl, criteria.trim(), _disableDraggable); }); _on(ownerDocument, 'mouseup', _this._onDrop); _on(ownerDocument, 'touchend', _this._onDrop); _on(ownerDocument, 'touchcancel', _this._onDrop); options.supportPointer && _on(ownerDocument, 'pointercancel', _this._onDrop); if (options.delay) { // If the user moves the pointer or let go the click or touch // before the delay has been reached: // disable the delayed drag _on(ownerDocument, 'mouseup', _this._disableDelayedDrag); _on(ownerDocument, 'touchend', _this._disableDelayedDrag); _on(ownerDocument, 'touchcancel', _this._disableDelayedDrag); _on(ownerDocument, 'mousemove', _this._delayedDragTouchMoveHandler); _on(ownerDocument, 'touchmove', _this._delayedDragTouchMoveHandler); options.supportPointer && _on(ownerDocument, 'pointermove', _this._delayedDragTouchMoveHandler); _this._dragStartTimer = setTimeout(dragStartFn.bind(_this), options.delay); } else { dragStartFn(); } } }, _delayedDragTouchMoveHandler: function (/** TouchEvent|PointerEvent **/e) { var touch = e.touches ? e.touches[0] : e; if (min(abs(touch.clientX - this._lastX), abs(touch.clientY - this._lastY)) >= this.options.touchStartThreshold ) { this._disableDelayedDrag(); } }, _disableDelayedDrag: function () { var ownerDocument = this.el.ownerDocument; clearTimeout(this._dragStartTimer); _off(ownerDocument, 'mouseup', this._disableDelayedDrag); _off(ownerDocument, 'touchend', this._disableDelayedDrag); _off(ownerDocument, 'touchcancel', this._disableDelayedDrag); _off(ownerDocument, 'mousemove', this._delayedDragTouchMoveHandler); _off(ownerDocument, 'touchmove', this._delayedDragTouchMoveHandler); _off(ownerDocument, 'pointermove', this._delayedDragTouchMoveHandler); }, _triggerDragStart: function (/** Event */evt, /** Touch */touch) { touch = touch || (evt.pointerType == 'touch' ? evt : null); if (touch) { // Touch device support tapEvt = { target: dragEl, clientX: touch.clientX, clientY: touch.clientY }; this._onDragStart(tapEvt, 'touch'); } else if (!this.nativeDraggable) { this._onDragStart(tapEvt, true); } else { _on(dragEl, 'dragend', this); _on(rootEl, 'dragstart', this._onDragStart); } try { if (document.selection) { // Timeout neccessary for IE9 _nextTick(function () { document.selection.empty(); }); } else { window.getSelection().removeAllRanges(); } } catch (err) { } }, _dragStarted: function () { if (rootEl && dragEl) { if (this.nativeDraggable) { _on(document, 'dragover', this._handleAutoScroll); _on(document, 'dragover', _checkAlignment); } var options = this.options; // Apply effect _toggleClass(dragEl, options.dragClass, false); _toggleClass(dragEl, options.ghostClass, true); _css(dragEl, 'transform', ''); Sortable.active = this; this._isAligned = true; // Drag start event _dispatchEvent(this, rootEl, 'start', dragEl, rootEl, rootEl, oldIndex); } else { this._nulling(); } }, _emulateDragOver: function (bypassLastTouchCheck) { if (touchEvt) { if (this._lastX === touchEvt.clientX && this._lastY === touchEvt.clientY && !bypassLastTouchCheck) { return; } this._lastX = touchEvt.clientX; this._lastY = touchEvt.clientY; if (!supportCssPointerEvents) { _css(ghostEl, 'display', 'none'); } var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY); var parent = target; var isDragEl = !!_closest(target, null, dragEl, true); while (target && target.shadowRoot) { target = target.shadowRoot.elementFromPoint(touchEvt.clientX, touchEvt.clientY); parent = target; } if (parent) { do { if (parent[expando]) { var i = touchDragOverListeners.length; while (i--) { touchDragOverListeners[i]({ clientX: touchEvt.clientX, clientY: touchEvt.clientY, target: target, rootEl: parent }); } if (!this.options.dragoverBubble) { break; } } target = parent; // store last element } /* jshint boss:true */ while (parent = parent.parentNode); } dragEl.parentNode[expando]._computeIsAligned(touchEvt, isDragEl); if (!supportCssPointerEvents) { _css(ghostEl, 'display', ''); } } }, _onTouchMove: function (/**TouchEvent*/evt) { if (tapEvt) { var options = this.options, fallbackTolerance = options.fallbackTolerance, fallbackOffset = options.fallbackOffset, touch = evt.touches ? evt.touches[0] : evt, dx = (touch.clientX - tapEvt.clientX) + fallbackOffset.x, dy = (touch.clientY - tapEvt.clientY) + fallbackOffset.y, translate3d = evt.touches ? 'translate3d(' + dx + 'px,' + dy + 'px,0)' : 'translate(' + dx + 'px,' + dy + 'px)'; // prevent duplicate event firing if (this.options.supportPointer && evt.type === 'touchmove') return; // only set the status to dragging, when we are actually dragging if (!Sortable.active) { if (fallbackTolerance && min(abs(touch.clientX - this._lastX), abs(touch.clientY - this._lastY)) < fallbackTolerance ) { return; } this._dragStarted(); } // as well as creating the ghost element on the document body this._appendGhost(); this._handleAutoScroll(touch, true); moved = true; touchEvt = touch; _css(ghostEl, 'webkitTransform', translate3d); _css(ghostEl, 'mozTransform', translate3d); _css(ghostEl, 'msTransform', translate3d); _css(ghostEl, 'transform', translate3d); evt.cancelable && evt.preventDefault(); } }, _appendGhost: function () { if (!ghostEl) { var rect = dragEl.getBoundingClientRect(), css = _css(dragEl), options = this.options, ghostRect; ghostEl = dragEl.cloneNode(true); _toggleClass(ghostEl, options.ghostClass, false); _toggleClass(ghostEl, options.fallbackClass, true); _toggleClass(ghostEl, options.dragClass, true); _css(ghostEl, 'top', rect.top - parseInt(css.marginTop, 10)); _css(ghostEl, 'left', rect.left - parseInt(css.marginLeft, 10)); _css(ghostEl, 'width', rect.width); _css(ghostEl, 'height', rect.height); _css(ghostEl, 'opacity', '0.8'); _css(ghostEl, 'position', 'fixed'); _css(ghostEl, 'zIndex', '100000'); _css(ghostEl, 'pointerEvents', 'none'); options.fallbackOnBody && document.body.appendChild(ghostEl) || rootEl.appendChild(ghostEl); // Fixing dimensions. ghostRect = ghostEl.getBoundingClientRect(); _css(ghostEl, 'width', rect.width * 2 - ghostRect.width); _css(ghostEl, 'height', rect.height * 2 - ghostRect.height); } }, _onDragStart: function (/**Event*/evt, /**boolean*/useFallback) { var _this = this; var dataTransfer = evt.dataTransfer; var options = _this.options; _this._offUpEvents(); if (activeGroup.checkPull(_this, _this, dragEl, evt)) { cloneEl = _clone(dragEl); cloneEl.draggable = false; cloneEl.style['will-change'] = ''; this._hideClone(); _toggleClass(cloneEl, _this.options.chosenClass, false); // #1143: IFrame support workaround _this._cloneId = _nextTick(function () { rootEl.insertBefore(cloneEl, dragEl); _dispatchEvent(_this, rootEl, 'clone', dragEl); }); } _toggleClass(dragEl, options.dragClass, true); if (useFallback) { if (useFallback === 'touch') { // Fixed #973: _on(document, 'touchmove', _preventScroll); // Bind touch events _on(document, 'touchmove', _this._onTouchMove); _on(document, 'touchend', _this._onDrop); _on(document, 'touchcancel', _this._onDrop); if (options.supportPointer) { _on(document, 'pointermove', _this._onTouchMove); _on(document, 'pointerup', _this._onDrop); } } else { // Old brwoser _on(document, 'mousemove', _this._onTouchMove); _on(document, 'mouseup', _this._onDrop); } _this._loopId = setInterval(_this._emulateDragOver, 50); _toggleClass(dragEl, options.dragClass, false); } else { if (dataTransfer) { dataTransfer.effectAllowed = 'move'; options.setData && options.setData.call(_this, dataTransfer, dragEl); } _on(document, 'drop', _this); // #1276 fix: _css(dragEl, 'transform', 'translateZ(0)'); _this._dragStartId = _nextTick(_this._dragStarted); } _on(document, 'selectstart', _this); }, _onDragOver: function (/**Event*/evt) { var el = this.el, target, dragRect, targetRect, revert, options = this.options, group = options.group, activeSortable = Sortable.active, isOwner = (activeGroup === group), isMovingBetweenSortable = false, canSort = options.sort ; if (evt.rootEl !== void 0 && evt.rootEl !== this.el) return; // touch fallback // no bubbling and not fallback if (!options.dragoverBubble && !evt.rootEl) { this._handleAutoScroll(evt); dragEl.parentNode[expando]._computeIsAligned(evt); } if (evt.preventDefault !== void 0) { evt.cancelable && evt.preventDefault(); !options.dragoverBubble && evt.stopPropagation(); } moved = true; target = _closest(evt.target, options.draggable, el, true); if (dragEl.animated && target === dragEl || target.animated || _silent) { return; } if (target !== lastTarget) { isCircumstantialInvert = false; pastFirstInvertThresh = false; lastTarget = null; } if (activeSortable && !options.disabled && (isOwner ? canSort || (revert = !rootEl.contains(dragEl)) // Reverting item into the original list : ( putSortable === this || ( (this.lastPutMode = activeGroup.checkPull(this, activeSortable, dragEl, evt)) && group.checkPut(this, activeSortable, dragEl, evt) ) ) ) ) { var direction; var axis = this._getDirection(evt, target); dragRect = dragEl.getBoundingClientRect(); if (putSortable !== this && this !== Sortable.active) { putSortable = this; isMovingBetweenSortable = true; } else if (this === Sortable.active) { isMovingBetweenSortable = false; putSortable = null; } if (revert) { this._hideClone(); parentEl = rootEl; // actualization if (cloneEl || nextEl) { rootEl.insertBefore(dragEl, cloneEl || nextEl); } else if (!canSort) { rootEl.appendChild(dragEl); } return; } if ((el.children.length === 0) || (el.children[0] === ghostEl) || (el === evt.target) && _ghostIsLast(evt, axis, el) ) { //assign target only if condition is true if (el.children.length !== 0 && el.children[0] !== ghostEl && el === evt.target) { target = _lastChild(el); } if (target) { if (target.animated) { return; } targetRect = target.getBoundingClientRect(); } if (isOwner) { activeSortable._hideClone(); } else { activeSortable._showClone(this); } if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, !!target) !== false) { if (!dragEl.contains(el)) { el.appendChild(dragEl); parentEl = el; // actualization this._isAligned = true; // must be for _ghostIsLast to pass realDragElRect = null; } this._animate(dragRect, dragEl); target && this._animate(targetRect, target); } } else if (target && !target.animated && target !== dragEl && (target.parentNode[expando] !== void 0) && target !== el) { isCircumstantialInvert = isCircumstantialInvert || options.invertSwap || dragEl.parentNode !== el || !this._isAligned; direction = _getSwapDirection(evt, target, axis, options.swapThreshold, options.invertedSwapThreshold, isCircumstantialInvert, lastTarget === target); if (direction === 0) return; realDragElRect = null; this._isAligned = true; if (!lastTarget || lastTarget !== target && (!target || !target.animated)) { pastFirstInvertThresh = false; lastTarget = target; } lastDirection = direction; targetRect = target.getBoundingClientRect(); var nextSibling = target.nextElementSibling, after = false ; after = direction === 1; var moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, after); if (moveVector !== false) { if (moveVector === 1 || moveVector === -1) { after = (moveVector === 1); } _silent = true; setTimeout(_unsilent, 30); if (isOwner) { activeSortable._hideClone(); } else { activeSortable._showClone(this); } if (!dragEl.contains(el)) { if (after && !nextSibling) { el.appendChild(dragEl); } else { target.parentNode.insertBefore(dragEl, after ? nextSibling : target); } } parentEl = dragEl.parentNode; // actualization this._animate(dragRect, dragEl); this._animate(targetRect, target); } } } }, _animate: function (prevRect, target) { var ms = this.options.animation; if (ms) { var currentRect = target.getBoundingClientRect(); if (target === dragEl) { realDragElRect = currentRect; } if (prevRect.nodeType === 1) { prevRect = prevRect.getBoundingClientRect(); } // Check if actually moving position if ((prevRect.left + prevRect.width / 2) === (currentRect.left + currentRect.width / 2) && (prevRect.top + prevRect.height / 2) === (currentRect.top + currentRect.height / 2) ) return; _css(target, 'transition', 'none'); _css(target, 'transform', 'translate3d(' + (prevRect.left - currentRect.left) + 'px,' + (prevRect.top - currentRect.top) + 'px,0)' ); forRepaintDummy = target.offsetWidth; // repaint _css(target, 'transition', 'all ' + ms + 'ms'); _css(target, 'transform', 'translate3d(0,0,0)'); clearTimeout(target.animated); target.animated = setTimeout(function () { _css(target, 'transition', ''); _css(target, 'transform', ''); target.animated = false; }, ms); } }, _offUpEvents: function () { var ownerDocument = this.el.ownerDocument; _off(document, 'touchmove', _preventScroll); _off(document, 'touchmove', this._onTouchMove); _off(document, 'pointermove', this._onTouchMove); _off(ownerDocument, 'mouseup', this._onDrop); _off(ownerDocument, 'touchend', this._onDrop); _off(ownerDocument, 'pointerup', this._onDrop); _off(ownerDocument, 'touchcancel', this._onDrop); _off(ownerDocument, 'pointercancel', this._onDrop); _off(document, 'selectstart', this); }, _onDrop: function (/**Event*/evt) { var el = this.el, options = this.options; scrolling = false; isCircumstantialInvert = false; pastFirstInvertThresh = false; clearInterval(this._loopId); clearInterval(pointerElemChangedInterval); _clearAutoScrolls(); _cancelThrottle(); clearTimeout(this._dragStartTimer); _cancelNextTick(this._cloneId); _cancelNextTick(this._dragStartId); // Unbind events _off(document, 'mousemove', this._onTouchMove); if (this.nativeDraggable) { _off(document, 'drop', this); _off(el, 'dragstart', this._onDragStart); _off(document, 'dragover', this._handleAutoScroll); _off(document, 'dragover', _checkAlignment); } this._offUpEvents(); if (evt) { if (moved) { evt.cancelable && evt.preventDefault(); !options.dropBubble && evt.stopPropagation(); } ghostEl && ghostEl.parentNode && ghostEl.parentNode.removeChild(ghostEl); if (rootEl === parentEl || (putSortable && putSortable.lastPutMode !== 'clone')) { // Remove clone cloneEl && cloneEl.parentNode && cloneEl.parentNode.removeChild(cloneEl); } if (dragEl) { if (this.nativeDraggable) { _off(dragEl, 'dragend', this); } _disableDraggable(dragEl); dragEl.style['will-change'] = ''; // Remove class's _toggleClass(dragEl, this.options.ghostClass, false); _toggleClass(dragEl, this.options.chosenClass, false); // Drag stop event _dispatchEvent(this, rootEl, 'unchoose', dragEl, parentEl, rootEl, oldIndex, null, evt); if (rootEl !== parentEl) { newIndex = _index(dragEl, options.draggable); if (newIndex >= 0) { // Add event _dispatchEvent(null, parentEl, 'add', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); // Remove event _dispatchEvent(this, rootEl, 'remove', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); // drag from one list and drop into another _dispatchEvent(null, parentEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); _dispatchEvent(this, rootEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); } putSortable && putSortable.save(); } else { if (dragEl.nextSibling !== nextEl) { // Get the index of the dragged element within its parent newIndex = _index(dragEl, options.draggable); if (newIndex >= 0) { // drag & drop within the same list _dispatchEvent(this, rootEl, 'update', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); _dispatchEvent(this, rootEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); } } } if (Sortable.active) { /* jshint eqnull:true */ if (newIndex == null || newIndex === -1) { newIndex = oldIndex; } _dispatchEvent(this, rootEl, 'end', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); // Save sorting this.save(); } } } this._nulling(); }, _nulling: function() { rootEl = dragEl = parentEl = ghostEl = nextEl = cloneEl = lastDownEl = scrollEl = scrollParentEl = autoScrolls.length = pointerElemChangedInterval = lastPointerElemX = lastPointerElemY = tapEvt = touchEvt = moved = newIndex = oldIndex = lastTarget = lastDirection = forRepaintDummy = realDragElRect = putSortable = activeGroup = Sortable.active = null; savedInputChecked.forEach(function (el) { el.checked = true; }); savedInputChecked.length = 0; }, handleEvent: function (/**Event*/evt) { switch (evt.type) { case 'drop': case 'dragend': this._onDrop(evt); break; case 'dragenter': case 'dragover': if (dragEl) { this._onDragOver(evt); _globalDragOver(evt); } break; case 'selectstart': evt.preventDefault(); break; } }, /** * Serializes the item into an array of string. * @returns {String[]} */ toArray: function () { var order = [], el, children = this.el.children, i = 0, n = children.length, options = this.options; for (; i < n; i++) { el = children[i]; if (_closest(el, options.draggable, this.el, false)) { order.push(el.getAttribute(options.dataIdAttr) || _generateId(el)); } } return order; }, /** * Sorts the elements according to the array. * @param {String[]} order order of the items */ sort: function (order) { var items = {}, rootEl = this.el; this.toArray().forEach(function (id, i) { var el = rootEl.children[i]; if (_closest(el, this.options.draggable, rootEl, false)) { items[id] = el; } }, this); order.forEach(function (id) { if (items[id]) { rootEl.removeChild(items[id]); rootEl.appendChild(items[id]); } }); }, /** * Save the current sorting */ save: function () { var store = this.options.store; store && store.set && store.set(this); }, /** * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. * @param {HTMLElement} el * @param {String} [selector] default: `options.draggable` * @returns {HTMLElement|null} */ closest: function (el, selector) { return _closest(el, selector || this.options.draggable, this.el, false); }, /** * Set/get option * @param {string} name * @param {*} [value] * @returns {*} */ option: function (name, value) { var options = this.options; if (value === void 0) { return options[name]; } else { options[name] = value; if (name === 'group') { _prepareGroup(options); } } }, /** * Destroy */ destroy: function () { var el = this.el; el[expando] = null; _off(el, 'mousedown', this._onTapStart); _off(el, 'touchstart', this._onTapStart); _off(el, 'pointerdown', this._onTapStart); if (this.nativeDraggable) { _off(el, 'dragover', this); _off(el, 'dragenter', this); } // Remove draggable attributes Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) { el.removeAttribute('draggable'); }); touchDragOverListeners.splice(touchDragOverListeners.indexOf(this._onDragOver), 1); this._onDrop(); this.el = el = null; }, _hideClone: function() { if (!cloneEl.cloneHidden) { _css(cloneEl, 'display', 'none'); cloneEl.cloneHidden = true; } }, _showClone: function(putSortable) { if (putSortable.lastPutMode !== 'clone') { this._hideClone(); return; } if (cloneEl.cloneHidden) { // show clone at dragEl or original position if (rootEl.contains(dragEl) && !this.options.group.revertClone) { rootEl.insertBefore(cloneEl, dragEl); } else if (nextEl) { rootEl.insertBefore(cloneEl, nextEl); } else { rootEl.appendChild(cloneEl); } if (this.options.group.revertClone) { this._animate(dragEl, cloneEl); } _css(cloneEl, 'display', ''); cloneEl.cloneHidden = false; } } }; function _closest(/**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx, includeCTX) { if (el) { ctx = ctx || document; do { if ((selector === '>*' && el.parentNode === ctx) || _matches(el, selector) || (includeCTX && el === ctx)) { return el; } if (el === ctx) break; /* jshint boss:true */ } while (el = _getParentOrHost(el)); } return null; } function _getParentOrHost(el) { return (el.host && el !== document && el.host.nodeType) ? el.host : el.parentNode; } function _globalDragOver(/**Event*/evt) { if (evt.dataTransfer) { evt.dataTransfer.dropEffect = 'move'; } evt.cancelable && evt.preventDefault(); } function _on(el, event, fn) { el.addEventListener(event, fn, captureMode); } function _off(el, event, fn) { el.removeEventListener(event, fn, captureMode); } function _toggleClass(el, name, state) { if (el && name) { if (el.classList) { el.classList[state ? 'add' : 'remove'](name); } else { var className = (' ' + el.className + ' ').replace(R_SPACE, ' ').replace(' ' + name + ' ', ' '); el.className = (className + (state ? ' ' + name : '')).replace(R_SPACE, ' '); } } } function _css(el, prop, val) { var style = el && el.style; if (style) { if (val === void 0) { if (document.defaultView && document.defaultView.getComputedStyle) { val = document.defaultView.getComputedStyle(el, ''); } else if (el.currentStyle) { val = el.currentStyle; } return prop === void 0 ? val : val[prop]; } else { if (!(prop in style)) { prop = '-webkit-' + prop; } style[prop] = val + (typeof val === 'string' ? '' : 'px'); } } } function _find(ctx, tagName, iterator) { if (ctx) { var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length; if (iterator) { for (; i < n; i++) { iterator(list[i], i); } } return list; } return []; } function _dispatchEvent(sortable, rootEl, name, targetEl, toEl, fromEl, startIndex, newIndex, originalEvt) { sortable = (sortable || rootEl[expando]); var evt, options = sortable.options, onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1); // Support for new CustomEvent feature if (window.CustomEvent) { evt = new CustomEvent(name, { bubbles: true, cancelable: true }); } else { evt = document.createEvent('Event'); evt.initEvent(name, true, true); } evt.to = toEl || rootEl; evt.from = fromEl || rootEl; evt.item = targetEl || rootEl; evt.clone = cloneEl; evt.oldIndex = startIndex; evt.newIndex = newIndex; evt.originalEvent = originalEvt; rootEl.dispatchEvent(evt); if (options[onName]) { options[onName].call(sortable, evt); } } function _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect, originalEvt, willInsertAfter) { var evt, sortable = fromEl[expando], onMoveFn = sortable.options.onMove, retVal; // Support for new CustomEvent feature if (window.CustomEvent) { evt = new CustomEvent('move', { bubbles: true, cancelable: true }); } else { evt = document.createEvent('Event'); evt.initEvent('move', true, true); } evt.to = toEl; evt.from = fromEl; evt.dragged = dragEl; evt.draggedRect = dragRect; evt.related = targetEl || toEl; evt.relatedRect = targetRect || toEl.getBoundingClientRect(); evt.willInsertAfter = willInsertAfter; evt.originalEvent = originalEvt; fromEl.dispatchEvent(evt); if (onMoveFn) { retVal = onMoveFn.call(sortable, evt, originalEvt); } return retVal; } function _disableDraggable(el) { el.draggable = false; } function _unsilent() { _silent = false; } function _getChild(el, childNum, options) { var currentChild = 0, i = 0, children = el.children ; while (i < children.length) { if ( children[i].style.display !== 'none' && children[i] !== ghostEl && children[i] !== dragEl && _closest(children[i], options.draggable, el, false) ) { if (currentChild === childNum) { return children[i]; } currentChild++; } i++; } return null; } function _lastChild(el) { var last = el.lastElementChild; if (last === ghostEl) { last = el.children[el.childElementCount - 2]; } return last || null; } function _ghostIsLast(evt, axis, el) { var elRect = _lastChild(el).getBoundingClientRect(), mouseOnAxis = axis === 'vertical' ? evt.clientY : evt.clientX, mouseOnOppAxis = axis === 'vertical' ? evt.clientX : evt.clientY, targetS2 = axis === 'vertical' ? elRect.bottom : elRect.right, targetS1Opp = axis === 'vertical' ? elRect.left : elRect.top, targetS2Opp = axis === 'vertical' ? elRect.right : elRect.bottom ; return ( mouseOnOppAxis > targetS1Opp && mouseOnOppAxis < targetS2Opp && mouseOnAxis > targetS2 ); } function _getSwapDirection(evt, target, axis, swapThreshold, invertedSwapThreshold, invertSwap, inside) { var targetRect = target.getBoundingClientRect(), mouseOnAxis = axis === 'vertical' ? evt.clientY : evt.clientX, targetLength = axis === 'vertical' ? targetRect.height : targetRect.width, targetS1 = axis === 'vertical' ? targetRect.top : targetRect.left, targetS2 = axis === 'vertical' ? targetRect.bottom : targetRect.right, dragRect = dragEl.getBoundingClientRect(), dragLength = axis === 'vertical' ? dragRect.height : dragRect.width, invert = false ; var dragStyle = _css(dragEl); dragLength += parseInt(dragStyle.marginLeft) + parseInt(dragStyle.marginRight); if (!invertSwap) { // Never invert or create dragEl shadow when width causes mouse to move past the end of regular swapThreshold if (inside && dragLength < targetLength * swapThreshold) { // multiplied only by swapThreshold because mouse will already be inside target by (1 - threshold) * targetLength / 2 // check if past first invert threshold on side opposite of lastDirection if (!pastFirstInvertThresh && (lastDirection === 1 ? ( mouseOnAxis > targetS1 + targetLength * invertedSwapThreshold / 2 ) : ( mouseOnAxis < targetS2 - targetLength * invertedSwapThreshold / 2 ) ) ) { // past first invert threshold, do not restrict inverted threshold to dragEl shadow pastFirstInvertThresh = true; } if (!pastFirstInvertThresh) { var dragS1 = axis === 'vertical' ? dragRect.top : dragRect.left, dragS2 = axis === 'vertical' ? dragRect.bottom : dragRect.right ; // dragEl shadow if ( lastDirection === 1 ? ( mouseOnAxis < targetS1 + dragLength // over dragEl shadow ) : ( mouseOnAxis > targetS2 - dragLength ) ) { return lastDirection * -1; } } else { invert = true; } } else { // Regular if ( mouseOnAxis > targetS1 + (targetLength * (1 - swapThreshold) / 2) && mouseOnAxis < targetS2 - (targetLength * (1 - swapThreshold) / 2) ) { return ((mouseOnAxis > targetS1 + targetLength / 2) ? -1 : 1); } } } invert = invert || invertSwap; if (invert) { // Invert of regular if ( mouseOnAxis < targetS1 + (targetLength * invertedSwapThreshold / 2) || mouseOnAxis > targetS2 - (targetLength * invertedSwapThreshold / 2) ) { return ((mouseOnAxis > targetS1 + targetLength / 2) ? 1 : -1); } } return 0; } /** * Generate id * @param {HTMLElement} el * @returns {String} * @private */ function _generateId(el) { var str = el.tagName + el.className + el.src + el.href + el.textContent, i = str.length, sum = 0; while (i--) { sum += str.charCodeAt(i); } return sum.toString(36); } /** * Returns the index of an element within its parent for a selected set of * elements * @param {HTMLElement} el * @param {selector} selector * @return {number} */ function _index(el, selector) { var index = 0; if (!el || !el.parentNode) { return -1; } while (el && (el = el.previousElementSibling)) { if ((el.nodeName.toUpperCase() !== 'TEMPLATE') && (selector === '>*' || _matches(el, selector))) { index++; } } return index; } function _matches(/**HTMLElement*/el, /**String*/selector) { if (el) { try { if (el.matches) { return el.matches(selector); } else if (el.msMatchesSelector) { return el.msMatchesSelector(selector); } } catch(_) { return false; } } return false; } var _throttleTimeout; function _throttle(callback, ms) { return function () { if (!_throttleTimeout) { var args = arguments, _this = this ; _throttleTimeout = setTimeout(function () { if (args.length === 1) { callback.call(_this, args[0]); } else { callback.apply(_this, args); } _throttleTimeout = void 0; }, ms); } }; } function _cancelThrottle() { clearTimeout(_throttleTimeout); _throttleTimeout = void 0; } function _extend(dst, src) { if (dst && src) { for (var key in src) { if (src.hasOwnProperty(key)) { dst[key] = src[key]; } } } return dst; } function _clone(el) { if (Polymer && Polymer.dom) { return Polymer.dom(el).cloneNode(true); } else if ($) { return $(el).clone(true)[0]; } else { return el.cloneNode(true); } } function _saveInputCheckedState(root) { savedInputChecked.length = 0; var inputs = root.getElementsByTagName('input'); var idx = inputs.length; while (idx--) { var el = inputs[idx]; el.checked && savedInputChecked.push(el); } } function _nextTick(fn) { return setTimeout(fn, 0); } function _cancelNextTick(id) { return clearTimeout(id); } function _preventScroll(evt) { if (Sortable.active && evt.cancelable) { evt.preventDefault(); } } // Export utils Sortable.utils = { on: _on, off: _off, css: _css, find: _find, is: function (el, selector) { return !!_closest(el, selector, el, false); }, extend: _extend, throttle: _throttle, closest: _closest, toggleClass: _toggleClass, clone: _clone, index: _index, nextTick: _nextTick, cancelNextTick: _cancelNextTick, detectDirection: _detectDirection, getChild: _getChild }; /** * Create sortable instance * @param {HTMLElement} el * @param {Object} [options] */ Sortable.create = function (el, options) { return new Sortable(el, options); }; // Export Sortable.version = '1.8.0-rc1'; return Sortable; });
extend1994/cdnjs
ajax/libs/Sortable/1.8.0-rc1/Sortable.js
JavaScript
mit
50,600
import { isElement, isValidElementType, ForwardRef } from 'react-is'; import unitless from '@emotion/unitless'; import validAttr from '@emotion/is-prop-valid'; import React, { useContext, useMemo, createElement, useState, useDebugValue, useEffect } from 'react'; import Stylis from 'stylis/stylis.min'; import _insertRulePlugin from 'stylis-rule-sheet'; import PropTypes from 'prop-types'; function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } // var interleave = (function (strings, interpolations) { var result = [strings[0]]; for (var i = 0, len = interpolations.length; i < len; i += 1) { result.push(interpolations[i], strings[i + 1]); } return result; }); // var isPlainObject = (function (x) { return typeof x === 'object' && x.constructor === Object; }); // var EMPTY_ARRAY = Object.freeze([]); var EMPTY_OBJECT = Object.freeze({}); // function isFunction(test) { return typeof test === 'function'; } // function getComponentName(target) { return (process.env.NODE_ENV !== 'production' ? typeof target === 'string' && target : false) || // $FlowFixMe target.displayName || // $FlowFixMe target.name || 'Component'; } // function isStatelessFunction(test) { return typeof test === 'function' && !(test.prototype && test.prototype.isReactComponent); } // function isStyledComponent(target) { return target && typeof target.styledComponentId === 'string'; } // var SC_ATTR = typeof process !== 'undefined' && process.env.SC_ATTR || 'data-styled'; var SC_ATTR_ACTIVE = 'active'; var SC_VERSION_ATTR = 'data-styled-version'; var SC_VERSION = "5.0.0-4.canary-sheet"; var IS_BROWSER = typeof window !== 'undefined' && 'HTMLElement' in window; var DISABLE_SPEEDY = typeof SC_DISABLE_SPEEDY === 'boolean' && SC_DISABLE_SPEEDY || process.env.NODE_ENV !== 'production'; // Shared empty execution context when generating static styles var STATIC_EXECUTION_CONTEXT = {}; // var ELEMENT_TYPE = 1; /* Node.ELEMENT_TYPE */ /** Find last style element if any inside target */ var findLastStyleTag = function findLastStyleTag(target) { var childNodes = target.childNodes; for (var i = childNodes.length; i >= 0; i--) { var child = childNodes[i]; if (child && child.nodeType === ELEMENT_TYPE && child.hasAttribute(SC_ATTR)) { return child; } } return undefined; }; /** Create a style element inside `target` or <head> after the last */ var makeStyleTag = function makeStyleTag(target) { var head = document.head; var parent = target || head; var style = document.createElement('style'); var prevStyle = findLastStyleTag(parent); var nextSibling = prevStyle !== undefined ? prevStyle.nextSibling : null; style.setAttribute(SC_ATTR, SC_ATTR_ACTIVE); style.setAttribute(SC_VERSION_ATTR, SC_VERSION); parent.insertBefore(style, nextSibling); return style; }; /** Get the CSSStyleSheet instance for a given style element */ var getSheet = function getSheet(tag) { if (tag.sheet) { return tag.sheet; } // Avoid Firefox quirk where the style element might not have a sheet property var _document = document, styleSheets = _document.styleSheets; for (var i = 0, l = styleSheets.length; i < l; i++) { var sheet = styleSheets[i]; if (sheet.ownerNode === tag) { return sheet; } } throw new TypeError("CSSStyleSheet could not be found on HTMLStyleElement"); }; // /** CSSStyleSheet-like Tag abstraction for CSS rules */ /** Create a CSSStyleSheet-like tag depending on the environment */ var makeTag = function makeTag(isServer, target) { if (!IS_BROWSER) { return new VirtualTag(target); } else if (DISABLE_SPEEDY) { return new TextTag(target); } else { return new SpeedyTag(target); } }; /** A Tag that wraps CSSOM's CSSStyleSheet API directly */ var SpeedyTag = /*#__PURE__*/ function () { function SpeedyTag(target) { var element = this.element = makeStyleTag(target); // Avoid Edge bug where empty style elements don't create sheets element.appendChild(document.createTextNode('')); this.sheet = getSheet(element); this.length = 0; } var _proto = SpeedyTag.prototype; _proto.insertRule = function insertRule(index, rule) { try { this.sheet.insertRule(rule, index); this.length++; return true; } catch (_error) { return false; } }; _proto.deleteRule = function deleteRule(index) { this.sheet.deleteRule(index); this.length--; }; _proto.getRule = function getRule(index) { if (index < this.length) { return this.sheet.cssRules[index].cssText; } else { return ''; } }; return SpeedyTag; }(); /** A Tag that emulates the CSSStyleSheet API but uses text nodes */ var TextTag = /*#__PURE__*/ function () { function TextTag(target) { var element = this.element = makeStyleTag(target); this.nodes = element.childNodes; this.length = 0; } var _proto2 = TextTag.prototype; _proto2.insertRule = function insertRule(index, rule) { if (index <= this.length && index >= 0) { var node = document.createTextNode(rule); var refNode = this.nodes[index]; this.element.insertBefore(node, refNode || null); this.length++; return true; } else { return false; } }; _proto2.deleteRule = function deleteRule(index) { this.element.removeChild(this.nodes[index]); this.length--; }; _proto2.getRule = function getRule(index) { if (index < this.length) { return this.nodes[index].textContent; } else { return ''; } }; return TextTag; }(); /** A completely virtual (server-side) Tag that doesn't manipulate the DOM */ var VirtualTag = /*#__PURE__*/ function () { function VirtualTag(_target) { this.rules = []; this.length = 0; } var _proto3 = VirtualTag.prototype; _proto3.insertRule = function insertRule(index, rule) { if (index <= this.length) { this.rules.splice(index, 0, rule); this.length++; return true; } else { return false; } }; _proto3.deleteRule = function deleteRule(index) { this.rules.splice(index, 1); this.length--; }; _proto3.getRule = function getRule(index) { if (index < this.length) { return this.rules[index]; } else { return ''; } }; return VirtualTag; }(); // /* eslint-disable no-use-before-define */ /** Group-aware Tag that sorts rules by indices */ /** Create a GroupedTag with an underlying Tag implementation */ var makeGroupedTag = function makeGroupedTag(tag) { return new DefaultGroupedTag(tag); }; var BASE_SIZE = 1 << 8; var DefaultGroupedTag = /*#__PURE__*/ function () { function DefaultGroupedTag(tag) { this.groupSizes = new Uint32Array(BASE_SIZE); this.length = BASE_SIZE; this.tag = tag; } var _proto = DefaultGroupedTag.prototype; _proto.indexOfGroup = function indexOfGroup(group) { var index = 0; for (var i = 0; i < group; i++) { index += this.groupSizes[i]; } return index; }; _proto.insertRules = function insertRules(group, rules) { if (group >= this.groupSizes.length) { var oldBuffer = this.groupSizes; var oldSize = oldBuffer.length; var newSize = BASE_SIZE << (group / BASE_SIZE | 0); this.groupSizes = new Uint32Array(newSize); this.groupSizes.set(oldBuffer); this.length = newSize; for (var i = oldSize; i < newSize; i++) { this.groupSizes[i] = 0; } } var startIndex = this.indexOfGroup(group + 1); for (var _i = 0, l = rules.length; _i < l; _i++) { if (this.tag.insertRule(startIndex + _i, rules[_i])) { this.groupSizes[group]++; } } }; _proto.clearGroup = function clearGroup(group) { if (group < this.length) { var length = this.groupSizes[group]; var startIndex = this.indexOfGroup(group); var endIndex = startIndex + length; this.groupSizes[group] = 0; for (var i = startIndex; i < endIndex; i++) { this.tag.deleteRule(startIndex); } } }; _proto.getGroup = function getGroup(group) { var css = ''; if (group >= this.length || this.groupSizes[group] === 0) { return css; } var length = this.groupSizes[group]; var startIndex = this.indexOfGroup(group); var endIndex = startIndex + length; for (var i = startIndex; i < endIndex; i++) { css += this.tag.getRule(i) + "\n"; } return css; }; return DefaultGroupedTag; }(); // var groupIDRegister = new Map(); var reverseRegister = new Map(); var nextFreeGroup = 1; var getGroupForId = function getGroupForId(id) { if (groupIDRegister.has(id)) { return groupIDRegister.get(id); } var group = nextFreeGroup++; groupIDRegister.set(id, group); reverseRegister.set(group, id); return group; }; var getIdForGroup = function getIdForGroup(group) { return reverseRegister.get(group); }; var setGroupForId = function setGroupForId(id, group) { if (group >= nextFreeGroup) { nextFreeGroup = group + 1; } groupIDRegister.set(id, group); reverseRegister.set(group, id); }; // var PLAIN_RULE_TYPE = 1; var SELECTOR = "style[" + SC_ATTR + "][" + SC_VERSION_ATTR + "=\"" + SC_VERSION + "\"]"; var MARKER_RE = new RegExp("^" + SC_ATTR + "\\.g(\\d+)\\[id=\"([\\w\\d-]+)\"\\]"); var outputSheet = function outputSheet(sheet) { var tag = sheet.getTag(); var length = tag.length; var css = ''; for (var group = 0; group < length; group++) { var id = getIdForGroup(group); if (id === undefined) continue; var names = sheet.names.get(id); var rules = tag.getGroup(group); if (names === undefined || rules.length === 0) continue; var selector = SC_ATTR + ".g" + group + "[id=\"" + id + "\"]"; var content = ''; if (names !== undefined) { names.forEach(function (name) { if (name.length > 0) { content += name + ","; } }); } // NOTE: It's easier to collect rules and have the marker // after the actual rules to simplify the rehydration css += rules + selector; if (content.length > 0) { css += "{content:\"" + content + "\"}\n"; } else { css += '{}\n'; } } return css; }; var rehydrateNamesFromContent = function rehydrateNamesFromContent(sheet, id, content) { var names = content.slice(1, -1).split(','); for (var i = 0, l = names.length; i < l; i++) { var name = names[i]; if (name.length > 0) { sheet.registerName(id, name); } } }; var rehydrateSheetFromTag = function rehydrateSheetFromTag(sheet, style) { var _getSheet = getSheet(style), cssRules = _getSheet.cssRules; var rules = []; for (var i = 0, l = cssRules.length; i < l; i++) { var cssRule = cssRules[i]; if (cssRule.type !== PLAIN_RULE_TYPE) { rules.push(cssRule.cssText); } else { var marker = cssRule.selectorText.match(MARKER_RE); if (marker !== null) { var group = parseInt(marker[1], 10) | 0; var id = marker[2]; var content = cssRule.style.content; if (group !== 0) { // Rehydrate componentId to group index mapping setGroupForId(id, group); // Rehydrate names and rules rehydrateNamesFromContent(sheet, id, content); sheet.getTag().insertRules(group, rules); } rules.length = 0; } else { rules.push(cssRule.cssText); } } } }; var rehydrateSheet = function rehydrateSheet(sheet) { var nodes = document.querySelectorAll(SELECTOR); for (var i = 0, l = nodes.length; i < l; i++) { var node = nodes[i]; if (node && node.getAttribute(SC_ATTR) !== SC_ATTR_ACTIVE) { rehydrateSheetFromTag(sheet, node); if (node.parentNode) { node.parentNode.removeChild(node); } } } }; // var SHOULD_REHYDRATE = IS_BROWSER; /** Contains the main stylesheet logic for stringification and caching */ var StyleSheet = /*#__PURE__*/ function () { /** Register a group ID to give it an index */ StyleSheet.registerId = function registerId(id) { return getGroupForId(id); }; function StyleSheet(isServer, target) { this.names = new Map(); this.isServer = isServer; this.target = target; // We rehydrate only once and use the sheet that is // created first if (!isServer && IS_BROWSER && SHOULD_REHYDRATE) { SHOULD_REHYDRATE = false; rehydrateSheet(this); } } /** Lazily initialises a GroupedTag for when it's actually needed */ var _proto = StyleSheet.prototype; _proto.getTag = function getTag() { if (this.tag === undefined) { var tag = makeTag(this.isServer, this.target); this.tag = makeGroupedTag(tag); } return this.tag; } /** Check whether a name is known for caching */ ; _proto.hasNameForId = function hasNameForId(id, name) { return this.names.has(id) && this.names.get(id).has(name); } /** Mark a group's name as known for caching */ ; _proto.registerName = function registerName(id, name) { getGroupForId(id); if (!this.names.has(id)) { var groupNames = new Set(); groupNames.add(name); this.names.set(id, groupNames); } else { this.names.get(id).add(name); } } /** Insert new rules which also marks the name as known */ ; _proto.insertRules = function insertRules(id, name, rules) { this.registerName(id, name); this.getTag().insertRules(getGroupForId(id), rules); } /** Clears all cached names for a given group ID */ ; _proto.clearNames = function clearNames(id) { if (this.names.has(id)) { this.names.get(id).clear(); } } /** Clears all rules for a given group ID */ ; _proto.clearRules = function clearRules(id) { this.getTag().clearGroup(getGroupForId(id)); this.clearNames(id); } /** Clears the entire tag which deletes all rules but not its names */ ; _proto.clearTag = function clearTag() { // NOTE: This does not clear the names, since it's only used during SSR // so that we can continuously output only new rules this.tag = undefined; } /** Outputs the current sheet as a CSS string with markers for SSR */ ; _proto.toString = function toString() { return outputSheet(this); }; return StyleSheet; }(); // // /** * Parse errors.md and turn it into a simple hash of code: message */ var ERRORS = process.env.NODE_ENV !== 'production' ? { "1": "Cannot create styled-component for component: %s.\n\n", "2": "Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n", "3": "Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n", "4": "The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n", "5": "The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n", "6": "Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n", "7": "ThemeProvider: Please return an object from your \"theme\" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n", "8": "ThemeProvider: Please make your \"theme\" prop an object.\n\n", "9": "Missing document `<head>`\n\n", "10": "Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n", "11": "_This error was replaced with a dev-time warning, it will be deleted for v4 final._ [createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n\n", "12": "It seems you are interpolating a keyframe declaration (%s) into an untagged string. This was supported in styled-components v3, but is not longer supported in v4 as keyframes are now injected on-demand. Please wrap your string in the css\\`\\` helper (see https://www.styled-components.com/docs/api#css), which ensures the styles are injected correctly.\n\n", "13": "%s is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.\n" } : {}; /** * super basic version of sprintf */ function format() { var a = arguments.length <= 0 ? undefined : arguments[0]; var b = []; for (var c = 1, len = arguments.length; c < len; c += 1) { b.push(c < 0 || arguments.length <= c ? undefined : arguments[c]); } b.forEach(function (d) { a = a.replace(/%[a-z]/, d); }); return a; } /** * Create an error file out of errors.md for development and a simple web link to the full errors * in production mode. */ var StyledComponentsError = /*#__PURE__*/ function (_Error) { _inheritsLoose(StyledComponentsError, _Error); function StyledComponentsError(code) { var _this; for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } if (process.env.NODE_ENV === 'production') { _this = _Error.call(this, "An error occurred. See https://github.com/styled-components/styled-components/blob/master/packages/styled-components/src/utils/errors.md#" + code + " for more information. " + (interpolations ? "Additional arguments: " + interpolations.join(', ') : '')) || this; } else { _this = _Error.call(this, format.apply(void 0, [ERRORS[code]].concat(interpolations)).trim()) || this; } return _assertThisInitialized(_this); } return StyledComponentsError; }(_wrapNativeSuper(Error)); // var Keyframes = /*#__PURE__*/ function () { function Keyframes(name, rules) { var _this = this; this.inject = function (styleSheet) { if (!styleSheet.hasNameForId(_this.id, _this.name)) { styleSheet.insertRules(_this.id, _this.name, _this.rules); } }; this.toString = function () { throw new StyledComponentsError(12, String(_this.name)); }; this.name = name; this.rules = rules; this.id = "sc-keyframes-" + name; } var _proto = Keyframes.prototype; _proto.getName = function getName() { return this.name; }; return Keyframes; }(); // /** * inlined version of * https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/hyphenateStyleName.js */ var uppercasePattern = /([A-Z])/g; var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return string.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-'); } // function addUnitIfNeeded(name, value) { // https://github.com/amilajack/eslint-plugin-flowtype-errors/issues/133 // $FlowFixMe if (value == null || typeof value === 'boolean' || value === '') { return ''; } if (typeof value === 'number' && value !== 0 && !(name in unitless)) { return value + "px"; // Presumes implicit 'px' suffix for unitless numbers } return String(value).trim(); } // /** * It's falsish not falsy because 0 is allowed. */ var isFalsish = function isFalsish(chunk) { return chunk === undefined || chunk === null || chunk === false || chunk === ''; }; var objToCss = function objToCss(obj, prevKey) { var css = Object.keys(obj).filter(function (key) { return !isFalsish(obj[key]); }).map(function (key) { if (isPlainObject(obj[key])) return objToCss(obj[key], key); return hyphenateStyleName(key) + ": " + addUnitIfNeeded(key, obj[key]) + ";"; }).join(' '); return prevKey ? prevKey + " {\n " + css + "\n}" : css; }; function flatten(chunk, executionContext, styleSheet) { if (Array.isArray(chunk)) { var ruleSet = []; for (var i = 0, len = chunk.length, result; i < len; i += 1) { result = flatten(chunk[i], executionContext, styleSheet); if (result === '') continue;else if (Array.isArray(result)) ruleSet.push.apply(ruleSet, result);else ruleSet.push(result); } return ruleSet; } if (isFalsish(chunk)) { return ''; } /* Handle other components */ if (isStyledComponent(chunk)) { return "." + chunk.styledComponentId; } /* Either execute or defer the function */ if (isFunction(chunk)) { if (isStatelessFunction(chunk) && executionContext) { var _result = chunk(executionContext); if (process.env.NODE_ENV !== 'production' && isElement(_result)) { // eslint-disable-next-line no-console console.warn(getComponentName(chunk) + " is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details."); } return flatten(_result, executionContext, styleSheet); } else return chunk; } if (chunk instanceof Keyframes) { if (styleSheet) { chunk.inject(styleSheet); return chunk.getName(); } else return chunk; } /* Handle objects */ return isPlainObject(chunk) ? objToCss(chunk) : chunk.toString(); } // function css(styles) { for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } if (isFunction(styles) || isPlainObject(styles)) { // $FlowFixMe return flatten(interleave(EMPTY_ARRAY, [styles].concat(interpolations))); } // $FlowFixMe return flatten(interleave(styles, interpolations)); } function constructWithOptions(componentConstructor, tag, options) { if (options === void 0) { options = EMPTY_OBJECT; } if (!isValidElementType(tag)) { throw new StyledComponentsError(1, String(tag)); } /* This is callable directly as a template function */ // $FlowFixMe: Not typed to avoid destructuring arguments var templateFunction = function templateFunction() { return componentConstructor(tag, options, css.apply(void 0, arguments)); }; /* If config methods are called, wrap up a new template function and merge options */ templateFunction.withConfig = function (config) { return constructWithOptions(componentConstructor, tag, _extends({}, options, config)); }; /* Modify/inject new props at runtime */ templateFunction.attrs = function (attrs) { return constructWithOptions(componentConstructor, tag, _extends({}, options, { attrs: Array.prototype.concat(options.attrs, attrs).filter(Boolean) })); }; return templateFunction; } // /* eslint-disable no-bitwise */ /* This is the "capacity" of our alphabet i.e. 2x26 for all letters plus their capitalised * counterparts */ var charsLength = 52; /* start at 75 for 'a' until 'z' (25) and then start at 65 for capitalised letters */ var getAlphabeticChar = function getAlphabeticChar(code) { return String.fromCharCode(code + (code > 25 ? 39 : 97)); }; /* input a number, usually a hash and convert it to base-52 */ function generateAlphabeticName(code) { var name = ''; var x; /* get a char and divide by alphabet-length */ for (x = Math.abs(code); x > charsLength; x = x / charsLength | 0) { name = getAlphabeticChar(x % charsLength) + name; } return getAlphabeticChar(x % charsLength) + name; } // // version of djb2 where we pretend that we're still looping over // the same string var phash = function phash(h, x) { h = h | 0; for (var i = 0, l = x.length | 0; i < l; i++) { h = (h << 5) + h + x.charCodeAt(i); } return h; }; // This is a djb2 hashing function var hash = function hash(x) { return phash(5381 | 0, x) >>> 0; }; var hasher = function hasher(str) { return generateAlphabeticName(hash(str)); }; // var stylis = new Stylis({ global: false, cascade: true, keyframe: false, prefix: true, compress: false, semicolon: false // NOTE: This means "autocomplete missing semicolons" }); // Wrap `insertRulePlugin to build a list of rules, // and then make our own plugin to return the rules. This // makes it easier to hook into the existing SSR architecture var parsingRules = []; // eslint-disable-next-line consistent-return var returnRulesPlugin = function returnRulesPlugin(context) { if (context === -2) { var parsedRules = parsingRules; parsingRules = []; return parsedRules; } }; var parseRulesPlugin = _insertRulePlugin(function (rule) { parsingRules.push(rule); }); var _componentId; var _selector; var _selectorRegexp; var selfReferenceReplacer = function selfReferenceReplacer(match, offset, string) { if ( // the first self-ref is always untouched offset > 0 && // there should be at least two self-refs to do a replacement (.b > .b) string.slice(0, offset).indexOf(_selector) !== -1 && // no consecutive self refs (.b.b); that is a precedence boost and treated differently string.slice(offset - _selector.length, offset) !== _selector) { return "." + _componentId; } return match; }; /** * When writing a style like * * & + & { * color: red; * } * * The second ampersand should be a reference to the static component class. stylis * has no knowledge of static class so we have to intelligently replace the base selector. */ var selfReferenceReplacementPlugin = function selfReferenceReplacementPlugin(context, _, selectors) { if (context === 2 && selectors.length && selectors[0].lastIndexOf(_selector) > 0) { // eslint-disable-next-line no-param-reassign selectors[0] = selectors[0].replace(_selectorRegexp, selfReferenceReplacer); } }; stylis.use([selfReferenceReplacementPlugin, parseRulesPlugin, returnRulesPlugin]); var COMMENT_REGEX = /^\s*\/\/.*$/gm; function stringifyRules(css, selector, prefix, componentId) { if (componentId === void 0) { componentId = '&'; } var flatCSS = css.replace(COMMENT_REGEX, ''); var cssStr = selector && prefix ? prefix + " " + selector + " { " + flatCSS + " }" : flatCSS; // stylis has no concept of state to be passed to plugins // but since JS is single=threaded, we can rely on that to ensure // these properties stay in sync with the current stylis run _componentId = componentId; _selector = selector; _selectorRegexp = new RegExp("\\" + _selector + "\\b", 'g'); return stylis(prefix || !selector ? '' : selector, cssStr); } // function hasFunctionObjectKey(obj) { // eslint-disable-next-line guard-for-in, no-restricted-syntax for (var key in obj) { if (isFunction(obj[key])) { return true; } } return false; } function isStaticRules(rules, attrs) { for (var i = 0; i < rules.length; i += 1) { var rule = rules[i]; // recursive case if (Array.isArray(rule) && !isStaticRules(rule, attrs)) { return false; } else if (isFunction(rule) && !isStyledComponent(rule)) { // functions are allowed to be static if they're just being // used to get the classname of a nested styled component return false; } } if (attrs.some(function (x) { return isFunction(x) || hasFunctionObjectKey(x); })) return false; return true; } // var isHMREnabled = process.env.NODE_ENV !== 'production' && typeof module !== 'undefined' && module.hot; /* ComponentStyle is all the CSS-specific stuff, not the React-specific stuff. */ var ComponentStyle = /*#__PURE__*/ function () { function ComponentStyle(rules, attrs, componentId) { this.rules = rules; this.isStatic = !isHMREnabled && IS_BROWSER && isStaticRules(rules, attrs); this.componentId = componentId; this.baseHash = hash(componentId); // NOTE: This registers the componentId, which ensures a consistent order // for this component's styles compared to others StyleSheet.registerId(componentId); } /* * Flattens a rule set into valid CSS * Hashes it, wraps the whole chunk in a .hash1234 {} * Returns the hash to be injected on render() * */ var _proto = ComponentStyle.prototype; _proto.generateAndInjectStyles = function generateAndInjectStyles(executionContext, styleSheet) { var componentId = this.componentId; if (this.isStatic) { if (!styleSheet.hasNameForId(componentId, componentId)) { var cssStatic = flatten(this.rules, executionContext, styleSheet).join(''); var cssStaticFormatted = stringifyRules(cssStatic, "." + componentId, undefined, componentId); styleSheet.insertRules(componentId, componentId, cssStaticFormatted); } return componentId; } else { var length = this.rules.length; var i = 0; var dynamicHash = this.baseHash; var css = ''; for (i = 0; i < length; i++) { var partRule = this.rules[i]; if (typeof partRule === 'string') { css += partRule; } else { var partChunk = flatten(partRule, executionContext, styleSheet); var partString = Array.isArray(partChunk) ? partChunk.join('') : partChunk; dynamicHash = phash(dynamicHash, partString + i); css += partString; } } var name = generateAlphabeticName(dynamicHash >>> 0); if (!styleSheet.hasNameForId(componentId, name)) { var cssFormatted = stringifyRules(css, "." + name, undefined, componentId); styleSheet.insertRules(componentId, name, cssFormatted); } return name; } }; return ComponentStyle; }(); // var LIMIT = 200; var createWarnTooManyClasses = (function (displayName) { var generatedClasses = {}; var warningSeen = false; return function (className) { if (!warningSeen) { generatedClasses[className] = true; if (Object.keys(generatedClasses).length >= LIMIT) { // Unable to find latestRule in test environment. /* eslint-disable no-console, prefer-template */ console.warn("Over " + LIMIT + " classes were generated for component " + displayName + ". \n" + 'Consider using the attrs method, together with a style object for frequently changed styles.\n' + 'Example:\n' + ' const Component = styled.div.attrs({\n' + ' style: ({ background }) => ({\n' + ' background,\n' + ' }),\n' + ' })`width: 100%;`\n\n' + ' <Component />'); warningSeen = true; generatedClasses = {}; } } }; }); // var determineTheme = (function (props, fallbackTheme, defaultProps) { if (defaultProps === void 0) { defaultProps = EMPTY_OBJECT; } // Props should take precedence over ThemeProvider, which should take precedence over // defaultProps, but React automatically puts defaultProps on props. /* eslint-disable react/prop-types, flowtype-errors/show-errors */ var isDefaultTheme = defaultProps ? props.theme === defaultProps.theme : false; var theme = props.theme && !isDefaultTheme ? props.theme : fallbackTheme || defaultProps.theme; /* eslint-enable */ return theme; }); // var escapeRegex = /[[\].#*$><+~=|^:(),"'`-]+/g; var dashesAtEnds = /(^-|-$)/g; /** * TODO: Explore using CSS.escape when it becomes more available * in evergreen browsers. */ function escape(str) { return str // Replace all possible CSS selectors .replace(escapeRegex, '-') // Remove extraneous hyphens at the start and end .replace(dashesAtEnds, ''); } // function isTag(target) { return typeof target === 'string' && (process.env.NODE_ENV !== 'production' ? target.charAt(0) === target.charAt(0).toLowerCase() : true); } // function generateDisplayName(target) { // $FlowFixMe return isTag(target) ? "styled." + target : "Styled(" + getComponentName(target) + ")"; } var _TYPE_STATICS; var REACT_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDerivedStateFromProps: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, callee: true, arguments: true, arity: true }; var TYPE_STATICS = (_TYPE_STATICS = {}, _TYPE_STATICS[ForwardRef] = { $$typeof: true, render: true }, _TYPE_STATICS); var defineProperty = Object.defineProperty, getOwnPropertyNames = Object.getOwnPropertyNames, _Object$getOwnPropert = Object.getOwnPropertySymbols, getOwnPropertySymbols = _Object$getOwnPropert === void 0 ? function () { return []; } : _Object$getOwnPropert, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor, getPrototypeOf = Object.getPrototypeOf, objectPrototype = Object.prototype; var arrayPrototype = Array.prototype; function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components var inheritedComponent = getPrototypeOf(sourceComponent); if (inheritedComponent && inheritedComponent !== objectPrototype) { hoistNonReactStatics(targetComponent, inheritedComponent, blacklist); } var keys = arrayPrototype.concat(getOwnPropertyNames(sourceComponent), // $FlowFixMe getOwnPropertySymbols(sourceComponent)); var targetStatics = TYPE_STATICS[targetComponent.$$typeof] || REACT_STATICS; var sourceStatics = TYPE_STATICS[sourceComponent.$$typeof] || REACT_STATICS; var i = keys.length; var descriptor; var key; // eslint-disable-next-line no-plusplus while (i--) { key = keys[i]; if ( // $FlowFixMe !KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && // $FlowFixMe !(targetStatics && targetStatics[key])) { descriptor = getOwnPropertyDescriptor(sourceComponent, key); if (descriptor) { try { // Avoid failures from read-only properties defineProperty(targetComponent, key, descriptor); } catch (e) { /* fail silently */ } } } } return targetComponent; } return targetComponent; } // function isDerivedReactComponent(fn) { return !!(fn && fn.prototype && fn.prototype.isReactComponent); } // // Helper to call a given function, only once var once = (function (cb) { var called = false; // $FlowFixMe this works if F is "(...any[]) => any" but that would imply the return value si forwarded return function () { if (!called) { called = true; cb.apply(void 0, arguments); } }; }); var ThemeContext = React.createContext(); var ThemeConsumer = ThemeContext.Consumer; function useMergedTheme(theme, outerTheme) { if (isFunction(theme)) { var mergedTheme = theme(outerTheme); if (process.env.NODE_ENV !== 'production' && (mergedTheme === null || Array.isArray(mergedTheme) || typeof mergedTheme !== 'object')) { throw new StyledComponentsError(7); } return mergedTheme; } if (theme === null || Array.isArray(theme) || typeof theme !== 'object') { throw new StyledComponentsError(8); } return outerTheme ? _extends({}, outerTheme, theme) : theme; } /** * Provide a theme to an entire react component tree via context */ function ThemeProvider(props) { var outerTheme = useContext(ThemeContext); // NOTE: can't really memoize with props.theme as that'd cause incorrect memoization when it's a function var themeContext = useMergedTheme(props.theme, outerTheme); if (!props.children) { return null; } return React.createElement(ThemeContext.Provider, { value: themeContext }, React.Children.only(props.children)); } // var StyleSheetContext = React.createContext(); var StyleSheetConsumer = StyleSheetContext.Consumer; var masterSheet = new StyleSheet(false); function useStyleSheet() { var fromContext = useContext(StyleSheetContext); return fromContext !== undefined ? fromContext : masterSheet; } function useStyleSheetProvider(sheet, target) { return useMemo(function () { if (sheet) { return sheet; } else if (target) { return new StyleSheet(false, target); } else { throw new StyledComponentsError(4); } }, [sheet, target]); } function StyleSheetManager(props) { var sheet = useStyleSheetProvider(props.sheet, props.target); return React.createElement(StyleSheetContext.Provider, { value: sheet }, process.env.NODE_ENV !== 'production' ? React.Children.only(props.children) : props.children); } process.env.NODE_ENV !== "production" ? StyleSheetManager.propTypes = { sheet: PropTypes.instanceOf(StyleSheet), target: PropTypes.shape({ appendChild: PropTypes.func.isRequired }) } : void 0; /* global $Call */ var identifiers = {}; /* We depend on components having unique IDs */ function generateId(displayName, parentComponentId) { var name = typeof displayName !== 'string' ? 'sc' : escape(displayName); // Ensure that no displayName can lead to duplicate componentIds var nr = (identifiers[name] || 0) + 1; identifiers[name] = nr; var componentId = name + "-" + hasher(name + nr); return parentComponentId ? parentComponentId + "-" + componentId : componentId; } function useResolvedAttrs(theme, props, attrs, utils) { if (theme === void 0) { theme = EMPTY_OBJECT; } // NOTE: can't memoize this // returns [context, resolvedAttrs] // where resolvedAttrs is only the things injected by the attrs themselves var context = _extends({}, props, { theme: theme }); var resolvedAttrs = {}; attrs.forEach(function (attrDef) { var resolvedAttrDef = attrDef; var attrDefWasFn = false; var attr; var key; if (isFunction(resolvedAttrDef)) { resolvedAttrDef = resolvedAttrDef(context); attrDefWasFn = true; } /* eslint-disable guard-for-in */ for (key in resolvedAttrDef) { attr = resolvedAttrDef[key]; if (!attrDefWasFn) { if (isFunction(attr) && !isDerivedReactComponent(attr) && !isStyledComponent(attr)) { if (process.env.NODE_ENV !== 'production') { utils.warnAttrsFnObjectKeyDeprecated(key); } attr = attr(context); if (process.env.NODE_ENV !== 'production' && React.isValidElement(attr)) { utils.warnNonStyledComponentAttrsObjectKey(key); } } } resolvedAttrs[key] = attr; context[key] = attr; } /* eslint-enable */ }); return [context, resolvedAttrs]; } function useInjectedStyle(componentStyle, hasAttrs, resolvedAttrs, utils, warnTooManyClasses) { var styleSheet = useStyleSheet(); // statically styled-components don't need to build an execution context object, // and shouldn't be increasing the number of class names var isStatic = componentStyle.isStatic && !hasAttrs; var className = isStatic ? componentStyle.generateAndInjectStyles(EMPTY_OBJECT, styleSheet) : componentStyle.generateAndInjectStyles(resolvedAttrs, styleSheet); if (process.env.NODE_ENV !== 'production' && !isStatic && warnTooManyClasses) { warnTooManyClasses(className); } useDebugValue(className); return className; } // TODO: convert these all to individual hooks, if possible function developmentDeprecationWarningsFactory(displayNameArg) { var displayName = displayNameArg || 'Unknown'; return { warnInnerRef: once(function () { return (// eslint-disable-next-line no-console console.warn("The \"innerRef\" API has been removed in styled-components v4 in favor of React 16 ref forwarding, use \"ref\" instead like a typical component. \"innerRef\" was detected on component \"" + displayName + "\".") ); }), warnAttrsFnObjectKeyDeprecated: once(function (key) { return (// eslint-disable-next-line no-console console.warn("Functions as object-form attrs({}) keys are now deprecated and will be removed in a future version of styled-components. Switch to the new attrs(props => ({})) syntax instead for easier and more powerful composition. The attrs key in question is \"" + key + "\" on component \"" + displayName + "\".") ); }), warnNonStyledComponentAttrsObjectKey: once(function (key) { return (// eslint-disable-next-line no-console console.warn("It looks like you've used a non styled-component as the value for the \"" + key + "\" prop in an object-form attrs constructor of \"" + displayName + "\".\n" + 'You should use the new function-form attrs constructor which avoids this issue: attrs(props => ({ yourStuff }))\n' + "To continue using the deprecated object syntax, you'll need to wrap your component prop in a function to make it available inside the styled component (you'll still get the deprecation warning though.)\n" + ("For example, { " + key + ": () => InnerComponent } instead of { " + key + ": InnerComponent }")) ); }) }; } function useDevelopmentDeprecationWarnings(displayName) { return useState(function () { return developmentDeprecationWarningsFactory(displayName); })[0]; } var useDeprecationWarnings = process.env.NODE_ENV !== 'production' ? useDevelopmentDeprecationWarnings : // NOTE: return value must only be accessed in non-production, of course // $FlowFixMe function () {}; function useStyledComponentImpl(forwardedComponent, props, forwardedRef) { var componentAttrs = forwardedComponent.attrs, componentStyle = forwardedComponent.componentStyle, defaultProps = forwardedComponent.defaultProps, displayName = forwardedComponent.displayName, foldedComponentIds = forwardedComponent.foldedComponentIds, styledComponentId = forwardedComponent.styledComponentId, target = forwardedComponent.target; // NOTE: the non-hooks version only subscribes to this when !componentStyle.isStatic, // but that'd be against the rules-of-hooks. We could be naughty and do it anyway as it // should be an immutable value, but behave for now. var theme = determineTheme(props, useContext(ThemeContext), defaultProps); var utils = useDeprecationWarnings(displayName); var _useResolvedAttrs = useResolvedAttrs(theme, props, componentAttrs, utils), context = _useResolvedAttrs[0], attrs = _useResolvedAttrs[1]; var generatedClassName = useInjectedStyle(componentStyle, componentAttrs.length > 0, context, utils, process.env.NODE_ENV !== 'production' ? forwardedComponent.warnTooManyClasses : undefined); // NOTE: this has to be called unconditionally due to the rules of hooks // it will just do nothing if it's not an in-browser development build // NOTE2: there is no (supported) way to know if the wrapped component actually can // receive refs -- just passing refs will trigger warnings on any function component child :( // -- this also means we can't keep doing this check unless StyledComponent is itself a class. // // const refToForward = useCheckClassNameUsage( // forwardedRef, // target, // generatedClassName, // attrs.suppressClassNameWarning // ); var refToForward = forwardedRef; var elementToBeCreated = // $FlowFixMe props.as || // eslint-disable-line react/prop-types attrs.as || target; var isTargetTag = isTag(elementToBeCreated); var computedProps = attrs !== props ? _extends({}, attrs, props) : props; var shouldFilterProps = 'as' in computedProps || isTargetTag; var propsForElement = shouldFilterProps ? {} : _extends({}, computedProps); if (process.env.NODE_ENV !== 'production' && 'innerRef' in computedProps && isTargetTag) { utils.warnInnerRef(); } if (shouldFilterProps) { // eslint-disable-next-line guard-for-in for (var key in computedProps) { if (key !== 'as' && (!isTargetTag || validAttr(key))) { // Don't pass through non HTML tags through to HTML elements propsForElement[key] = computedProps[key]; } } } if ( // $FlowFixMe props.style && // eslint-disable-line react/prop-types attrs.style !== props.style // eslint-disable-line react/prop-types ) { // $FlowFixMe propsForElement.style = _extends({}, attrs.style, props.style); // eslint-disable-line react/prop-types } // $FlowFixMe propsForElement.className = Array.prototype.concat(foldedComponentIds, // $FlowFixMe props.className, // eslint-disable-line react/prop-types styledComponentId, attrs.className, generatedClassName).filter(Boolean).join(' '); // $FlowFixMe propsForElement.ref = refToForward; useDebugValue(styledComponentId); return createElement(elementToBeCreated, propsForElement); } function createStyledComponent(target, options, rules) { var isTargetStyledComp = isStyledComponent(target); var isCompositeComponent = !isTag(target); var _options$displayName = options.displayName, displayName = _options$displayName === void 0 ? generateDisplayName(target) : _options$displayName, _options$componentId = options.componentId, componentId = _options$componentId === void 0 ? generateId(options.displayName, options.parentComponentId) : _options$componentId, _options$attrs = options.attrs, attrs = _options$attrs === void 0 ? EMPTY_ARRAY : _options$attrs; var styledComponentId = options.displayName && options.componentId ? escape(options.displayName) + "-" + options.componentId : options.componentId || componentId; // fold the underlying StyledComponent attrs up (implicit extend) var finalAttrs = // $FlowFixMe isTargetStyledComp && target.attrs ? Array.prototype.concat(target.attrs, attrs).filter(Boolean) : attrs; var componentStyle = new ComponentStyle(isTargetStyledComp ? // fold the underlying StyledComponent rules up (implicit extend) // $FlowFixMe target.componentStyle.rules.concat(rules) : rules, finalAttrs, styledComponentId); /** * forwardRef creates a new interim component, which we'll take advantage of * instead of extending ParentComponent to create _another_ interim class */ // $FlowFixMe this is a forced cast to merge it StyledComponentWrapperProperties var WrappedStyledComponent = React.forwardRef(function (props, ref) { return useStyledComponentImpl(WrappedStyledComponent, props, ref); }); WrappedStyledComponent.attrs = finalAttrs; WrappedStyledComponent.componentStyle = componentStyle; WrappedStyledComponent.displayName = displayName; WrappedStyledComponent.foldedComponentIds = isTargetStyledComp ? // $FlowFixMe Array.prototype.concat(target.foldedComponentIds, target.styledComponentId) : EMPTY_ARRAY; WrappedStyledComponent.styledComponentId = styledComponentId; // fold the underlying StyledComponent target up since we folded the styles WrappedStyledComponent.target = isTargetStyledComp ? // $FlowFixMe target.target : target; // $FlowFixMe WrappedStyledComponent.withComponent = function withComponent(tag) { var previousComponentId = options.componentId, optionsToCopy = _objectWithoutPropertiesLoose(options, ["componentId"]); var newComponentId = previousComponentId && previousComponentId + "-" + (isTag(tag) ? tag : escape(getComponentName(tag))); var newOptions = _extends({}, optionsToCopy, { attrs: finalAttrs, componentId: newComponentId }); return createStyledComponent(tag, newOptions, rules); }; if (process.env.NODE_ENV !== 'production') { WrappedStyledComponent.warnTooManyClasses = createWarnTooManyClasses(displayName); } // $FlowFixMe WrappedStyledComponent.toString = function () { return "." + WrappedStyledComponent.styledComponentId; }; if (isCompositeComponent) { hoistNonReactStatics(WrappedStyledComponent, target, { // all SC-specific things should not be hoisted attrs: true, componentStyle: true, displayName: true, foldedComponentIds: true, styledComponentId: true, target: true, withComponent: true }); } return WrappedStyledComponent; } // // Thanks to ReactDOMFactories for this handy list! var domElements = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', // SVG 'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'marker', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan']; // var styled = function styled(tag) { return constructWithOptions(createStyledComponent, tag); }; // Shorthands for all valid HTML Elements domElements.forEach(function (domElement) { styled[domElement] = styled(domElement); }); // var GlobalStyle = /*#__PURE__*/ function () { function GlobalStyle(rules, componentId) { this.rules = rules; this.componentId = componentId; this.isStatic = isStaticRules(rules, EMPTY_ARRAY); StyleSheet.registerId(componentId); } var _proto = GlobalStyle.prototype; _proto.createStyles = function createStyles(executionContext, styleSheet) { var flatCSS = flatten(this.rules, executionContext, styleSheet); var css = stringifyRules(flatCSS.join(''), ''); var id = this.componentId; // NOTE: We use the id as a name as well, since these rules never change styleSheet.insertRules(id, id, css); }; _proto.removeStyles = function removeStyles(styleSheet) { styleSheet.clearRules(this.componentId); }; _proto.renderStyles = function renderStyles(executionContext, styleSheet) { // NOTE: Remove old styles, then inject the new ones this.removeStyles(styleSheet); this.createStyles(executionContext, styleSheet); }; return GlobalStyle; }(); if (IS_BROWSER) { window.scCGSHMRCache = {}; } function createGlobalStyle(strings) { for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(void 0, [strings].concat(interpolations)); var styledComponentId = "sc-global-" + hasher(JSON.stringify(rules)); var globalStyle = new GlobalStyle(rules, styledComponentId); function GlobalStyleComponent(props) { var styleSheet = useStyleSheet(); var theme = useContext(ThemeContext); if (process.env.NODE_ENV !== 'production' && React.Children.count(props.children)) { // eslint-disable-next-line no-console console.warn("The global style component " + styledComponentId + " was given child JSX. createGlobalStyle does not render children."); } if (globalStyle.isStatic) { globalStyle.renderStyles(STATIC_EXECUTION_CONTEXT, styleSheet); } else { var context = _extends({}, props); if (typeof theme !== 'undefined') { context.theme = determineTheme(props, theme); } globalStyle.renderStyles(context, styleSheet); } useEffect(function () { if (IS_BROWSER) { window.scCGSHMRCache[styledComponentId] = (window.scCGSHMRCache[styledComponentId] || 0) + 1; return function () { if (window.scCGSHMRCache[styledComponentId]) { window.scCGSHMRCache[styledComponentId] -= 1; } /** * Depending on the order "render" is called this can cause the styles to be lost * until the next render pass of the remaining instance, which may * not be immediate. */ if (window.scCGSHMRCache[styledComponentId] === 0) { globalStyle.removeStyles(styleSheet); } }; } return undefined; }, []); return null; } return GlobalStyleComponent; } // function keyframes(strings) { /* Warning if you've used keyframes on React Native */ if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { // eslint-disable-next-line no-console console.warn('`keyframes` cannot be used on ReactNative, only on the web. To do animation in ReactNative please use Animated.'); } for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(void 0, [strings].concat(interpolations)).join(''); var name = hasher(rules); return new Keyframes(name, stringifyRules(rules, name, '@keyframes')); } // /* eslint-disable camelcase, no-undef */ var getNonce = function getNonce() { return typeof __webpack_nonce__ !== 'undefined' ? __webpack_nonce__ : null; }; // var CLOSING_TAG_R = /^\s*<\/[a-z]/i; var ServerStyleSheet = /*#__PURE__*/ function () { function ServerStyleSheet() { var _this = this; this.getStyleTags = function () { var css = _this.sheet.toString(); var nonce = getNonce(); var attrs = [nonce && "nonce=\"" + nonce + "\"", SC_ATTR, SC_VERSION_ATTR + "=\"" + SC_VERSION + "\""]; var htmlAttr = attrs.filter(Boolean).join(' '); return "<style " + htmlAttr + ">" + css + "</style>"; }; this.getStyleElement = function () { var _props; var props = (_props = {}, _props[SC_ATTR] = '', _props[SC_VERSION_ATTR] = SC_VERSION, _props.dangerouslySetInnerHTML = { __html: _this.sheet.toString() }, _props); var nonce = getNonce(); if (nonce) { props.nonce = nonce; } return React.createElement("style", props); }; this.sheet = new StyleSheet(true); this.sealed = false; } var _proto = ServerStyleSheet.prototype; _proto.collectStyles = function collectStyles(children) { if (this.sealed) { throw new StyledComponentsError(2); } this.sealed = true; return React.createElement(StyleSheetManager, { sheet: this.sheet }, children); }; _proto.interleaveWithNodeStream = function interleaveWithNodeStream(input) { { throw new StyledComponentsError(3); } // eslint-disable-next-line global-require var _require = require('stream'), Readable = _require.Readable, Transform = _require.Transform; var readableStream = input; var sheet = this.sheet, getStyleTags = this.getStyleTags; var transformer = new Transform({ transform: function appendStyleChunks(chunk, /* encoding */ _, callback) { // Get the chunk and retrieve the sheet's CSS as an HTML chunk, // then reset its rules so we get only new ones for the next chunk var renderedHtml = chunk.toString(); var html = getStyleTags(); sheet.clearTag(); // prepend style html to chunk, unless the start of the chunk is a // closing tag in which case append right after that if (CLOSING_TAG_R.test(renderedHtml)) { var endOfClosingTag = renderedHtml.indexOf('>') + 1; var before = renderedHtml.slice(0, endOfClosingTag); var after = renderedHtml.slice(endOfClosingTag); this.push(before + html + after); } else { this.push(html + renderedHtml); } callback(); } }); readableStream.on('error', function (err) { // forward the error to the transform stream transformer.emit('error', err); }); return readableStream.pipe(transformer); }; return ServerStyleSheet; }(); // export default <Config: { theme?: any }, Instance>( // Component: AbstractComponent<Config, Instance> // ): AbstractComponent<$Diff<Config, { theme?: any }> & { theme?: any }, Instance> // // but the old build system tooling doesn't support the syntax var withTheme = (function (Component) { // $FlowFixMe This should be React.forwardRef<Config, Instance> var WithTheme = React.forwardRef(function (props, ref) { var theme = useContext(ThemeContext); // $FlowFixMe defaultProps isn't declared so it can be inferrable var defaultProps = Component.defaultProps; var themeProp = determineTheme(props, theme, defaultProps); if (process.env.NODE_ENV !== 'production' && themeProp === undefined) { // eslint-disable-next-line no-console console.warn("[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class \"" + getComponentName(Component) + "\""); } return React.createElement(Component, _extends({}, props, { theme: themeProp, ref: ref })); }); hoistNonReactStatics(WithTheme, Component); WithTheme.displayName = "WithTheme(" + getComponentName(Component) + ")"; return WithTheme; }); // var __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS = { StyleSheet: StyleSheet, masterSheet: masterSheet }; // /* Warning if you've imported this file on React Native */ if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { // eslint-disable-next-line no-console console.warn("It looks like you've imported 'styled-components' on React Native.\n" + "Perhaps you're looking to import 'styled-components/native'?\n" + 'Read more about this at https://www.styled-components.com/docs/basics#react-native'); } /* Warning if there are several instances of styled-components */ if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test' && typeof window !== 'undefined' && typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Node.js') === -1 && navigator.userAgent.indexOf('jsdom') === -1) { window['__styled-components-init__'] = window['__styled-components-init__'] || 0; if (window['__styled-components-init__'] === 1) { // eslint-disable-next-line no-console console.warn("It looks like there are several instances of 'styled-components' initialized in this application. " + 'This may cause dynamic styles not rendering properly, errors happening during rehydration process ' + 'and makes your application bigger without a good reason.\n\n' + 'See https://s-c.sh/2BAXzed for more info.'); } window['__styled-components-init__'] += 1; } // export default styled; export { ServerStyleSheet, StyleSheetConsumer, StyleSheetContext, StyleSheetManager, ThemeConsumer, ThemeContext, ThemeProvider, __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS, createGlobalStyle, css, isStyledComponent, keyframes, withTheme }; //# sourceMappingURL=styled-components.browser.esm.js.map
sufuf3/cdnjs
ajax/libs/styled-components/5.0.0-4.canary-sheet/styled-components.browser.esm.js
JavaScript
mit
63,129
/* Highcharts JS v7.1.0 (2019-04-01) Indicator series type for Highstock (c) 2010-2019 Wojciech Chmiel License: www.highcharts.com/license */ (function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/indicators/ao",["highcharts","highcharts/modules/stock"],function(g){a(g);a.Highcharts=g;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function g(a,e,g,m){a.hasOwnProperty(e)||(a[e]=m.apply(null,g))}a=a?a._modules:{};g(a,"indicators/ao.src.js",[a["parts/Globals.js"]],function(a){var e=a.correctFloat,g=a.isArray;a.seriesType("ao", "sma",{greaterBarColor:"#06B535",lowerBarColor:"#F21313",threshold:0,groupPadding:.2,pointPadding:.2,states:{hover:{halo:{size:0}}}},{nameBase:"AO",nameComponents:!1,markerAttribs:a.noop,getColumnMetrics:a.seriesTypes.column.prototype.getColumnMetrics,crispCol:a.seriesTypes.column.prototype.crispCol,translate:a.seriesTypes.column.prototype.translate,drawPoints:a.seriesTypes.column.prototype.drawPoints,drawGraph:function(){var a=this.options,f=this.points,e=a.greaterBarColor,a=a.lowerBarColor,c=f[0]; if(!this.userOptions.color&&c)for(c.color=e,c=1;c<f.length;c++)f[c].color=f[c].y>f[c-1].y?e:f[c].y<f[c-1].y?a:f[c-1].color},getValues:function(a){var f=a.xData||[];a=a.yData||[];var m=a.length,c=[],n=[],p=[],h=0,k=0,d,l,b;if(34>=f.length||!g(a[0])||4!==a[0].length)return!1;for(b=0;33>b;b++)d=(a[b][1]+a[b][2])/2,29<=b&&(h=e(h+d)),k=e(k+d);for(b=33;b<m;b++)d=(a[b][1]+a[b][2])/2,h=e(h+d),k=e(k+d),d=h/5,l=k/34,d=e(d-l),c.push([f[b],d]),n.push(f[b]),p.push(d),d=b+1-5,l=b+1-34,h=e(h-(a[d][1]+a[d][2])/2), k=e(k-(a[l][1]+a[l][2])/2);return{values:c,xData:n,yData:p}}})});g(a,"masters/indicators/ao.src.js",[],function(){})}); //# sourceMappingURL=ao.js.map
joeyparrish/cdnjs
ajax/libs/highcharts/7.1.0/indicators/ao.js
JavaScript
mit
1,819
// Flags: --unhandled-rejections=none 'use strict'; const common = require('../common'); common.disableCrashOnUnhandledRejection(); // Verify that ignoring unhandled rejection works fine and that no warning is // logged. new Promise(() => { throw new Error('One'); }); Promise.reject('test'); process.on('warning', common.mustNotCall('warning')); process.on('uncaughtException', common.mustNotCall('uncaughtException')); process.on('rejectionHandled', common.mustNotCall('rejectionHandled')); process.on('unhandledRejection', common.mustCall(2)); setTimeout(common.mustCall(), 2);
enclose-io/compiler
lts/test/parallel/test-promise-unhandled-silent.js
JavaScript
mit
591
/** * Copyright (c) UNA, Inc - https://una.io * MIT License - https://opensource.org/licenses/MIT * * @defgroup UnaStudio UNA Studio * @{ */ function BxDolStudioNavigationMenus(oOptions) { this.sActionsUrl = oOptions.sActionUrl; this.sPageUrl = oOptions.sPageUrl; this.sObjNameGrid = oOptions.sObjNameGrid; this.sObjName = oOptions.sObjName == undefined ? 'oBxDolStudioNavigationMenus' : oOptions.sObjName; this.sAnimationEffect = oOptions.sAnimationEffect == undefined ? 'fade' : oOptions.sAnimationEffect; this.iAnimationSpeed = oOptions.iAnimationSpeed == undefined ? 'slow' : oOptions.iAnimationSpeed; this.sParamsDivider = oOptions.sParamsDivider == undefined ? '#-#' : oOptions.sParamsDivider; this.sTextSearchInput = oOptions.sTextSearchInput == undefined ? '' : oOptions.sTextSearchInput; } BxDolStudioNavigationMenus.prototype.onChangeFilter = function() { var sValueModule = $('#bx-grid-module-' + this.sObjNameGrid).val(); var sValueSearch = $('#bx-grid-search-' + this.sObjNameGrid).val(); if(sValueSearch == this.sTextSearchInput) sValueSearch = ''; glGrids[this.sObjNameGrid].setFilter(sValueModule + this.sParamsDivider + sValueSearch, true); }; BxDolStudioNavigationMenus.prototype.onSelectSet = function(oSelect) { var sSet = $(oSelect).val(); if(sSet == 'sys_create_new') $('#bx-form-element-set_title').show(); else $('#bx-form-element-set_title').hide(); }; /** @} */
camperjz/trident
upgrade/files/9.0.0.B2-9.0.0.B3/files/studio/js/navigation_menus.js
JavaScript
mit
1,476
(function(e,h){"object"===typeof exports&&"object"===typeof module?module.exports=h():"function"===typeof define&&define.amd?define([],h):"object"===typeof exports?exports.RxPlayer=h():e.RxPlayer=h()})(this,function(){return function(e){function h(l){if(a[l])return a[l].exports;var k=a[l]={exports:{},id:l,loaded:!1};e[l].call(k.exports,k,k.exports,h);k.loaded=!0;return k.exports}var a={};h.m=e;h.c=a;h.p="";return h(0)}([function(e,h,a){a(130);a(131);a(67);a(132);a(133);a(134);a(135);a(136);a(137); a(138);a(139);a(140);a(141);a(142);a(68);a(143);a(144);a(145);a(146);a(147);a(69);a(148);a(70);a(149);a(150);e.exports=a(197)},function(e,h,a){var l=a(13),k=a(27),d=a(185),g=a(30),b=a(20);e=function(){function a(f){this._isScalar=!1;f&&(this._subscribe=f)}a.prototype.lift=function(f){var b=new a;b.source=this;b.operator=f;return b};a.prototype.subscribe=function(a,b,c){var g=this.operator;a=d.toSubscriber(a,b,c);g?a.add(this._subscribe(g.call(a))):a.add(this._subscribe(a));if(a.syncErrorThrowable&& (a.syncErrorThrowable=!1,a.syncErrorThrown))throw a.syncErrorValue;return a};a.prototype.forEach=function(a,c,d){d||(l.root.Rx&&l.root.Rx.config&&l.root.Rx.config.Promise?d=l.root.Rx.config.Promise:l.root.Promise&&(d=l.root.Promise));if(!d)throw Error("no Promise impl found");var k=this;return new d(function(d,u){k.subscribe(function(d){g.tryCatch(a).call(c,d)===b.errorObject&&u(b.errorObject.e)},u,d)})};a.prototype._subscribe=function(a){return this.source.subscribe(a)};a.prototype[k.SymbolShim.observable]= function(){return this};a.create=function(f){return new a(f)};return a}();h.Observable=e},function(e,h,a){var l="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol?"symbol":typeof a},k=function(a,b){function c(){this.constructor=a}for(var g in b)b.hasOwnProperty(g)&&(a[g]=b[g]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},d=a(34);e=a(5);var g=a(46),b=a(129);a=function(a){function m(g, d,k){a.call(this);this.syncErrorValue=null;this.isStopped=this.syncErrorThrowable=this.syncErrorThrown=!1;switch(arguments.length){case 0:this.destination=b.empty;break;case 1:if(!g){this.destination=b.empty;break}if("object"===("undefined"===typeof g?"undefined":l(g))){g instanceof m?this.destination=g:(this.syncErrorThrowable=!0,this.destination=new c(this,g));break}default:this.syncErrorThrowable=!0,this.destination=new c(this,g,d,k)}}k(m,a);m.create=function(a,b,f){a=new m(a,b,f);a.syncErrorThrowable= !1;return a};m.prototype.next=function(a){this.isStopped||this._next(a)};m.prototype.error=function(a){this.isStopped||(this.isStopped=!0,this._error(a))};m.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())};m.prototype.unsubscribe=function(){this.isUnsubscribed||(this.isStopped=!0,a.prototype.unsubscribe.call(this))};m.prototype._next=function(a){this.destination.next(a)};m.prototype._error=function(a){this.destination.error(a);this.unsubscribe()};m.prototype._complete= function(){this.destination.complete();this.unsubscribe()};m.prototype[g.rxSubscriber]=function(){return this};return m}(e.Subscription);h.Subscriber=a;var c=function(a){function b(c,g,m,k){a.call(this);this._parent=c;var l;c=this;d.isFunction(g)?l=g:g&&(c=g,l=g.next,m=g.error,k=g.complete);this._context=c;this._next=l;this._error=m;this._complete=k}k(b,a);b.prototype.next=function(a){if(!this.isStopped&&this._next){var b=this._parent;b.syncErrorThrowable?this.__tryOrSetError(b,this._next,a)&&this.unsubscribe(): this.__tryOrUnsub(this._next,a)}};b.prototype.error=function(a){if(!this.isStopped){var b=this._parent;if(this._error)b.syncErrorThrowable?this.__tryOrSetError(b,this._error,a):this.__tryOrUnsub(this._error,a),this.unsubscribe();else if(b.syncErrorThrowable)b.syncErrorValue=a,b.syncErrorThrown=!0,this.unsubscribe();else throw this.unsubscribe(),a;}};b.prototype.complete=function(){if(!this.isStopped){var a=this._parent;this._complete&&(a.syncErrorThrowable?this.__tryOrSetError(a,this._complete):this.__tryOrUnsub(this._complete)); this.unsubscribe()}};b.prototype.__tryOrUnsub=function(a,b){try{a.call(this._context,b)}catch(f){throw this.unsubscribe(),f;}};b.prototype.__tryOrSetError=function(a,b,f){try{b.call(this._context,f)}catch(c){return a.syncErrorValue=c,a.syncErrorThrown=!0}return!1};b.prototype._unsubscribe=function(){var a=this._parent;this._parent=this._context=null;a.unsubscribe()};return b}(a)},function(e,h){function a(d){this.name="AssertionError";this.message=d;Error.captureStackTrace&&Error.captureStackTrace(this, a)}function l(d,g){if(!d)throw new a(g);}var k="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol?"symbol":typeof a};a.prototype=Error();l.equal=function(a,g,b){return l(a===g,b)};l.iface=function(a,g,b){l(a,g+" should be an object");for(var c in b)l.equal(k(a[c]),b[c],g+" should have property "+c+" as a "+b[c])};e.exports=l},function(e,h){function a(){}var l={NONE:0,ERROR:1,WARNING:2, INFO:3,DEBUG:4},k=function(){};a.error=k;a.warn=k;a.info=k;a.debug=k;a.setLevel=function(d){"string"==typeof d&&(d=l[d]);a.error=d>=l.ERROR?console.error.bind(console):k;a.warn=d>=l.WARNING?console.warn.bind(console):k;a.info=d>=l.INFO?console.info.bind(console):k;a.debug=d>=l.DEBUG?console.log.bind(console):k};e.exports=a},function(e,h,a){var l="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor=== Symbol?"symbol":typeof a},k=function(a,b){function f(){this.constructor=a}for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);a.prototype=null===b?Object.create(b):(f.prototype=b.prototype,new f)},d=a(28),g=a(79),b=a(34),c=a(30),f=a(20);e=function(){function a(b){this.isUnsubscribed=!1;b&&(this._unsubscribe=b)}a.prototype.unsubscribe=function(){var a=!1,k;if(!this.isUnsubscribed){this.isUnsubscribed=!0;var u=this._unsubscribe,l=this._subscriptions;this._subscriptions=null;if(b.isFunction(u)){var e=c.tryCatch(u).call(this); e===f.errorObject&&(a=!0,(k=k||[]).push(f.errorObject.e))}if(d.isArray(l))for(var u=-1,h=l.length;++u<h;)e=l[u],g.isObject(e)&&(e=c.tryCatch(e.unsubscribe).call(e),e===f.errorObject&&(a=!0,k=k||[],e=f.errorObject.e,e instanceof m?k=k.concat(e.errors):k.push(e)));if(a)throw new m(k);}};a.prototype.add=function(b){if(b&&b!==this&&b!==a.EMPTY){var f=b;switch("undefined"===typeof b?"undefined":l(b)){case "function":f=new a(b);case "object":if(f.isUnsubscribed||"function"!==typeof f.unsubscribe)break; else this.isUnsubscribed?f.unsubscribe():(this._subscriptions||(this._subscriptions=[])).push(f);break;default:throw Error("Unrecognized subscription "+b+" added to Subscription.");}}};a.prototype.remove=function(b){if(null!=b&&b!==this&&b!==a.EMPTY){var f=this._subscriptions;f&&(b=f.indexOf(b),-1!==b&&f.splice(b,1))}};a.EMPTY=function(a){a.isUnsubscribed=!0;return a}(new a);return a}();h.Subscription=e;var m=function(a){function b(f){a.call(this,"unsubscriptoin error(s)");this.errors=f;this.name= "UnsubscriptionError"}k(b,a);return b}(Error);h.UnsubscriptionError=m},function(e,h,a){var l=function(a,d){function g(){this.constructor=a}for(var b in d)d.hasOwnProperty(b)&&(a[b]=d[b]);a.prototype=null===d?Object.create(d):(g.prototype=d.prototype,new g)};e=function(a){function d(g){a.call(this);this.scheduler=g}l(d,a);d.create=function(a){return new d(a)};d.dispatch=function(a){a.subscriber.complete()};d.prototype._subscribe=function(a){var b=this.scheduler;if(b)return b.schedule(d.dispatch,0, {subscriber:a});a.complete()};return d}(a(1).Observable);h.EmptyObservable=e},function(e,h,a){var l=a(9);e.exports=function(a){return l(a)?a:Object(a)}},function(e,h,a){h=a(61);var l=a(16),k=a(17),d=Object.prototype.toString;a=h(Array,"isArray")||function(a){return k(a)&&l(a.length)&&"[object Array]"==d.call(a)};e.exports=a},function(e,h){var a="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor=== Symbol?"symbol":typeof a};e.exports=function(l){var k="undefined"===typeof l?"undefined":a(l);return!!l&&("object"==k||"function"==k)}},function(e,h,a){var l=function(a,b){function f(){this.constructor=a}for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);a.prototype=null===b?Object.create(b):(f.prototype=b.prototype,new f)};e=a(1);var k=a(2),d=a(5),g=a(182),b=a(46),c=a(81),f=a(76);a=function(a){function n(b,f){a.call(this);this.destination=b;this.source=f;this.observers=[];this.hasCompleted=this.dispatching= this.hasErrored=this.isStopped=this.isUnsubscribed=!1}l(n,a);n.prototype.lift=function(a){var b=new n(this.destination||this,this);b.operator=a;return b};n.prototype.add=function(a){d.Subscription.prototype.add.call(this,a)};n.prototype.remove=function(a){d.Subscription.prototype.remove.call(this,a)};n.prototype.unsubscribe=function(){d.Subscription.prototype.unsubscribe.call(this)};n.prototype._subscribe=function(a){if(this.source)return this.source.subscribe(a);if(!a.isUnsubscribed){if(this.hasErrored)return a.error(this.errorValue); if(this.hasCompleted)return a.complete();this.throwIfUnsubscribed();var b=new g.SubjectSubscription(this,a);this.observers.push(a);return b}};n.prototype._unsubscribe=function(){this.source=null;this.isStopped=!0;this.destination=this.observers=null};n.prototype.next=function(a){this.throwIfUnsubscribed();this.isStopped||(this.dispatching=!0,this._next(a),this.dispatching=!1,this.hasErrored?this._error(this.errorValue):this.hasCompleted&&this._complete())};n.prototype.error=function(a){this.throwIfUnsubscribed(); this.isStopped||(this.hasErrored=this.isStopped=!0,this.errorValue=a,this.dispatching||this._error(a))};n.prototype.complete=function(){this.throwIfUnsubscribed();this.isStopped||(this.hasCompleted=this.isStopped=!0,this.dispatching||this._complete())};n.prototype.asObservable=function(){return new m(this)};n.prototype._next=function(a){this.destination?this.destination.next(a):this._finalNext(a)};n.prototype._finalNext=function(a){for(var b=-1,f=this.observers.slice(0),c=f.length;++b<c;)f[b].next(a)}; n.prototype._error=function(a){this.destination?this.destination.error(a):this._finalError(a)};n.prototype._finalError=function(a){var b=-1,f=this.observers;this.observers=null;this.isUnsubscribed=!0;if(f)for(var c=f.length;++b<c;)f[b].error(a);this.isUnsubscribed=!1;this.unsubscribe()};n.prototype._complete=function(){this.destination?this.destination.complete():this._finalComplete()};n.prototype._finalComplete=function(){var a=-1,b=this.observers;this.observers=null;this.isUnsubscribed=!0;if(b)for(var f= b.length;++a<f;)b[a].complete();this.isUnsubscribed=!1;this.unsubscribe()};n.prototype.throwIfUnsubscribed=function(){this.isUnsubscribed&&c.throwError(new f.ObjectUnsubscribedError)};n.prototype[b.rxSubscriber]=function(){return new k.Subscriber(this)};n.create=function(a,b){return new n(a,b)};return n}(e.Observable);h.Subject=a;var m=function(a){function b(f){a.call(this);this.source=f}l(b,a);return b}(e.Observable)},function(e,h,a){function l(){for(var a=[],c=0;c<arguments.length;c++)a[c-0]=arguments[c]; var c=Number.POSITIVE_INFINITY,f=null,m=a[a.length-1];g.isScheduler(m)?(f=a.pop(),1<a.length&&"number"===typeof a[a.length-1]&&(c=a.pop())):"number"===typeof m&&(c=a.pop());return 1===a.length?a[0]:(new k.ArrayObservable(a,f)).lift(new d.MergeAllOperator(c))}var k=a(19),d=a(42),g=a(12);h.merge=function(){for(var a=[],c=0;c<arguments.length;c++)a[c-0]=arguments[c];a.unshift(this);return l.apply(this,a)};h.mergeStatic=l},function(e,h){h.isScheduler=function(a){return a&&"function"===typeof a.schedule}}, function(e,h,a){(function(a,k){var d="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol?"symbol":typeof a},g={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1};h.root=g["undefined"===typeof self?"undefined":d(self)]&&self||g["undefined"===typeof window?"undefined":d(window)]&&window;d(h);d(a);!(d=g["undefined"===typeof k?"undefined":d(k)]&&k)||d.global!==d&&d.window!== d||(h.root=d)}).call(h,a(186)(e),function(){return this}())},function(e,h,a){function l(a,b){return u(a.map(function(a){return(b||A).map(function(b){return b+a})}))}function k(a,b){return D(b,function(b){var f;f=document.createElement(a.tagName);b="on"+b;b in f?f=!0:(f.setAttribute(b,"return;"),f="function"==typeof f[b]);return f})}function d(a,b){var f=void 0;a=l(a,b);return function(b){return b instanceof O?("undefined"==typeof f&&(f=k(b,a)||null),f?y(b,f):w()):z(b,a)}}function g(a,b){function f(){var a= 0>=arguments.length||void 0===arguments[0]?{}:arguments[0];a.errorCode&&(a={systemCode:a.systemCode,code:a.errorCode.code});this.name="KeySessionError";this.mediaKeyError=a;this.message="MediaKeyError code:"+a.code+" and systemCode:"+a.systemCode}f.prototype=Error();return function(c,g){var m="function"==typeof b?b.call(this):this,d=R(m),k=P(m).map(function(a){throw new f(m.error||a);});try{return a.call(this,c,g),r(d,k).take(1)}catch(u){return p["throw"](u)}}}function b(a,b){if(b instanceof L)return b._setVideo(a); if(a.setMediaKeys)return a.setMediaKeys(b);if(null!==b){if(a.WebkitSetMediaKeys)return a.WebkitSetMediaKeys(b);if(a.mozSetMediaKeys)return a.mozSetMediaKeys(b);if(a.msSetMediaKeys)return a.msSetMediaKeys(b);throw Error("compat: cannot find setMediaKeys method");}}function c(){return!!(t.fullscreenElement||t.mozFullScreenElement||t.webkitFullscreenElement||t.msFullscreenElement)}var f=Object.assign||function(a){for(var b=1;b<arguments.length;b++){var f=arguments[b],c;for(c in f)Object.prototype.hasOwnProperty.call(f, c)&&(a[c]=f[c])}return a},m=function(){function a(b,f){for(var c=0;c<f.length;c++){var g=f[c];g.enumerable=g.enumerable||!1;g.configurable=!0;"value"in g&&(g.writable=!0);Object.defineProperty(b,g.key,g)}}return function(b,f,c){f&&a(b.prototype,f);c&&a(b,c);return b}}(),u=a(37);a(4);var n=a(35);h=a(21);var q=h.bytesToStr,x=h.strToBytes,v=a(3),p=a(1).Observable,r=a(11).mergeStatic,y=a(71).FromEventObservable.create,w=a(72).NeverObservable.create,z=a(15).on,D=a(22),C=a(86),t=document,B=window,A=["", "webkit","moz","ms"],O=B.HTMLElement;a=B.HTMLVideoElement;var G=B.MediaSource||B.MozMediaSource||B.WebKitMediaSource||B.MSMediaSource,E=B.MediaKeys||B.MozMediaKeys||B.WebKitMediaKeys||B.MSMediaKeys,H="Microsoft Internet Explorer"==navigator.appName||"Netscape"==navigator.appName&&/(Trident|Edge)\//.test(navigator.userAgent),L=function(){},F=void 0;navigator.requestMediaKeySystemAccess&&(F=function(a,b){return C(navigator.requestMediaKeySystemAccess(a,b))});var J=function(){function a(b,f,c){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this._keyType=b;this._mediaKeys=f;this._configuration=c}a.prototype.createMediaKeys=function(){return p.of(this._mediaKeys)};a.prototype.getConfiguration=function(){return this._configuration};m(a,[{key:"keySystem",get:function(){return this._keyType}}]);return a}(),K=d(["loadedmetadata"]),I=d(["sourceopen","webkitsourceopen"]);h=d(["encrypted","needkey"]);var M=d(["keymessage","message"]),R=d(["keyadded","ready"]),P=d(["keyerror","error"]), Q=d(["keystatuseschange"]);h={onEncrypted:h,onKeyMessage:M,onKeyStatusesChange:Q,onKeyError:P};!F&&a.prototype.webkitGenerateKeyRequest?function(){var a=function(a,b){var f=this;n.call(this);this.sessionId="";this._vid=a;this._key=b;this._con=r(M(a),R(a),P(a)).subscribe(function(a){return f.trigger(a.type,a)})};a.prototype=f({},n.prototype,{generateRequest:function(a,b){this._vid.webkitGenerateKeyRequest(this._key,b)},update:g(function(a,b){if(0<=this._key.indexOf("clearkey")){var f=JSON.parse(q(a)), c=x(atob(f.keys[0].k)),f=x(atob(f.keys[0].kid));this._vid.webkitAddKey(this._key,c,f,b)}else this._vid.webkitAddKey(this._key,a,null,b);this.sessionId=b}),close:function(){this._con&&this._con.unsubscribe();this._vid=this._con=null}});L=function(a){this.ks_=a};L.prototype={_setVideo:function(a){this._vid=a},createSession:function(){return new a(this._vid,this.ks_)}};var b=function(a){var b=t.querySelector("video")||t.createElement("video");return b&&b.canPlayType?!!b.canPlayType("video/mp4",a):!1}; F=function(a,f){if(!b(a))return p["throw"]();for(var c=0;c<f.length;c++){var g=f[c],m=g.videoCapabilities,d=g.audioCapabilities,k=g.initDataTypes,u=g.sessionTypes,n=g.distinctiveIdentifier,g=g.persistentState,l=!0;if(l=(l=(l=(l=l&&(!k||!!D(k,function(a){return"cenc"===a})))&&(!u||u.filter(function(a){return"temporary"===a}).length===u.length))&&"required"!==n)&&"required"!==g)return c={videoCapabilities:m,audioCapabilities:d,initDataTypes:["cenc"],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed", sessionTypes:["temporary"]},p.of(new J(a,new L(a),c))}return p["throw"]()}}():E&&!F&&function(){var a=function(a){n.call(this);this.sessionId="";this._mk=a};a.prototype=f({},n.prototype,{generateRequest:function(a,b){var f=this;this._ss=this._mk.memCreateSession("video/mp4",b);this._con=r(M(this._ss),R(this._ss),P(this._ss)).subscribe(function(a){return f.trigger(a.type,a)})},update:g(function(a,b){v(this._ss);this._ss.update(a,b);this.sessionId=b},function(){return this._ss}),close:function(){this._ss&& (this._ss.close(),this._ss=null);this._con&&(this._con.unsubscribe(),this._con=null)}});E.prototype.alwaysRenew=!0;E.prototype.memCreateSession=E.prototype.createSession;E.prototype.createSession=function(){return new a(this)};F=function(a,b){if(!E.isTypeSupported(a))return p["throw"]();for(var f=0;f<b.length;f++){var c=b[f],g=c.videoCapabilities,m=c.audioCapabilities,d=c.initDataTypes,c=c.distinctiveIdentifier,k=!0;if(k=(k=k&&(!d||D(d,function(a){return"cenc"===a})))&&"required"!==c)return f={videoCapabilities:g, audioCapabilities:m,initDataTypes:["cenc"],distinctiveIdentifier:"not-allowed",persistentState:"required",sessionTypes:["temporary","persistent-license"]},p.of(new J(a,new E(a),f))}return p["throw"]()}}();E||(Q=function(){throw Error("eme: MediaKeys is not available");},E={create:Q,isTypeSupported:Q});if(B.WebKitSourceBuffer&&!B.WebKitSourceBuffer.prototype.addEventListener){var Q=B.WebKitSourceBuffer.prototype,T;for(T in n.prototype)Q[T]=n.prototype[T];Q.__listeners=[];Q.appendBuffer=function(a){if(this.updating)throw Error("SourceBuffer updating"); this.trigger("updatestart");this.updating=!0;try{this.append(a)}catch(b){this.__emitUpdate("error",b);return}this.__emitUpdate("update")};Q.__emitUpdate=function(a,b){var f=this;setTimeout(function(){f.trigger(a,b);f.updating=!1;f.trigger("updateend")},0)}}T=d(["fullscreenchange","FullscreenChange"],A.concat("MS"));e.exports={HTMLVideoElement_:a,MediaSource_:G,isCodecSupported:function(a){return!!G&&G.isTypeSupported(a)},sourceOpen:function(a){return"open"==a.readyState?p.of(null):I(a).take(1)},canSeek:function(a){return 1<= a.readyState?p.of(null):K(a).take(1)},canPlay:function(a){return 4<=a.readyState?p.of(null):z(a,"canplay").take(1)},KeySystemAccess:J,requestMediaKeySystemAccess:F,setMediaKeys:function(a,f){return C(b(a,f))},emeEvents:h,shouldRenewMediaKeys:function(){return H},isFullscreen:c,onFullscreenChange:T,requestFullscreen:function(a){c()||(a.requestFullscreen?a.requestFullscreen():a.msRequestFullscreen?a.msRequestFullscreen():a.mozRequestFullScreen?a.mozRequestFullScreen():a.webkitRequestFullscreen&&a.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT))}, exitFullscreen:function(){c()&&(t.exitFullscreen?t.exitFullscreen():t.msExitFullscreen?t.msExitFullscreen():t.mozCancelFullScreen?t.mozCancelFullScreen():t.webkitExitFullscreen&&t.webkitExitFullscreen())},videoSizeChange:function(){return z(B,"resize")},visibilityChange:function(){var a=void 0;null!=t.hidden?a="":null!=t.mozHidden?a="moz":null!=t.msHidden?a="ms":null!=t.webkitHidden&&(a="webkit");var b=a?a+"Hidden":"hidden";return z(t,a+"visibilitychange").map(function(){return t[b]})},clearVideoSrc:function(a){H? a.removeAttribute("src"):a.src=""},addTextTrack:function(a){var b=void 0,f=void 0;H?(b=a.addTextTrack("subtitles"),b.mode=b.SHOWING):(f=document.createElement("track"),b=f.track,f.kind="subtitles",b.mode="showing",a.appendChild(f));return{track:b,trackElement:f}},isVTTSupported:function(){return!H},isIE:H}},function(e,h,a){a(69);a(70);a(67);a(68);h=a(1).Observable;var l=a(11).mergeStatic,k=a(71).FromEventObservable.create,d=a(41).TimerObservable.create,g=a(72).NeverObservable.create,b=a(49).getBackedoffDelay, c=a(4),f=a(50);h.prototype.log=function(a,b){a||(a="");return this["do"](function(f){return c.debug(a,"next",b?b(f):f)},function(b){return c.debug(a,"error",b)},function(){return c.debug(a,"completed")})};e.exports={on:function(a,b){return Array.isArray(b)?l.apply(null,b.map(function(b){return k(a,b)})):k(a,b)},first:function(a){return a.take(1)},only:function(a){return g().startWith(a)},retryWithBackoff:function(a,c){var g=c.retryDelay,k=c.totalRetry,l=c.shouldRetry,e=c.resetDelay,h=0,r;0<e&&(r= f(function(){return h=0},e));return function w(){for(var f=0,c=arguments.length,u=Array(c);f<c;f++)u[f]=arguments[f];return a.apply(null,u)["catch"](function(a){if(l&&!l(a,h)||h++>=k)throw a;a=b(g,h);return d(a).flatMap(function(){r&&r();return w.apply(null,u)})})}}}},function(e,h){e.exports=function(a){return"number"==typeof a&&-1<a&&0==a%1&&9007199254740991>=a}},function(e,h){var a="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"=== typeof Symbol&&a.constructor===Symbol?"symbol":typeof a};e.exports=function(l){return!!l&&"object"==("undefined"===typeof l?"undefined":a(l))}},function(e,h,a){h=a(61);var l=a(33),k=a(9),d=a(119),g=h(Object,"keys");e.exports=g?function(a){var c=null==a?void 0:a.constructor;return"function"==typeof c&&c.prototype===a||"function"!=typeof a&&l(a)?d(a):k(a)?g(a):[]}:d},function(e,h,a){var l=function(a,c){function f(){this.constructor=a}for(var g in c)c.hasOwnProperty(g)&&(a[g]=c[g]);a.prototype=null=== c?Object.create(c):(f.prototype=c.prototype,new f)};e=a(1);var k=a(40),d=a(6),g=a(12);a=function(a){function c(f,c){a.call(this);this.array=f;this.scheduler=c;c||1!==f.length||(this._isScalar=!0,this.value=f[0])}l(c,a);c.create=function(a,b){return new c(a,b)};c.of=function(){for(var a=[],b=0;b<arguments.length;b++)a[b-0]=arguments[b];b=a[a.length-1];g.isScheduler(b)?a.pop():b=null;var u=a.length;return 1<u?new c(a,b):1===u?new k.ScalarObservable(a[0],b):new d.EmptyObservable(b)};c.dispatch=function(a){var b= a.array,c=a.index,g=a.subscriber;c>=a.count?g.complete():(g.next(b[c]),g.isUnsubscribed||(a.index=c+1,this.schedule(a)))};c.prototype._subscribe=function(a){var b=this.array,g=b.length,d=this.scheduler;if(d)return d.schedule(c.dispatch,0,{array:b,index:0,count:g,subscriber:a});for(d=0;d<g&&!a.isUnsubscribed;d++)a.next(b[d]);a.complete()};return c}(e.Observable);h.ArrayObservable=a},function(e,h){h.errorObject={e:{}}},function(e,h,a){function l(a){for(var b=a.length,c=new Uint8Array(b),f=0;f<b;f++)c[f]= a.charCodeAt(f)&255;return c}function k(a,b){b||(b="");for(var c="",f=0;f<a.byteLength;f++)c+=(a[f]>>>4).toString(16),c+=(a[f]&15).toString(16),b.length&&(c+=b);return c}var d=a(3);e.exports={totalBytes:function(a){for(var b=0,c=0;c<a.length;c++)b+=a[c].byteLength;return b},strToBytes:l,bytesToStr:function(a){return String.fromCharCode.apply(null,a)},bytesToUTF16Str:function(a){for(var b="",c=a.length,f=0;f<c;f+=2)b+=String.fromCharCode(a[f]);return b},hexToBytes:function(a){for(var b=a.length,c= new Uint8Array(b/2),f=0,m=0;f<b;f+=2,m++)c[m]=parseInt(a.substr(f,2),16)&255;return c},bytesToHex:k,concat:function(){for(var a=arguments.length,b=-1,c=0,f;++b<a;)f=arguments[b],c+="number"===typeof f?f:f.length;for(var c=new Uint8Array(c),m=0,b=-1;++b<a;)f=arguments[b],"number"===typeof f?m+=f:0<f.length&&(c.set(f,m),m+=f.length);return c},be2toi:function(a,b){return(a[0+b]<<8)+(a[1+b]<<0)},be4toi:function(a,b){return 16777216*a[0+b]+65536*a[1+b]+256*a[2+b]+a[3+b]},be8toi:function(a,b){return 4294967296* (16777216*a[0+b]+65536*a[1+b]+256*a[2+b]+a[3+b])+16777216*a[4+b]+65536*a[5+b]+256*a[6+b]+a[7+b]},le2toi:function(a,b){return(a[0+b]<<0)+(a[1+b]<<8)},le4toi:function(a,b){return a[0+b]+256*a[1+b]+65536*a[2+b]+16777216*a[3+b]},le8toi:function(a,b){return a[0+b]+256*a[1+b]+65536*a[2+b]+16777216*a[3+b]+(a[4+b]+256*a[5+b]+65536*a[6+b]+16777216*a[7+b]*4294967296)},itobe2:function(a){return new Uint8Array([a>>>8&255,a&255])},itobe4:function(a){return new Uint8Array([a>>>24&255,a>>>16&255,a>>>8&255,a&255])}, itobe8:function(a){var b=a%4294967296;a=(a-b)/4294967296;return new Uint8Array([a>>>24&255,a>>>16&255,a>>>8&255,a&255,b>>>24&255,b>>>16&255,b>>>8&255,b&255])},itole2:function(a){return new Uint8Array([a&255,a>>>8&255])},itole4:function(a){return new Uint8Array([a&255,a>>>8&255,a>>>16&255,a>>>24&255])},itole8:function(a){var b=a%4294967296;a=(a-b)/4294967296;return new Uint8Array([a&255,a>>>8&255,a>>>16&255,a>>>24&255,b&255,b>>>8&255,b>>>16&255,b>>>24&255])},guidToUuid:function(a){d.equal(a.length, 16,"UUID length should be 16");var b=l(a);a=b[0];var c=b[1],f=b[2],m=b[3],u=b[4],e=b[5],h=b[6],x=b[7],v=b.subarray(8,10),b=b.subarray(10,16),p=new Uint8Array(16);p[0]=m;p[1]=f;p[2]=c;p[3]=a;p[4]=e;p[5]=u;p[6]=x;p[7]=h;p.set(v,8);p.set(b,10);return k(p)},toBase64URL:function(a){return btoa(a).replace(/\=+$/,"")}}},function(e,h,a){h=a(97);a=a(59)(h);e.exports=a},function(e,h,a){h=a(123);var l=a(92);a=a(114)(h,l);e.exports=a},function(e,h,a){var l=function(a,d){function g(){this.constructor=a}for(var b in d)d.hasOwnProperty(b)&& (a[b]=d[b]);a.prototype=null===d?Object.create(d):(g.prototype=d.prototype,new g)};e=function(a){function d(){a.apply(this,arguments)}l(d,a);d.prototype.notifyNext=function(a,b,c,f,m){this.destination.next(b)};d.prototype.notifyError=function(a,b){this.destination.error(a)};d.prototype.notifyComplete=function(a){this.destination.complete()};return d}(a(2).Subscriber);h.OuterSubscriber=e},function(e,h,a){var l=function(a,b){function f(){this.constructor=a}for(var c in b)b.hasOwnProperty(c)&&(a[c]= b[c]);a.prototype=null===b?Object.create(b):(f.prototype=b.prototype,new f)},k=a(19),d=a(28),g=a(12);e=a(24);var b=a(29);h.combineLatest=function(){for(var a=[],b=0;b<arguments.length;b++)a[b-0]=arguments[b];b=null;"function"===typeof a[a.length-1]&&(b=a.pop());1===a.length&&d.isArray(a[0])&&(a=a[0]);a.unshift(this);return(new k.ArrayObservable(a)).lift(new c(b))};h.combineLatestStatic=function(){for(var a=[],b=0;b<arguments.length;b++)a[b-0]=arguments[b];var f=b=null;g.isScheduler(a[a.length-1])&& (f=a.pop());"function"===typeof a[a.length-1]&&(b=a.pop());1===a.length&&d.isArray(a[0])&&(a=a[0]);return(new k.ArrayObservable(a,f)).lift(new c(b))};var c=function(){function a(b){this.project=b}a.prototype.call=function(a){return new f(a,this.project)};return a}();h.CombineLatestOperator=c;var f=function(a){function f(b,c){a.call(this,b);this.project=c;this.active=0;this.values=[];this.observables=[];this.toRespond=[]}l(f,a);f.prototype._next=function(a){var b=this.toRespond;b.push(b.length);this.observables.push(a)}; f.prototype._complete=function(){var a=this.observables,f=a.length;if(0===f)this.destination.complete();else{this.active=f;for(var c=0;c<f;c++){var g=a[c];this.add(b.subscribeToResult(this,g,g,c))}}};f.prototype.notifyComplete=function(a){0===--this.active&&this.destination.complete()};f.prototype.notifyNext=function(a,b,f,c,g){a=this.values;a[f]=b;b=this.toRespond;0<b.length&&(f=b.indexOf(f),-1!==f&&b.splice(f,1));0===b.length&&(this.project?this._tryProject(a):this.destination.next(a))};f.prototype._tryProject= function(a){var b;try{b=this.project.apply(this,a)}catch(f){this.destination.error(f);return}this.destination.next(b)};return f}(e.OuterSubscriber);h.CombineLatestSubscriber=f},function(e,h,a){e=a(179);h.asap=new e.AsapScheduler},function(e,h,a){function l(a){var f=d(a);b(f,a);c(f);k(f);return f}function k(a){a["for"]||(a["for"]=g)}function d(a){a.Symbol||(a.Symbol=function(a){return"@@Symbol("+a+"):"+f++});return a.Symbol}function g(a){return"@@"+a}function b(a,b){if(!a.iterator)if("function"=== typeof a["for"])a.iterator=a["for"]("iterator");else if(b.Set&&"function"===typeof(new b.Set)["@@iterator"])a.iterator="@@iterator";else if(b.Map)for(var f=Object.getOwnPropertyNames(b.Map.prototype),c=0;c<f.length;++c){var g=f[c];if("entries"!==g&&"size"!==g&&b.Map.prototype[g]===b.Map.prototype.entries){a.iterator=g;break}}else a.iterator="@@iterator"}function c(a){a.observable||(a.observable="function"===typeof a["for"]?a["for"]("observable"):"@@observable")}e=a(13);h.polyfillSymbol=l;h.ensureFor= k;var f=0;h.ensureSymbol=d;h.symbolForPolyfill=g;h.ensureIterator=b;h.ensureObservable=c;h.SymbolShim=l(e.root)},function(e,h){h.isArray=Array.isArray||function(a){return a&&"number"===typeof a.length}},function(e,h,a){var l=a(13),k=a(28),d=a(80),g=a(1),b=a(27),c=a(127);h.subscribeToResult=function(a,m,u,e){var h=new c.InnerSubscriber(a,u,e);if(!h.isUnsubscribed){if(m instanceof g.Observable){if(m._isScalar){h.next(m.value);h.complete();return}return m.subscribe(h)}if(k.isArray(m)){a=0;for(u=m.length;a< u&&!h.isUnsubscribed;a++)h.next(m[a]);h.isUnsubscribed||h.complete()}else{if(d.isPromise(m))return m.then(function(a){h.isUnsubscribed||(h.next(a),h.complete())},function(a){return h.error(a)}).then(null,function(a){l.root.setTimeout(function(){throw a;})}),h;if("function"===typeof m[b.SymbolShim.iterator]){for(a=0;a<m.length&&(h.next(m[a]),!h.isUnsubscribed);a++);h.isUnsubscribed||h.complete()}else if("function"===typeof m[b.SymbolShim.observable])if(m=m[b.SymbolShim.observable](),"function"!==typeof m.subscribe)h.error("invalid observable"); else return m.subscribe(new c.InnerSubscriber(a,u,e));else h.error(new TypeError("unknown type returned"))}}}},function(e,h,a){function l(){try{return d.apply(this,arguments)}catch(a){return k.errorObject.e=a,k.errorObject}}var k=a(20),d;h.tryCatch=function(a){d=a;return l}},function(e,h,a){function l(a){if(Array.isArray(a))return a;for(var b=a.length,f=Array(b),c=-1;++c<b;)f[c]={start:a.start(c),end:a.end(c),bitrate:0};return f}function k(a,b){return a.start<=b&&b<a.end}function d(a,b){for(var f= 0;f<b.length;f++)if(g(a,b[f]))return b[f];return null}function g(a,b){return k(a,b.start)||k(a,b.end)||k(b,a.start)}function b(a,b){return k(a,b.start)&&k(a,b.end)}function c(a,b,f){return{start:Math.min(a.start,b.start),end:Math.max(a.end,b.end),bitrate:f}}var f=a(3),m=1/60;h=function(){function a(b){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.ranges=b?l(b):[];this.length=this.ranges.length}a.prototype.start=function(a){return this.ranges[a].start};a.prototype.end= function(a){return this.ranges[a].end};a.prototype.hasRange=function(a,b){for(var f=a+b,c=0;c<this.ranges.length;c++){var g=this.ranges[c],d=g.start,g=g.end;if(d-a<=m&&a-g<=m&&d-f<=m&&f-g<=m)return this.ranges[c]}return null};a.prototype.getRange=function(a){for(var b=0;b<this.ranges.length;b++)if(k(this.ranges[b],a))return this.ranges[b];return null};a.prototype.getOuterRanges=function(a){for(var b=[],f=0;f<this.ranges.length;f++)k(this.ranges[f],a)||b.push(this.ranges[f]);return b};a.prototype.getGap= function(a){var b=this.getRange(a);return b?b.end-a:Infinity};a.prototype.getLoaded=function(a){var b=this.getRange(a);return b?a-b.start:0};a.prototype.getSize=function(a){return(a=this.getRange(a))?a.end-a.start:0};a.prototype.getNextRangeGap=function(a){for(var b=this.ranges,f=-1,c=void 0;++f<b.length;){var g=b[f].start;if(g>a){c=g;break}}return null!=c?c-a:Infinity};a.prototype.insert=function(a,d,k){var l=this.ranges;f(d<=k);if(d!=k){a={start:d,end:k,bitrate:a};for(d=0;d<l.length;d++){k=l[d]; var e=g(a,k),u=Math.abs(k.start-a.end)<m||Math.abs(k.end-a.start)<m;if(e||u)if(a.bitrate===k.bitrate)a=c(a,k,k.bitrate),l.splice(d--,1);else if(e)if(b(k,a))l.splice(++d,0,a),e=k.end,k.end=a.start,a={start:a.end,end:e,bitrate:k.bitrate};else if(b(a,k))l.splice(d--,1);else if(k.start<a.start)k.end=a.start;else{k.start=a.end;break}else break;else if(0===d){if(a.end<=l[0].start)break}else if(l[d-1].end<=a.start&&a.end<=k.start)break}l.splice(d,0,a);for(a=0;a<l.length;a++)d=l[a],d.start===d.end&&l.splice(a++, 1);for(a=1;a<l.length;a++)d=l[a-1],k=l[a],d.bitrate===k.bitrate&&(Math.abs(k.start-d.end)<m||Math.abs(k.end-d.start)<m)&&(d=c(d,k,k.bitrate),l.splice(--a,2,d))}this.length=this.ranges.length;return this.ranges};a.prototype.remove=function(b,f){this.intersect(new a([{start:0,end:b},{start:f,end:Infinity}]))};a.prototype.equals=function(a){var b;a:{b=this.ranges;a=a.ranges;for(var f=0;f<b.length;f++){var c=b[f],g=d(c,a);if(!g||g.start>c.start||g.end<c.end){b=!1;break a}}b=!0}return b};a.prototype.intersect= function(a){var b=this.ranges;a=a.ranges;for(var f=0;f<b.length;f++){var c=b[f],g=d(c,a);g?(g.start>c.start&&(c.start=g.start),g.end<c.end&&(c.end=g.end)):b.splice(f--,1)}this.length=this.ranges.length;return this.ranges};return a}();e.exports={bufferedToArray:l,BufferedRanges:h}},function(e,h,a){function l(a,b){if("function"!==typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a, enumerable:!1,writable:!0,configurable:!0}});b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function k(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function");}function d(a){return"number"==typeof a&&!isNaN(a)||!isNaN(+a)?!0:!1}var g=a(36).resolveURL,b=a(214),c=new b(100);h=function(){function a(b,c,g,l,e,h,p,r,y,w){k(this,a);this.id=g;this.ada=b;this.rep=c;this.time=d(e)?+e:-1;this.duration=d(h)?+h:-1;this.number=d(p)?+p:-1;this.media=l?""+l:"";this.range= Array.isArray(r)?r:null;this.indexRange=Array.isArray(y)?y:null;this.init=!!w}a.create=function(b,g,d,k,l,e,h,r,y,w){d=b.id+"_"+g.id+"_"+d;var z=c.get(d);if(z)return z;b=new a(b,g,d,k,l,e,h,r,y,w);c.set(d,b);return b};a.prototype.getId=function(){return this.id};a.prototype.getAdaptation=function(){return this.ada};a.prototype.getRepresentation=function(){return this.rep};a.prototype.getTime=function(){return this.time};a.prototype.getDuration=function(){return this.duration};a.prototype.getNumber= function(){return this.number};a.prototype.getMedia=function(){return this.media};a.prototype.getRange=function(){return this.range};a.prototype.getIndexRange=function(){return this.indexRange};a.prototype.isInitSegment=function(){return this.init};a.prototype.getResolvedURL=function(){return g(this.ada.rootURL,this.ada.baseURL,this.rep.baseURL)};return a}();a=function(a){function b(c,d,g,l,e){k(this,b);c=a.call(this,c,d,c.id+"_"+d.id+"_init",g,-1,-1,-1,l,e,!0);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return!c||"object"!==typeof c&&"function"!==typeof c?this:c}l(b,a);return b}(h);e.exports={Segment:h,InitSegment:a,clearSegmentCache:function(){c=new b(100)}}},function(e,h,a){var l=a(60),k=a(16);e.exports=function(a){return null!=a&&k(l(a))}},function(e,h){h.isFunction=function(a){return"function"===typeof a}},function(e,h,a){function l(){this.__listeners={}}var k=a(3);l.prototype.addEventListener=function(a,g){k("function"==typeof g,"eventemitter: second argument should be a function");this.__listeners[a]|| (this.__listeners[a]=[]);this.__listeners[a].push(g)};l.prototype.removeEventListener=function(a,g){if(0===arguments.length)this.__listeners={};else if(this.__listeners.hasOwnProperty(a))if(1===arguments.length)delete this.__listeners[a];else{var b=this.__listeners[a],c=b.indexOf(g);~c&&b.splice(c,1);b.length||delete this.__listeners[a]}};l.prototype.trigger=function(a,g){this.__listeners.hasOwnProperty(a)&&this.__listeners[a].slice().forEach(function(a){try{a(g)}catch(c){console.error(c,c.stack)}})}; l.prototype.on=l.prototype.addEventListener;l.prototype.off=l.prototype.removeEventListener;e.exports=l},function(e,h){var a=/^(?:[a-z]+:)?\/\//i,l=/\/[\.]{1,2}\//;e.exports={resolveURL:function(){var k=arguments.length;if(0===k)return"";for(var d="",g=0;g<k;g++){var b=arguments[g];"string"===typeof b&&""!==b&&(a.test(b)?d=b:("/"===b[0]&&(b=b.substr(1)),"/"===d[d.length-1]&&(d=d.substr(0,d.length-1)),d=d+"/"+b))}if(l.test(d)){k=[];d=d.split("/");g=0;for(b=d.length;g<b;g++)".."==d[g]?k.pop():"."!= d[g]&&k.push(d[g]);k=k.join("/")}else k=d;return k},parseBaseURL:function(a){var d=a.lastIndexOf("/");return 0<=d?a.substring(0,d+1):a}}},function(e,h,a){var l=a(101),k=a(62);e.exports=function(a,g,b){var c=a?a.length:0;b&&k(a,g,b)&&(g=!1);return c?l(a,g):[]}},function(e,h){var a=/^\d+$/;e.exports=function(l,k){l="number"==typeof l||a.test(l)?+l:-1;return-1<l&&0==l%1&&l<(null==k?9007199254740991:k)}},function(e,h,a){var l=a(33),k=a(17);h=Object.prototype;var d=h.hasOwnProperty,g=h.propertyIsEnumerable; e.exports=function(a){return k(a)&&l(a)&&d.call(a,"callee")&&!g.call(a,"callee")}},function(e,h,a){var l=function(a,d){function g(){this.constructor=a}for(var b in d)d.hasOwnProperty(b)&&(a[b]=d[b]);a.prototype=null===d?Object.create(d):(g.prototype=d.prototype,new g)};e=function(a){function d(g,b){a.call(this);this.value=g;this.scheduler=b;this._isScalar=!0}l(d,a);d.create=function(a,b){return new d(a,b)};d.dispatch=function(a){var b=a.value,c=a.subscriber;a.done?c.complete():(c.next(b),c.isUnsubscribed|| (a.done=!0,this.schedule(a)))};d.prototype._subscribe=function(a){var b=this.value,c=this.scheduler;if(c)return c.schedule(d.dispatch,0,{done:!1,value:b,subscriber:a});a.next(b);a.isUnsubscribed||a.complete()};return d}(a(1).Observable);h.ScalarObservable=e},function(e,h,a){var l=function(a,b){function g(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b):(g.prototype=b.prototype,new g)},k=a(78);e=a(1);var d=a(26),g=a(12),b=a(77);a=function(a){function f(f, l,e){void 0===f&&(f=0);a.call(this);this.period=-1;this.dueTime=0;k.isNumeric(l)?this.period=1>Number(l)&&1||Number(l):g.isScheduler(l)&&(e=l);g.isScheduler(e)||(e=d.asap);this.scheduler=e;this.dueTime=b.isDate(f)?+f-this.scheduler.now():f}l(f,a);f.create=function(a,b,c){void 0===a&&(a=0);return new f(a,b,c)};f.dispatch=function(a){var b=a.index,f=a.period,c=a.subscriber;c.next(b);if(!c.isUnsubscribed){if(-1===f)return c.complete();a.index=b+1;this.schedule(a,f)}};f.prototype._subscribe=function(a){return this.scheduler.schedule(f.dispatch, this.dueTime,{index:0,period:this.period,subscriber:a})};return f}(e.Observable);h.TimerObservable=a},function(e,h,a){var l=function(a,c){function f(){this.constructor=a}for(var g in c)c.hasOwnProperty(g)&&(a[g]=c[g]);a.prototype=null===c?Object.create(c):(f.prototype=c.prototype,new f)};e=a(24);var k=a(29);h.mergeAll=function(a){void 0===a&&(a=Number.POSITIVE_INFINITY);return this.lift(new d(a))};var d=function(){function a(b){this.concurrent=b}a.prototype.call=function(a){return new g(a,this.concurrent)}; return a}();h.MergeAllOperator=d;var g=function(a){function c(f,c){a.call(this,f);this.concurrent=c;this.hasCompleted=!1;this.buffer=[];this.active=0}l(c,a);c.prototype._next=function(a){this.active<this.concurrent?(this.active++,this.add(k.subscribeToResult(this,a))):this.buffer.push(a)};c.prototype._complete=function(){this.hasCompleted=!0;0===this.active&&0===this.buffer.length&&this.destination.complete()};c.prototype.notifyComplete=function(a){var b=this.buffer;this.remove(a);this.active--;0< b.length?this._next(b.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()};return c}(e.OuterSubscriber);h.MergeAllSubscriber=g},function(e,h,a){var l=a(152);h.multicast=function(a){return new l.ConnectableObservable(this,"function"===typeof a?a:function(){return a})}},function(e,h,a){var l=function(a,g){function b(){this.constructor=a}for(var c in g)g.hasOwnProperty(c)&&(a[c]=g[c]);a.prototype=null===g?Object.create(g):(b.prototype=g.prototype,new b)},k=a(13);e=function(a){function g(b, c){a.call(this);this.scheduler=b;this.work=c}l(g,a);g.prototype.execute=function(){if(this.isUnsubscribed)throw Error("How did did we execute a canceled Action?");this.work(this.state)};g.prototype.schedule=function(a,c){void 0===c&&(c=0);return this.isUnsubscribed?this:this._schedule(a,c)};g.prototype._schedule=function(a,c){var f=this;void 0===c&&(c=0);this.delay=c;this.state=a;var g=this.id;null!=g&&(this.id=void 0,k.root.clearTimeout(g));this.id=k.root.setTimeout(function(){f.id=null;var a=f.scheduler; a.actions.push(f);a.flush()},c);return this};g.prototype._unsubscribe=function(){var a=this.id,c=this.scheduler.actions,f=c.indexOf(this);null!=a&&(this.id=null,k.root.clearTimeout(a));-1!==f&&c.splice(f,1);this.scheduler=this.state=this.work=null};return g}(a(5).Subscription);h.FutureAction=e},function(e,h,a){var l=function(a,b){function c(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};e=a(10);var k=a(81), d=a(76);a=function(a){function b(b){a.call(this);this._value=b}l(b,a);b.prototype.getValue=function(){if(this.hasErrored)k.throwError(this.errorValue);else if(this.isUnsubscribed)k.throwError(new d.ObjectUnsubscribedError);else return this._value};Object.defineProperty(b.prototype,"value",{get:function(){return this.getValue()},enumerable:!0,configurable:!0});b.prototype._subscribe=function(b){var f=a.prototype._subscribe.call(this,b);f&&!f.isUnsubscribed&&b.next(this._value);return f};b.prototype._next= function(b){a.prototype._next.call(this,this._value=b)};b.prototype._error=function(b){this.hasErrored=!0;a.prototype._error.call(this,this.errorValue=b)};return b}(e.Subject);h.BehaviorSubject=a},function(e,h,a){e=a(27);h.rxSubscriber=e.SymbolShim["for"]("rxSubscriber")},function(e,h){h.noop=function(){}},function(e,h,a){function l(a,b,f){a.id=a.id||y++;var c=a.adaptations,c=c.concat(f||[]),c=c.map(function(a){return k(a,b)}),c=c.filter(function(a){return 0>w.indexOf(a.type)?(u.info("not supported adaptation type", a.type),!1):!0});n(0<c.length);f={};for(var g=0;g<c.length;g++){var d=c[g],m=d.type;f[m]=f[m]||[];f[m].push(d)}a.adaptations=f;return a}function k(a,f){n("undefined"!=typeof a.id);q(a,f);var c={};r.forEach(function(b){b in a&&(c[b]=a[b])});var g=a.representations.map(function(a){n("undefined"!=typeof a.id);q(a,c);var b=a.index;n(b);b.timescale||(b.timescale=1);a.bitrate||(a.bitrate=1);"mp4a.40.02"==a.codecs&&(a.codecs="mp4a.40.2");return a}).sort(function(a,b){return a.bitrate-b.bitrate}),d=a.type, k=a.mimeType;k||(k=g[0].mimeType);n(k);a.mimeType=k;d||(d=a.type=k.split("/")[0]);if("video"==d||"audio"==d)g=g.filter(function(a){return p(b(a))});n(0<g.length,"manifest: no compatible representation for this adaptation");a.representations=g;a.bitrates=g.map(function(a){return a.bitrate});return a}function d(a){Array.isArray(a)||(a=[a]);return x(a.map(function(a){var b=a.mimeType,f=a.url,c=a.language;a=a.languages;c&&(a=[c]);return a.map(function(a){return{id:y++,type:"text",lang:a,mimeType:b,rootURL:f, baseURL:"",representations:[{id:y++,mimeType:b,index:{indexType:"template",duration:Number.MAX_VALUE,timescale:1,startNumber:0}}]}})}))}function g(a,b){for(var c in a)if(b.hasOwnProperty(c)){var d=a[c],k=b[c];"string"==typeof d||"number"==typeof d||"object"==("undefined"===typeof d?"undefined":f(d))&&d instanceof Date?a[c]=k:Array.isArray(d)?(d.length=0,Array.prototype.push.apply(d,k)):a[c]=g(d,k)}return a}function b(a){return a.mimeType+';codecs="'+a.codecs+'"'}function c(a,b){var f=a.adaptations; return(f=f&&f[b])?f:[]}var f="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol?"symbol":typeof a},m=Object.assign||function(a){for(var b=1;b<arguments.length;b++){var f=arguments[b],c;for(c in f)Object.prototype.hasOwnProperty.call(f,c)&&(a[c]=f[c])}return a},u=a(4),n=a(3),q=a(23),x=a(37),v=a(36).parseBaseURL,p=a(14).isCodecSupported,r="profiles width height frameRate audioSamplingRate mimeType segmentProfiles codecs maximumSAPPeriod maxPlayoutRate codingDependency index".split(" "), y=0,w=["audio","video","text"];e.exports={normalizeManifest:function(a,b,f){n(b.transportType);b.id=b.id||y++;b.type=b.type||"static";var c=b.locations;c&&c.length||(b.locations=[a]);b.isLive="dynamic"==b.type;var g={rootURL:v(b.locations[0]),baseURL:b.baseURL,isLive:b.isLive};f&&(f=d(f));a=b.periods.map(function(a){return l(a,g,f)});b=m({},b,a[0]);b.periods=null;b.duration||(b.duration=Infinity);b.isLive&&(b.suggestedPresentationDelay=b.suggestedPresentationDelay||15,b.availabilityStartTime=b.availabilityStartTime|| 0);return b},mergeManifestsIndex:function(a,b){var f=a.adaptations,c=b.adaptations,d=function(a){var b=c[a];f[a].forEach(function(a,f){g(a.index,b[f].index)})},k;for(k in f)d(k);return a},mutateManifestLiveGap:function(a){var b=1>=arguments.length||void 0===arguments[1]?1:arguments[1];a.isLive&&(a.presentationLiveGap+=b)},getCodec:b,getAdaptations:function(a){a=a.adaptations;if(!a)return[];var f=[],c;for(c in a){var d=a[c];f.push({type:c,adaptations:d,codec:b(d[0].representations[0])})}return f}, getAdaptationsByType:c,getAvailableSubtitles:function(a){return c(a,"text").map(function(a){return a.lang})},getAvailableLanguages:function(a){return c(a,"audio").map(function(a){return a.lang})}}},function(e,h){function a(a){return a*(1+.3*(2*Math.random()-1))}e.exports={getFuzzedDelay:a,getBackedoffDelay:function(l){return a(l*Math.pow(2,(1>=arguments.length||void 0===arguments[1]?1:arguments[1])-1))}}},function(e,h){e.exports=function(a,l,k){function d(){var g=c-Date.now();if(0<g)b=setTimeout(d, g);else switch(b=null,f.length){case 0:return a();case 1:return a(f[0]);case 2:return a(f[0],f[1]);case 3:return a(f[0],f[1],f[2]);default:return a.apply(null,f)}}function g(){var a=arguments.length,k=0;for(f=Array(a);k<a;k++)f[k]=arguments[k];if(m&&!e)return e=!0,c=Date.now(),d();a=c;c=Date.now()+l;if(!b||c<a)b&&clearTimeout(b),b=setTimeout(d,l);return g}var b=null,c=0,f=[],m=!(!k||!k.leading),e=!1;g.isWaiting=function(){return!!b};g.dispose=function(){b&&(clearTimeout(b),b=null)};return g}},function(e, h,a){(function(l){function k(a,b,f){var c=3>=arguments.length||void 0===arguments[3]?null:arguments[3];this.name="RequestError";this.url=a;this.xhr=b;this.code=b.status;this.reason=c;this.message="request: "+f+" ("+a+")";Error.captureStackTrace&&Error.captureStackTrace(this,k)}function d(a,b){var f=b.code,c=b.method,g=b.message;this.name="RestCallMethodError";this.url=a;this.code=f;this.message="restmethodcall: webservice error status "+f+" ("+a+")"+(c?" ("+c+")":"")+(g?"\n"+g:"");Error.captureStackTrace&& Error.captureStackTrace(this,d)}function g(a,b,f){a=a.querySelector("RestCallResult");var c=+a.querySelector("Status").textContent;if(0>c)throw new d(b,{code:c,method:f});return{output:a.querySelector("Output"),status:c}}function b(a){return"rest-call-method"==a.format?m(a):n.create(function(b){function f(a){var c=a.target,d=c.status;if(200>d||300<=d)return b.error(new k(g,c,c.statusText));var d=Date.now()-v,m;m="document"==e?(new l.DOMParser).parseFromString(c.responseText,"text/xml"):c.response; if("json"==e&&"string"==typeof m)try{m=JSON.parse(m)}catch(n){m=null}if(null==m)return b.error(new k(g,c,'null response with format "'+e+'" (error while parsing or wrong content-type)'));if(h){var q;if(u){q=u;for(var p={},x,y=0;y<q.length;y++)x=q[y],p[x]=c.getResponseHeader(x);q=p}b.next({blob:m,size:a.total,duration:d,headers:q,url:c.responseURL||g,xhr:c})}else b.next(m);b.complete()}function c(a){b.error(new k(g,a,"error event"))}var g=a.url,d=a.data,m=a.headers,e=a.format,h=a.withMetadata,u=a.responseHeaders, n=new XMLHttpRequest;n.open(a.method||"GET",g,!0);n.responseType="document"==e?"text":e||"text";if(m)for(var q in m)n.setRequestHeader(q,m[q]);n.addEventListener("load",f,!1);n.addEventListener("error",c,!1);var v=Date.now();n.send(d);return function(){var a=n.readyState;0<a&&4>a&&(n.removeEventListener("load",f),n.removeEventListener("error",c),n.abort());n=null}})}function c(a){return(a||"").toString().replace(q,function(a){return x[a]})}function f(a){var b="",g;for(g in a)var d=a[g],d="object"== ("undefined"===typeof d?"undefined":h(d))?f(d):c(d),b=b+("<"+g+">"+d+"</"+g+">");return b}function m(a){a.method="POST";a.headers={"Content-Type":"application/xml"};a.data=v.replace("{payload}",f(a.data));a.format="document";return b(a).map(function(b){return g(b,a.url,a.ScriptInfo)})}var h="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol?"symbol":typeof a},n=a(1).Observable;k.prototype= Error();d.prototype=Error();var q=/[&<>]/g,x={"&":"&amp;","<":"&lt;",">":"&gt;"},v='<RestCallMethod xmlns:i="http://www.w3.org/2001/XMLSchema-instance">{payload}</RestCallMethod>';b.escapeXml=c;b.RequestError=k;b.RestCallMethodError=d;b.RestCallResult=g;b.getNodeTextContent=function(a,b){var f=a.querySelector(b);return f&&f.textContent};e.exports=b}).call(h,function(){return this}())},function(e,h){var a=Math.max;e.exports=function(l,k){if("function"!=typeof l)throw new TypeError("Expected a function"); k=a(void 0===k?l.length-1:+k||0,0);return function(){for(var d=arguments,g=-1,b=a(d.length-k,0),c=Array(b);++g<b;)c[g]=d[k+g];switch(k){case 0:return l.call(this,c);case 1:return l.call(this,d[0],c);case 2:return l.call(this,d[0],d[1],c)}b=Array(k+1);for(g=-1;++g<k;)b[g]=d[g];b[k]=c;return l.apply(this,b)}}},function(e,h,a){var l=a(7);e.exports=function(a,d,g){if(null!=a){void 0!==g&&g in l(a)&&(d=[g]);g=0;for(var b=d.length;null!=a&&g<b;)a=a[d[g++]];return g&&g==b?a:void 0}}},function(e,h,a){function l(a, c,f,m,e,h){return a===c?!0:null==a||null==c||!d(a)&&!g(c)?a!==a&&c!==c:k(a,c,l,f,m,e,h)}var k=a(106),d=a(9),g=a(17);e.exports=l},function(e,h){e.exports=function(a){return function(l){return null==l?void 0:l[a]}}},function(e,h,a){var l=a(66);e.exports=function(a,d,g){if("function"!=typeof a)return l;if(void 0===d)return a;switch(g){case 1:return function(b){return a.call(d,b)};case 3:return function(b,c,f){return a.call(d,b,c,f)};case 4:return function(b,c,f,g){return a.call(d,b,c,f,g)};case 5:return function(b, c,f,g,l){return a.call(d,b,c,f,g,l)}}return function(){return a.apply(d,arguments)}}},function(e,h,a){var l=a(60),k=a(16),d=a(7);e.exports=function(a,b){return function(c,f){var m=c?l(c):0;if(!k(m))return a(c,f);for(var e=b?m:-1,h=d(c);(b?e--:++e<m)&&!1!==f(h[e],e,h););return c}}},function(e,h,a){var l=a(7);e.exports=function(a){return function(d,g,b){var c=l(d);b=b(d);for(var f=b.length,m=a?f:-1;a?m--:++m<f;){var e=b[m];if(!1===g(c[e],e,c))break}return d}}},function(e,h,a){var l=a(95),k=a(99),d= a(100),g=a(8);e.exports=function(a,c){return function(f,m,e){m=l(m,e,3);return g(f)?(m=d(f,m,c),-1<m?f[m]:void 0):k(f,m,a)}}},function(e,h,a){h=a(55)("length");e.exports=h},function(e,h,a){var l=a(121);e.exports=function(a,d){var g=null==a?void 0:a[d];return l(g)?g:void 0}},function(e,h,a){var l="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol?"symbol":typeof a},k=a(33),d=a(38),g=a(9); e.exports=function(a,c,f){if(!g(f))return!1;var m="undefined"===typeof c?"undefined":l(c);return("number"==m?k(f)&&d(c,f.length):"string"==m&&c in f)?(c=f[c],a===a?a===c:c!==c):!1}},function(e,h,a){var l="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol?"symbol":typeof a},k=a(8),d=a(7),g=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,b=/^\w*$/;e.exports=function(a,f){var m="undefined"=== typeof a?"undefined":l(a);return"string"==m&&b.test(a)||"number"==m?!0:k(a)?!1:!g.test(a)||null!=f&&a in d(f)}},function(e,h,a){var l=a(9);e.exports=function(a){return a===a&&!l(a)}},function(e,h,a){var l=a(112),k=a(8),d=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g,g=/\\(\\)?/g;e.exports=function(a){if(k(a))return a;var c=[];l(a).replace(d,function(a,b,d,k){c.push(d?k.replace(g,"$1"):b||a)});return c}},function(e,h){e.exports=function(a){return a}},function(e,h,a){e=a(1); a=a(157);e.Observable.prototype["catch"]=a._catch},function(e,h,a){e=a(1);a=a(75);e.Observable.prototype.mergeMap=a.mergeMap;e.Observable.prototype.flatMap=a.mergeMap},function(e,h,a){e=a(1);a=a(173);e.Observable.prototype.startWith=a.startWith},function(e,h,a){e=a(1);a=a(175);e.Observable.prototype.take=a.take},function(e,h,a){var l=function(a,c){function f(){this.constructor=a}for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d]);a.prototype=null===c?Object.create(c):(f.prototype=c.prototype,new f)}; e=a(1);var k=a(30),d=a(20),g=a(5);a=function(a){function c(f,c,d){a.call(this);this.sourceObj=f;this.eventName=c;this.selector=d}l(c,a);c.create=function(a,b,d){return new c(a,b,d)};c.setupSubscription=function(a,b,d,k){var e;if(a&&"[object NodeList]"===a.toString()||a&&"[object HTMLCollection]"===a.toString())for(var l=0,h=a.length;l<h;l++)c.setupSubscription(a[l],b,d,k);else a&&"function"===typeof a.addEventListener&&"function"===typeof a.removeEventListener?(a.addEventListener(b,d),e=function(){return a.removeEventListener(b, d)}):a&&"function"===typeof a.on&&"function"===typeof a.off?(a.on(b,d),e=function(){return a.off(b,d)}):a&&"function"===typeof a.addListener&&"function"===typeof a.removeListener&&(a.addListener(b,d),e=function(){return a.removeListener(b,d)});k.add(new g.Subscription(e))};c.prototype._subscribe=function(a){var b=this.selector;c.setupSubscription(this.sourceObj,this.eventName,b?function(){for(var c=[],g=0;g<arguments.length;g++)c[g-0]=arguments[g];c=k.tryCatch(b).apply(void 0,c);c===d.errorObject? a.error(d.errorObject.e):a.next(c)}:function(b){return a.next(b)},a)};return c}(e.Observable);h.FromEventObservable=a},function(e,h,a){var l=function(a,g){function b(){this.constructor=a}for(var c in g)g.hasOwnProperty(c)&&(a[c]=g[c]);a.prototype=null===g?Object.create(g):(b.prototype=g.prototype,new b)};e=a(1);var k=a(47);a=function(a){function g(){a.call(this)}l(g,a);g.create=function(){return new g};g.prototype._subscribe=function(a){k.noop()};return g}(e.Observable);h.NeverObservable=a},function(e, h,a){function l(a){var c=a.value;a=a.subscriber;a.isUnsubscribed||(a.next(c),a.complete())}function k(a){var c=a.err;a=a.subscriber;a.isUnsubscribed||a.error(c)}var d=function(a,c){function f(){this.constructor=a}for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d]);a.prototype=null===c?Object.create(c):(f.prototype=c.prototype,new f)},g=a(13);e=function(a){function c(c,d){void 0===d&&(d=null);a.call(this);this.promise=c;this.scheduler=d}d(c,a);c.create=function(a,b){void 0===b&&(b=null);return new c(a, b)};c.prototype._subscribe=function(a){var b=this,c=this.promise,d=this.scheduler;if(null==d)this._isScalar?a.isUnsubscribed||(a.next(this.value),a.complete()):c.then(function(c){b.value=c;b._isScalar=!0;a.isUnsubscribed||(a.next(c),a.complete())},function(b){a.isUnsubscribed||a.error(b)}).then(null,function(a){g.root.setTimeout(function(){throw a;})});else if(this._isScalar){if(!a.isUnsubscribed)return d.schedule(l,0,{value:this.value,subscriber:a})}else c.then(function(c){b.value=c;b._isScalar= !0;a.isUnsubscribed||a.add(d.schedule(l,0,{value:c,subscriber:a}))},function(b){a.isUnsubscribed||a.add(d.schedule(k,0,{err:b,subscriber:a}))}).then(null,function(a){g.root.setTimeout(function(){throw a;})})};return c}(a(1).Observable);h.PromiseObservable=e},function(e,h,a){function l(){for(var a=[],c=0;c<arguments.length;c++)a[c-0]=arguments[c];c=null;k.isScheduler(a[a.length-1])&&(c=a.pop());return(new d.ArrayObservable(a,c)).lift(new g.MergeAllOperator(1))}var k=a(12),d=a(19),g=a(42);h.concat= function(){for(var a=[],c=0;c<arguments.length;c++)a[c-0]=arguments[c];return l.apply(void 0,[this].concat(a))};h.concatStatic=l},function(e,h,a){var l=function(a,c){function f(){this.constructor=a}for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d]);a.prototype=null===c?Object.create(c):(f.prototype=c.prototype,new f)},k=a(29);e=a(24);h.mergeMap=function(a,c,f){void 0===f&&(f=Number.POSITIVE_INFINITY);return this.lift(new d(a,c,f))};var d=function(){function a(b,f,d){void 0===d&&(d=Number.POSITIVE_INFINITY); this.project=b;this.resultSelector=f;this.concurrent=d}a.prototype.call=function(a){return new g(a,this.project,this.resultSelector,this.concurrent)};return a}();h.MergeMapOperator=d;var g=function(a){function c(c,d,g,k){void 0===k&&(k=Number.POSITIVE_INFINITY);a.call(this,c);this.project=d;this.resultSelector=g;this.concurrent=k;this.hasCompleted=!1;this.buffer=[];this.index=this.active=0}l(c,a);c.prototype._next=function(a){this.active<this.concurrent?this._tryNext(a):this.buffer.push(a)};c.prototype._tryNext= function(a){var b,c=this.index++;try{b=this.project(a,c)}catch(d){this.destination.error(d);return}this.active++;this._innerSub(b,a,c)};c.prototype._innerSub=function(a,b,c){this.add(k.subscribeToResult(this,a,b,c))};c.prototype._complete=function(){this.hasCompleted=!0;0===this.active&&0===this.buffer.length&&this.destination.complete()};c.prototype.notifyNext=function(a,b,c,d,g){this.resultSelector?this._notifyResultSelector(a,b,c,d):this.destination.next(b)};c.prototype._notifyResultSelector=function(a, b,c,d){var g;try{g=this.resultSelector(a,b,c,d)}catch(k){this.destination.error(k);return}this.destination.next(g)};c.prototype.notifyComplete=function(a){var b=this.buffer;this.remove(a);this.active--;0<b.length?this._next(b.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()};return c}(e.OuterSubscriber);h.MergeMapSubscriber=g},function(e,h){var a=function(a,d){function g(){this.constructor=a}for(var b in d)d.hasOwnProperty(b)&&(a[b]=d[b]);a.prototype=null===d?Object.create(d): (g.prototype=d.prototype,new g)},l=function(k){function d(){k.call(this,"object unsubscribed");this.name="ObjectUnsubscribedError"}a(d,k);return d}(Error);h.ObjectUnsubscribedError=l},function(e,h){h.isDate=function(a){return a instanceof Date&&!isNaN(+a)}},function(e,h,a){var l=a(28);h.isNumeric=function(a){return!l.isArray(a)&&0<=a-parseFloat(a)+1}},function(e,h){var a="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&& a.constructor===Symbol?"symbol":typeof a};h.isObject=function(e){return null!=e&&"object"===("undefined"===typeof e?"undefined":a(e))}},function(e,h){h.isPromise=function(a){return a&&"function"!==typeof a.subscribe&&"function"===typeof a.then}},function(e,h){h.throwError=function(a){throw a;}},function(e,h,a){function l(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function");}function k(a){this.name="EMEError";this.message=a&&a.message||"eme: unknown error";this.reason= a&&a.reason||a;this.stack=Error().stack}function d(a){this.name="GenerateRequestError";this.message="";this.stack=Error().stack;this.session=a}function g(a){if("number"==typeof a)return a;for(var b=0,c=void 0,f=0;f<a.length;f++)c=a[f],b=(b<<5)-b+c,b&=b;return b}function b(a,b,c){return{type:"eme",value:y({name:a,session:b},c)}}function c(a){if(!U||!W||J())return null;var b=Y;return(a=D(a,function(a){return a.type!==U.type||a.persistentLicense&&"required"!=b.persistentState||a.distinctiveIdentifierRequired&& "required"!=b.distinctiveIdentifier?!1:!0}))?{keySystem:a,keySystemAccess:new H(U,W,Y)}:null}function f(a){var b=["temporary"],c="optional",f="optional";a.persistentLicense&&(c="required",b.push("persistent-license"));a.persistentStateRequired&&(c="required");a.distinctiveIdentifierRequired&&(f="required");return{videoCapabilities:void 0,audioCapabilities:void 0,initDataTypes:["cenc"],distinctiveIdentifier:f,persistentState:c,sessionTypes:b}}function m(a){var b=c(a);if(b)return w.debug("eme: found compatible keySystem quickly", b),A.of(b);var d=C(a.map(function(a){return P[a.type].map(function(b){return{keyType:b,keySystem:a}})}));return A.create(function(a){function b(k){if(!c)if(k>=d.length)a.onError(T());else{var m=d[k],e=m.keyType,l=m.keySystem,h=[f(l)];w.debug("eme: request keysystem access "+e+","+(k+1+" of "+d.length),h);g=L(e,h).subscribe(function(b){w.info("eme: found compatible keysystem",e,h);a.next({keySystem:l,keySystemAccess:b});a.complete()},function(){w.debug("eme: rejected access to keysystem",e,h);g=null; b(k+1)})}}var c=!1,g=null;b(0);(function(){c=!0;g&&g.unsubscribe()})})}function u(a,b,c){var f=Z,d=W;return t(c.createMediaKeys()).flatMap(function(g){W=g;Y=c.getConfiguration();U=b;Z=a;if(a.mediaKeys===g)return A.of(g);d&&d!==W&&S.dispose();var k=void 0;f&&f!==Z?(w.debug("eme: unlink old video element and set mediakeys"),k=F(f,null).concat(F(Z,g))):(w.debug("eme: set mediakeys"),k=F(Z,g));return k.mapTo(g)})}function n(a,b,c,f){w.debug("eme: create a new "+b+" session");var d=a.createSession(b); a=p(d,c)["finally"](function(){S.deleteAndClose(d);V["delete"](f)}).publish();return{session:d,sessionEvents:a}}function q(a,c,f,g,k){a=n(a,f,c,k);var m=a.session;a=a.sessionEvents;S.add(k,m,a);w.debug("eme: generate request",g,k);g=t(m.generateRequest(g,k))["catch"](function(){throw new d(m);})["do"](function(){"persistent-license"==f&&V.add(k,m)}).mapTo(b("generated-request",m,{initData:k,initDataType:g}));return E(a,g)}function x(a,b,c,f,g){return q(a,b,c,f,g)["catch"](function(k){if(!(k instanceof d))throw k;var m=S.getFirst();if(!m)throw k;w.warn("eme: could not create a new session, retry after closing a currently loaded session",k);return S.deleteAndClose(m).flatMap(function(){return q(a,b,c,f,g)})})}function v(a,c,f,d,g){w.debug("eme: load persisted session",f);var k=n(a,"persistent-license",c,g),m=k.session,e=k.sessionEvents;return t(m.load(f))["catch"](function(){return A.of(!1)}).flatMap(function(k){if(k)return S.add(g,m,e),V.add(g,m),e.startWith(b("loaded-session",m,{storedSessionId:f})); w.warn("eme: no data stored for the loaded session, do fallback",f);S.deleteById(f);V["delete"](g);m.sessionId&&m.remove();return x(a,c,"persistent-license",d,g).startWith(b("loaded-session-failed",m,{storedSessionId:f}))})}function p(a,c){w.debug("eme: handle message events",a);var f=void 0,d=M(a).map(function(a){return r("eme: keyerror event "+a.errorCode+" / "+a.systemCode,a)}),g=R(a).flatMap(function(b){f=b.sessionId;w.debug("eme: keystatuseschange event",f,a,b);a.keyStatuses.forEach(function(a, b){var c=Q[b]||Q[a];c&&r(c)});if(!c.onKeyStatusesChange)return w.info("eme: keystatuseschange event not handled"),O();var d=void 0;try{d=c.onKeyStatusesChange(b,a)}catch(g){d=A["throw"](g)}return t(d)["catch"](function(a){return r("eme: onKeyStatusesChange has failed (reason:"+(a&&a.message||"unknown")+")",a)})}),k=I(a).flatMap(function(b){f=b.sessionId;var d=new Uint8Array(b.message),g=b.messageType||"license-request";w.debug("eme: event message type "+g,a,b);b=B(function(){return c.getLicense(d, g)},{totalRetry:3,retryDelay:100});return t(b())["catch"](function(a){return r("eme: getLicense has failed (reason: "+(a&&a.message||"unknown")+")",a)})}),g=E(k,g).concatMap(function(c){w.debug("eme: update session",f,c);return t(a.update(c,f))["catch"](function(a){return r("eme: error on session update "+f,a)}).mapTo(b("session-update",a,{updatedWith:c}))}),d=E(g,d);return a.closed?d.takeUntil(t(a.closed)):d}function r(a,b){var c=Error(a);b&&(c.reason=b);w.error(a,b);throw c;}var y=Object.assign|| function(a){for(var b=1;b<arguments.length;b++){var c=arguments[b],f;for(f in c)Object.prototype.hasOwnProperty.call(c,f)&&(a[f]=c[f])}return a},w=a(4),z=a(3),D=a(22),C=a(37),t=a(86),B=a(15).retryWithBackoff,A=a(1).Observable,O=a(6).EmptyObservable.create,G=a(25).combineLatestStatic,E=a(11).mergeStatic;h=a(14);var H=h.KeySystemAccess,L=h.requestMediaKeySystemAccess,F=h.setMediaKeys;a=h.emeEvents;var J=h.shouldRenewMediaKeys,K=a.onEncrypted,I=a.onKeyMessage,M=a.onKeyError,R=a.onKeyStatusesChange,P= {clearkey:["webkit-org.w3.clearkey","org.w3.clearkey"],widevine:["com.widevine.alpha"],playready:["com.youtube.playready","com.microsoft.playready"]},Q={expired:"eme: a required key has expired and the content cannot be decrypted.","internal-error":"eme: an unknown error has occurred in the CDM."};k.prototype=Error();d.prototype=Error();var T=function(){Error("eme: could not find a compatible key system")};h=function(){function a(){l(this,a);this._entries=[]}a.prototype.getFirst=function(){if(0<this._entries.length)return this._entries[0].session}; a.prototype.get=function(a){a=g(a);var b=D(this._entries,function(b){return b.initData===a});return b?b.session:null};a.prototype.add=function(a,b,c){a=g(a);var f=this.get(a);f&&this.deleteAndClose(f);c=c.connect();a={session:b,initData:a,eventSubscription:c};w.debug("eme-mem-store: add session",a);this._entries.push(a)};a.prototype.deleteById=function(a){var b=D(this._entries,function(b){return b.session.sessionId===a});return b?this["delete"](b.session):null};a.prototype["delete"]=function(a){var b= D(this._entries,function(b){return b.session===a});if(!b)return null;var c=b.session,f=b.eventSubscription;w.debug("eme-mem-store: delete session",b);b=this._entries.indexOf(b);this._entries.splice(b,1);f.unsubscribe();return c};a.prototype.deleteAndClose=function(a){return(a=this["delete"](a))?(w.debug("eme-mem-store: close session",a),t(a.close())["catch"](function(){return A.of(null)})):A.of(null)};a.prototype.dispose=function(){var a=this,b=this._entries.map(function(b){return a.deleteAndClose(b.session)}); this._entries=[];return E.apply(null,b)};return a}();var V=new (function(){function a(b){l(this,a);this.setStorage(b)}a.prototype.setStorage=function(a){if(this._storage!==a){z(a,"eme: no licenseStorage given for keySystem with persistentLicense");z.iface(a,"licenseStorage",{save:"function",load:"function"});this._storage=a;try{this._entries=this._storage.load(),z(Array.isArray(this._entries))}catch(b){w.warn("eme-persitent-store: could not get entries from license storage",b),this.dispose()}}};a.prototype.get= function(a){a=g(a);return D(this._entries,function(b){return b.initData===a})||null};a.prototype.add=function(a,b){var c=b&&b.sessionId;if(c){a=g(a);var f=this.get(a);f&&f.sessionId===c||(f&&this["delete"](a),w.info("eme-persitent-store: add new session",c,b),this._entries.push({sessionId:c,initData:a}),this._save())}};a.prototype["delete"]=function(a){a=g(a);var b=D(this._entries,function(b){return b.initData===a});b&&(w.warn("eme-persitent-store: delete session from store",b),b=this._entries.indexOf(b), this._entries.splice(b,1),this._save())};a.prototype.dispose=function(){this._entries=[];this._save()};a.prototype._save=function(){try{this._storage.save(this._entries)}catch(a){w.warn("eme-persitent-store: could not save licenses in localStorage")}};return a}())({load:function(){return[]},save:function(){}}),S=new h,W=void 0,Y=void 0,U=void 0,Z=void 0;e.exports={createEME:function(a,c){function f(c,d){var g=d.keySystem,k=d.keySystemAccess;g.persistentLicense&&V.setStorage(g.licenseStorage);w.info("eme: encrypted event", c);return u(a,g,k).flatMap(function(a){a:{var f=k.getConfiguration(),d=c.initDataType,m=new Uint8Array(c.initData),e=S.get(m);if(e&&e.sessionId)w.debug("eme: reuse loaded session",e.sessionId),a=A.of(b("reuse-session",e));else{f=(e=(f=f.sessionTypes)&&0<=f.indexOf("persistent-license"))&&g.persistentLicense?"persistent-license":"temporary";if(e&&g.persistentLicense&&(e=V.get(m))){a=v(a,g,e.sessionId,d,m);break a}a=x(a,g,f,d,m)}}return a})}return G(K(a),m(c)).take(1).flatMap(function(a){return f(a[0], a[1])})["catch"](function(a){throw new k(a);})},EMEError:k,getCurrentKeySystem:function(){return U&&U.type},onEncrypted:K,dispose:function(){U=W=null;S.dispose()}}},function(e,h,a){function l(a){this.name="OutOfIndexError";this.type=a;this.message="out of range in index "+a}function k(a){switch(a.indexType){case "template":return b;case "timeline":return c;case "list":return f;case "base":return m;default:throw Error("index-handler: unrecognized indexType "+a.indexType);}}a(3);var d=a(48).getAdaptationsByType, g=a(32).InitSegment,b=a(195),c=a(84),f=a(194),m=a(193);l.prototype=Error();h=function(){function a(b,c){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.adaptation=b;this.representation=c;this.index=c.index;this.handler=new (k(this.index))(b,c,this.index)}a.prototype.getInitSegment=function(){var a=this.index.initialization||{};return new g(this.adaptation,this.representation,a.media,a.range,this.index.indexRange)};a.prototype.normalizeRange=function(a,b,c){var f= this.index.presentationTimeOffset||0,d=this.index.timescale||1;b||(b=0);c||(c=0);b=Math.min(b,c);return{time:a*d-f,up:(a+b)*d-f,to:(a+c)*d-f}};a.prototype.getSegments=function(a,b,c){a=this.normalizeRange(a,b,c);b=a.up;c=a.to;if(!this.handler.checkRange(a.time))throw new l(this.index.indexType);return this.handler.getSegments(b,c)};a.prototype.insertNewSegments=function(a,b){for(var c=[],f=0;f<a.length;f++)this.handler.addSegment(a[f],b)&&c.push(a[f]);return c};a.prototype.setTimescale=function(a){var b= this.index;return b.timescale!==a?(b.timescale=a,!0):!1};a.prototype.scale=function(a){return a/this.index.timescale};return a}();e.exports={OutOfIndexError:l,IndexHandler:h,getLiveEdge:function(a){var b=d(a,"video")[0].representations[0].index;return k(b).getLiveEdge(b,a)}}},function(e,h,a){function l(a){var g=a.ts,b=a.d;a=a.r;return-1===b?g:g+(a+1)*b}var k=a(32).Segment;h=function(){function a(g,b,c){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.adaptation= g;this.representation=b;this.index=c;this.timeline=c.timeline}a.getLiveEdge=function(a,b){var c=l(a.timeline[a.timeline.length-1])/a.timescale-b.suggestedPresentationDelay;return Math.max(a.timeline[0].ts/a.timescale+1,c)};a.prototype.createSegment=function(a,b,c){return k.create(this.adaptation,this.representation,a,this.index.media,a,c,0,b,null,!1)};a.prototype.calculateRepeat=function(a,b){var c=a.r||0;0>c&&(c=Math.ceil(((b?b.t:Infinity)-a.ts)/a.d)-1);return c};a.prototype.checkRange=function(a){var b= this.timeline[this.timeline.length-1];if(!b)return!0;0>b.d&&(b={ts:b.ts,d:0,r:b.r});return a<=l(b)};a.prototype.getSegmentIndex=function(a){for(var b=this.timeline,c=0,f=b.length;c<f;){var d=c+f>>>1;b[d].ts<a?c=d+1:f=d}return 0<c?c-1:c};a.prototype.getSegmentNumber=function(a,b,c){a=b-a;return 0<a?Math.floor(a/c):0};a.prototype.getSegments=function(a,b){var c=this.index.timeline,f=[],d=c.length,k=this.getSegmentIndex(a)-1,e=c.length&&c[0].d||0;a:for(;!(++k>=d);){var l=c[k],h=l.d,v=l.ts,p=l.range, e=Math.max(e,h);if(0>h){v+e<b&&f.push(this.createSegment(v,p,void 0));break}for(var l=this.calculateRepeat(l,c[k+1]),r=this.getSegmentNumber(v,a,h),y=void 0;(y=v+r*h)<b;)if(r++<=l)f.push(this.createSegment(y,p,h));else continue a;break}return f};a.prototype.addSegment=function(a,b){var c=this.timeline,f=c.length,d=c[f-1];if(b&&a.ts===b.ts){var k=a.ts+a.d,e=k-(d.ts+d.d*d.r);if(0>=e)return!1;-1===d.d&&((f=c[f-2])&&f.d===e?(f.r++,c.pop()):d.d=e);c.push({d:-1,ts:k,r:0});return!0}return a.ts>=l(d)?(d.d=== a.d?d.r++:c.push({d:a.d,ts:a.ts,r:0}),!0):!1};return a}();e.exports=h},function(e,h,a){function l(a,f){var d=a.currentTime,k=new g(a.buffered);return new b(d,k,a.duration,k.getGap(d),f,a.playbackRate,k.getRange(d),a.readyState,null)}var k=a(1).Observable,d=a(45).BehaviorSubject,g=a(31).BufferedRanges,b=function(){function a(b,d,g,k,e,l,h,p,r){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.ts=b;this.buffered=d;this.duration=g;this.gap=k;this.name=e;this.playback= l;this.range=h;this.readyState=p;this.stalled=r}a.prototype.clone=function(){return new a(this.ts,this.buffered,this.duration,this.gap,this.name,this.playback,this.range,this.readyState,this.stalled)};return a}();e.exports={getEmptyTimings:function(){return new b(0,new g,0,Infinity,"timeupdate",1,null,0,null)},getTimings:l,timingsSampler:function(a){return k.create(function(b){function d(k){var m=g,e=k&&k.type||"timeupdate";k=l(a,e);var m=m.stalled,h=k.gap;if(e="loadedmetadata"!=e&&!m)e=k.range,e= !(e&&.5>=k.duration-(h+e.end));var n=void 0,n=e&&(.5>=h||Infinity===h)?{name:k.name,playback:k.playback}:m&&Infinity>h&&h>("seeking"==m.name?.5:5)?null:m;k.stalled=n;g=k;b.next(g)}var g=l(a,"init"),k=setInterval(d,1E3);a.addEventListener("play",d);a.addEventListener("progress",d);a.addEventListener("seeking",d);a.addEventListener("seeked",d);a.addEventListener("loadedmetadata",d);b.next(g);return function(){clearInterval(k);a.removeEventListener("play",d);a.removeEventListener("progress",d);a.removeEventListener("seeking", d);a.removeEventListener("seeked",d);a.removeEventListener("loadedmetadata",d)}}).multicast(function(){return new d({name:"init",stalled:null})}).refCount()},seekingsSampler:function(a){return a.filter(function(a){return"seeking"==a.name&&(Infinity===a.gap||-2>a.gap)}).skip(1).startWith(!0)},getLiveGap:function(a,b){if(!b.isLive)return Infinity;var d=b.availabilityStartTime,g=b.presentationLiveGap;return Date.now()/1E3-a-(d+g+10)},toWallClockTime:function(a,b){return new Date(1E3*(a+b.availabilityStartTime))}, fromWallClockTime:function(a,b){var d=a,g=b.suggestedPresentationDelay,k=b.presentationLiveGap,e=b.timeShiftBufferDepth;"number"!=typeof d&&(d=d.getTime());var l=Date.now();return Math.max(Math.min(d,l-1E3*(k+g)),l-1E3*e)/1E3-b.availabilityStartTime}}},function(e,h,a){var l=a(1).Observable,k=a(73).PromiseObservable.create;e.exports=function(a){return a&&"function"==typeof a.subscribe?a:a&&"function"==typeof a.then?k(a):l.of(a)}},function(e,h){function a(a,b){for(var c=-1,f=a?a.length:0;++c<f;)if(a[c]=== b)return c;return-1}function l(a){return!!a&&"object"==("undefined"===typeof a?"undefined":q(a))&&"[object Date]"==v.call(a)||!1}function k(a){return!!a&&"function"==typeof a||!1}function d(a){return"number"==typeof a}function g(a){return!!a&&"object"==("undefined"===typeof a?"undefined":q(a))||!1}function b(a){return"string"==typeof a}function c(a){for(var b=arguments,c=1;c<b.length;c++){var f=b[c];if(g(f))for(var d=w(f),k=0,m=d.length;k<m;k++)a[d[k]]=f[d[k]]}return a}function f(a,b){for(var c=a? a.length:0,f=-1,d=Array(c);++f<c;)d[f]=b(a[f],f);return d}function m(a,b,c){for(var f=a?a.length:0,d=-1;++d<f;)c=b(c,a[d],d);return c}function u(a,b){for(var c=a?a.length:0,f=-1,d=[];++f<c;)b(a[f],f)&&d.push(a[f]);return d}function n(a,c){for(var f in a)if(c.hasOwnProperty(f)){var g=a[f],k=c[f];b(g)||d(g)||l(g)?a[f]=k:r(g)?(g.length=0,y.apply(g,k)):a[f]=n(g,k)}return a}var q="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"=== typeof Symbol&&a.constructor===Symbol?"symbol":typeof a},x=Object.prototype,v=x.toString,p=x.hasOwnProperty,r=Array.isArray,y=Array.prototype.push,w=Object.keys||function(a){var b=[],c;for(c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},x=function(){var a=0;return function(b){b||(b="");return""+b+a++}}();e.exports={chunk:function(a,b){for(var c=[],f=0,d=-1,g=a?a.length:0;++d<g;)c[f]?c[f].length===b?c[++f]=[a[d]]:c[f].push(a[d]):c[f]=[a[d]];return c},compact:function(a){return u(a,function(a){return null!= a})},contains:function(b,c){return-1<a(b,c)},cloneArray:function(a){for(var b=a?a.length:0,c=-1,f=Array(b);++c<b;)f[c]=a[c];return f},cloneObject:function(a){return c({},a)},defaults:function(a,b){for(var c in b)"undefined"==typeof a[c]&&(a[c]=b[c]);return a},each:function(a,b){for(var c=a?a.length:0,f=-1;++f<c;)b(a[f],f)},extend:c,values:function(a){for(var b=w(a),c=-1,f=b.length,d=Array(f);++c<f;)d[c]=a[b[c]];return d},filter:u,find:function(a,b){for(var c=-1,f=a?a.length:0;++c<f;)if(b(a[c],c))return a[c]}, between:function(a,b,c){for(var f=-1,d=a?a.length:0;++f<d;)if(a[f][b]<=c&&a[f+1]&&c<a[f+1][b])return a[f]},findLast:function(a,b){for(var c=a?a.length:0;0<=--c;)if(b(a[c],c))return a[c]},flatten:function(a,b){for(var c=b?f(a,b):a,d=-1,g=c?c.length:0,k=[];++d<g;){var m=c[d];if(m&&"object"==("undefined"===typeof m?"undefined":q(m))&&"number"==typeof m.length){var e=-1,l=m.length,h=k.length;for(k.length+=l;++e<l;)k[h++]=m[e]}else k.push(m)}return k},groupBy:function(a,b){var c;c=k(b)?b:function(a){return a[b]}; return m(a,function(a,b){var f=c(b);(r(a[f])?a[f]:a[f]=[]).push(b);return a},{})},identity:function(a){return a},indexOf:a,isArray:r,isDate:l,isFunction:k,isNumber:d,isObject:g,isString:b,isPromise:function(a){return!!a&&"function"==typeof a.then},isObservable:function(a){return!!a&&"function"==typeof a.subscribe},keys:w,last:function(a){return a[a.length-1]},map:f,memoize:function(a,b){var c=function B(){var c=B.cache,f=b?b.apply(this,arguments):arguments[0];return p.call(c,f)?c[f]:c[f]=a.apply(this, arguments)};c.cache={};return c},noop:function(){},pad:function(a,b){a=a.toString();return a.length>=b?a:(Array(b+1).join("0")+a).slice(-b)},pick:function(a,b){return m(b,function(b,c){c in a&&(b[c]=a[c]);return b},{})},pluck:function(a,b){return f(a,function(a){return a[b]})},reduce:m,simpleMerge:n,sortedIndex:function(a,b,c){var f=0,d=a?a.length:f;for(b=c(b);f<d;){var g=f+d>>>1;c(a[g])<b?f=g+1:d=g}return f},sortedMerge:function(a,b,c){for(var f=0,d=0,g=0,k=a.length,m=b.length,e=[];f<k&&d<m;)a[f][c]<= b[d][c]?(e[g]=a[f],f++,g++):0<g&&b[d][c]<=e[g-1][c]?d++:(e[g]=b[d],d++,g++);if(f<k)for(c=f;c<k;c++)e[g]=a[c],g++;else for(c=d;c<m;c++)e[g]=b[c],g++;return e},tryCatch:function(a){try{return a()}catch(b){return b}},uniqueId:x}},function(e,h){e.exports=function(a){var e=a?a.length:0;return e?a[e-1]:void 0}},function(e,h,a){h=a(98);a=a(59)(h,!0);e.exports=a},function(e,h){e.exports=function(a,e){for(var k=-1,d=e.length,g=a.length;++k<d;)a[g+k]=e[k];return a}},function(e,h){e.exports=function(a,e){for(var k= -1,d=a.length;++k<d;)if(e(a[k],k,a))return!0;return!1}},function(e,h){e.exports=function(a,e){return void 0===a?e:a}},function(e,h,a){var l=a(18);e.exports=function(a,d,g){for(var b=-1,c=l(d),f=c.length;++b<f;){var e=c[b],h=a[e],n=g(h,d[e],e,a,d);(n===n?n===h:h!==h)&&(void 0!==h||e in a)||(a[e]=n)}return a}},function(e,h,a){var l=a(96),k=a(18);e.exports=function(a,g){return null==g?a:l(g,k(g),a)}},function(e,h,a){var l="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}: function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol?"symbol":typeof a},k=a(108),d=a(109),g=a(56),b=a(66),c=a(126);e.exports=function(a,e,h){var n="undefined"===typeof a?"undefined":l(a);return"function"==n?void 0===e?a:g(a,e,h):null==a?b:"object"==n?k(a):void 0===e?c(a):d(a,e)}},function(e,h){e.exports=function(a,e,k){k||(k={});for(var d=-1,g=e.length;++d<g;){var b=e[d];k[b]=a[b]}return k}},function(e,h,a){h=a(103);a=a(57)(h);e.exports=a},function(e,h,a){h=a(104);a=a(57)(h,!0); e.exports=a},function(e,h){e.exports=function(a,e,k,d){var g;k(a,function(a,c,f){if(e(a,c,f))return g=d?c:a,!1});return g}},function(e,h){e.exports=function(a,e,k){for(var d=a.length,g=k?d:-1;k?g--:++g<d;)if(e(a[g],g,a))return g;return-1}},function(e,h,a){function l(a,e,h,n){n||(n=[]);for(var q=-1,x=a.length;++q<x;){var v=a[q];c(v)&&b(v)&&(h||g(v)||d(v))?e?l(v,e,h,n):k(n,v):h||(n[n.length]=v)}return n}var k=a(90),d=a(39),g=a(8),b=a(33),c=a(17);e.exports=l},function(e,h,a){h=a(58)();e.exports=h},function(e, h,a){var l=a(102),k=a(18);e.exports=function(a,g){return l(a,g,k)}},function(e,h,a){var l=a(105),k=a(18);e.exports=function(a,g){return l(a,g,k)}},function(e,h,a){h=a(58)(!0);e.exports=h},function(e,h,a){var l=a(115),k=a(116),d=a(117),g=a(8),b=a(122);h=Object.prototype;var c=h.hasOwnProperty,f=h.toString;e.exports=function(a,e,h,q,x,v,p){var r=g(a),y=g(e),w="[object Array]",z="[object Array]";r||(w=f.call(a),"[object Arguments]"==w?w="[object Object]":"[object Object]"!=w&&(r=b(a)));y||(z=f.call(e), "[object Arguments]"==z?z="[object Object]":"[object Object]"!=z&&b(e));var D="[object Object]"==w,y="[object Object]"==z;if((z=w==z)&&!r&&!D)return k(a,e,w);if(!x&&(w=D&&c.call(a,"__wrapped__"),y=y&&c.call(e,"__wrapped__"),w||y))return h(w?a.value():a,y?e.value():e,q,x,v,p);if(!z)return!1;v||(v=[]);p||(p=[]);for(w=v.length;w--;)if(v[w]==a)return p[w]==e;v.push(a);p.push(e);a=(r?l:d)(a,e,h,q,x,v,p);v.pop();p.pop();return a}},function(e,h,a){var l=a(54),k=a(7);e.exports=function(a,g,b){var c=g.length, f=c,e=!b;if(null==a)return!f;for(a=k(a);c--;){var h=g[c];if(e&&h[2]?h[1]!==a[h[0]]:!(h[0]in a))return!1}for(;++c<f;){var h=g[c],n=h[0],q=a[n],x=h[1];if(e&&h[2]){if(void 0===q&&!(n in a))return!1}else if(h=b?b(q,x,n):void 0,void 0===h?!l(x,q,b,!0):!h)return!1}return!0}},function(e,h,a){var l=a(107),k=a(118),d=a(7);e.exports=function(a){var b=k(a);if(1==b.length&&b[0][2]){var c=b[0][0],f=b[0][1];return function(a){return null==a?!1:a[c]===f&&(void 0!==f||c in d(a))}}return function(a){return l(a,b)}}}, function(e,h,a){var l=a(53),k=a(54),d=a(111),g=a(8),b=a(63),c=a(64),f=a(88),m=a(7),u=a(65);e.exports=function(a,e){var h=g(a),v=b(a)&&c(e),p=a+"";a=u(a);return function(b){if(null==b)return!1;var c=p;b=m(b);if(!(!h&&v||c in b)){b=1==a.length?b:l(b,d(a,0,-1));if(null==b)return!1;c=f(a);b=m(b)}return b[c]===e?void 0!==e||c in b:k(e,b[c],void 0,!0)}}},function(e,h,a){var l=a(53),k=a(65);e.exports=function(a){var g=a+"";a=k(a);return function(b){return l(b,a,g)}}},function(e,h){e.exports=function(a,e, k){var d=-1,g=a.length;e=null==e?0:+e||0;0>e&&(e=-e>g?0:g+e);k=void 0===k||k>g?g:+k||0;0>k&&(k+=g);g=e>k?0:k-e>>>0;e>>>=0;for(k=Array(g);++d<g;)k[d]=a[d+e];return k}},function(e,h){e.exports=function(a){return null==a?"":a+""}},function(e,h,a){var l=a(56),k=a(62),d=a(52);e.exports=function(a){return d(function(b,c){var f=-1,d=null==b?0:c.length,e=2<d?c[d-2]:void 0,h=2<d?c[2]:void 0,q=1<d?c[d-1]:void 0;"function"==typeof e?(e=l(e,q,5),d-=2):(e="function"==typeof q?q:void 0,d-=e?1:0);h&&k(c[0],c[1], h)&&(e=3>d?void 0:e,d=1);for(;++f<d;)(h=c[f])&&a(b,h,e);return b})}},function(e,h,a){var l=a(52);e.exports=function(a,d){return l(function(g){var b=g[0];if(null==b)return b;g.push(d);return a.apply(void 0,g)})}},function(e,h,a){var l=a(91);e.exports=function(a,d,g,b,c,f,e){var h=-1,n=a.length,q=d.length;if(n!=q&&!(c&&q>n))return!1;for(;++h<n;){var x=a[h],q=d[h],v=b?b(c?q:x,c?x:q,h):void 0;if(void 0!==v){if(v)continue;return!1}if(c){if(!l(d,function(a){return x===a||g(x,a,b,c,f,e)}))return!1}else if(x!== q&&!g(x,q,b,c,f,e))return!1}return!0}},function(e,h){e.exports=function(a,e,k){switch(k){case "[object Boolean]":case "[object Date]":return+a==+e;case "[object Error]":return a.name==e.name&&a.message==e.message;case "[object Number]":return a!=+a?e!=+e:a==+e;case "[object RegExp]":case "[object String]":return a==e+""}return!1}},function(e,h,a){var l=a(18),k=Object.prototype.hasOwnProperty;e.exports=function(a,g,b,c,f,e,h){var n=l(a),q=n.length,x=l(g).length;if(q!=x&&!f)return!1;for(x=q;x--;){var v= n[x];if(!(f?v in g:k.call(g,v)))return!1}for(var p=f;++x<q;){var v=n[x],r=a[v],y=g[v],w=c?c(f?y:r,f?r:y,v):void 0;if(void 0===w?!b(r,y,c,f,e,h):!w)return!1;p||(p="constructor"==v)}return p||(b=a.constructor,c=g.constructor,!(b!=c&&"constructor"in a&&"constructor"in g)||"function"==typeof b&&b instanceof b&&"function"==typeof c&&c instanceof c)?!0:!1}},function(e,h,a){var l=a(64),k=a(125);e.exports=function(a){a=k(a);for(var g=a.length;g--;)a[g][2]=l(a[g][1]);return a}},function(e,h,a){var l=a(39), k=a(8),d=a(38),g=a(16),b=a(124),c=Object.prototype.hasOwnProperty;e.exports=function(a){for(var e=b(a),h=e.length,n=h&&a.length,q=!!n&&g(n)&&(k(a)||l(a)),x=-1,v=[];++x<h;){var p=e[x];(q&&d(p,n)||c.call(a,p))&&v.push(p)}return v}},function(e,h,a){var l=a(9),k=Object.prototype.toString;e.exports=function(a){return l(a)&&"[object Function]"==k.call(a)}},function(e,h,a){var l=a(120),k=a(17),d=/^\[object .+?Constructor\]$/,g=Function.prototype.toString,b=RegExp("^"+g.call(Object.prototype.hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=function(a){return null==a?!1:l(a)?b.test(g.call(a)):k(a)&&d.test(a)}},function(e,h,a){var l=a(16),k=a(17),d={};d["[object Float32Array]"]=d["[object Float64Array]"]=d["[object Int8Array]"]=d["[object Int16Array]"]=d["[object Int32Array]"]=d["[object Uint8Array]"]=d["[object Uint8ClampedArray]"]=d["[object Uint16Array]"]=d["[object Uint32Array]"]=!0;d["[object Arguments]"]=d["[object Array]"]=d["[object ArrayBuffer]"]= d["[object Boolean]"]=d["[object Date]"]=d["[object Error]"]=d["[object Function]"]=d["[object Map]"]=d["[object Number]"]=d["[object Object]"]=d["[object RegExp]"]=d["[object Set]"]=d["[object String]"]=d["[object WeakMap]"]=!1;var g=Object.prototype.toString;e.exports=function(a){return k(a)&&l(a.length)&&!!d[g.call(a)]}},function(e,h,a){var l=a(93),k=a(94);h=a(113)(function(a,g,b){return b?l(a,g,b):k(a,g)});e.exports=h},function(e,h,a){var l=a(39),k=a(8),d=a(38),g=a(16),b=a(9),c=Object.prototype.hasOwnProperty; e.exports=function(a){if(null==a)return[];b(a)||(a=Object(a));for(var e=a.length,e=e&&g(e)&&(k(a)||l(a))&&e||0,h=a.constructor,n=-1,h="function"==typeof h&&h.prototype===a,q=Array(e),x=0<e;++n<e;)q[n]=n+"";for(var v in a)x&&d(v,e)||"constructor"==v&&(h||!c.call(a,v))||q.push(v);return q}},function(e,h,a){var l=a(18),k=a(7);e.exports=function(a){a=k(a);for(var g=-1,b=l(a),c=b.length,f=Array(c);++g<c;){var e=b[g];f[g]=[e,a[e]]}return f}},function(e,h,a){var l=a(55),k=a(110),d=a(63);e.exports=function(a){return d(a)? l(a):k(a)}},function(e,h,a){var l=function(a,d){function g(){this.constructor=a}for(var b in d)d.hasOwnProperty(b)&&(a[b]=d[b]);a.prototype=null===d?Object.create(d):(g.prototype=d.prototype,new g)};e=function(a){function d(d,b,c){a.call(this);this.parent=d;this.outerValue=b;this.outerIndex=c;this.index=0}l(d,a);d.prototype._next=function(a){this.parent.notifyNext(this.outerValue,a,this.outerIndex,this.index++,this)};d.prototype._error=function(a){this.parent.notifyError(a,this);this.unsubscribe()}; d.prototype._complete=function(){this.parent.notifyComplete(this);this.unsubscribe()};return d}(a(2).Subscriber);h.InnerSubscriber=e},function(e,h,a){var l=a(1);e=function(){function a(d,g,b){this.kind=d;this.value=g;this.exception=b;this.hasValue="N"===d}a.prototype.observe=function(a){switch(this.kind){case "N":return a.next&&a.next(this.value);case "E":return a.error&&a.error(this.exception);case "C":return a.complete&&a.complete()}};a.prototype["do"]=function(a,g,b){switch(this.kind){case "N":return a&& a(this.value);case "E":return g&&g(this.exception);case "C":return b&&b()}};a.prototype.accept=function(a,g,b){return a&&"function"===typeof a.next?this.observe(a):this["do"](a,g,b)};a.prototype.toObservable=function(){switch(this.kind){case "N":return l.Observable.of(this.value);case "E":return l.Observable["throw"](this.exception);case "C":return l.Observable.empty()}};a.createNext=function(d){return"undefined"!==typeof d?new a("N",d):this.undefinedValueNotification};a.createError=function(d){return new a("E", void 0,d)};a.createComplete=function(){return this.completeNotification};a.completeNotification=new a("C");a.undefinedValueNotification=new a("N",void 0);return a}();h.Notification=e},function(e,h){h.empty={isUnsubscribed:!0,next:function(a){},error:function(a){throw a;},complete:function(){}}},function(e,h,a){e=a(1);a=a(19);e.Observable.of=a.ArrayObservable.of},function(e,h,a){e=a(1);a=a(153);e.Observable["throw"]=a.ErrorObservable.create},function(e,h,a){e=a(1);a=a(74);e.Observable.prototype.concat= a.concat},function(e,h,a){e=a(1);a=a(158);e.Observable.prototype.concatAll=a.concatAll},function(e,h,a){e=a(1);a=a(159);e.Observable.prototype.concatMap=a.concatMap},function(e,h,a){e=a(1);a=a(160);e.Observable.prototype.debounceTime=a.debounceTime},function(e,h,a){e=a(1);a=a(161);e.Observable.prototype.distinctUntilChanged=a.distinctUntilChanged},function(e,h,a){e=a(1);a=a(162);e.Observable.prototype["do"]=a._do},function(e,h,a){e=a(1);a=a(163);e.Observable.prototype.filter=a.filter},function(e, h,a){e=a(1);a=a(164);e.Observable.prototype["finally"]=a._finally},function(e,h,a){e=a(1);a=a(165);e.Observable.prototype.ignoreElements=a.ignoreElements},function(e,h,a){e=a(1);a=a(166);e.Observable.prototype.map=a.map},function(e,h,a){e=a(1);a=a(167);e.Observable.prototype.mapTo=a.mapTo},function(e,h,a){e=a(1);a=a(43);e.Observable.prototype.multicast=a.multicast},function(e,h,a){e=a(1);a=a(169);e.Observable.prototype.publish=a.publish},function(e,h,a){e=a(1);a=a(170);e.Observable.prototype.scan= a.scan},function(e,h,a){e=a(1);a=a(171);e.Observable.prototype.share=a.share},function(e,h,a){e=a(1);a=a(172);e.Observable.prototype.skip=a.skip},function(e,h,a){e=a(1);a=a(174);e.Observable.prototype.switchMap=a.switchMap},function(e,h,a){e=a(1);a=a(176);e.Observable.prototype.takeUntil=a.takeUntil},function(e,h,a){e=a(1);a=a(177);e.Observable.prototype.timeout=a.timeout},function(e,h,a){var l=function(a,b){function c(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype= null===b?Object.create(b):(c.prototype=b.prototype,new c)};e=a(1);var k=a(40),d=a(6);a=function(a){function b(b,f,d,k){a.call(this);this.arrayLike=b;this.scheduler=k;f||k||1!==b.length||(this._isScalar=!0,this.value=b[0]);f&&(this.mapFn=f.bind(d))}l(b,a);b.create=function(a,f,g,e){var h=a.length;return 0===h?new d.EmptyObservable:1!==h||f?new b(a,f,g,e):new k.ScalarObservable(a[0],e)};b.dispatch=function(a){var b=a.arrayLike,d=a.index,g=a.length,k=a.mapFn,e=a.subscriber;e.isUnsubscribed||(d>=g?e.complete(): (b=k?k(b[d],d):b[d],e.next(b),a.index=d+1,this.schedule(a)))};b.prototype._subscribe=function(a){var f=this.arrayLike,d=this.mapFn,g=this.scheduler,k=f.length;if(g)return g.schedule(b.dispatch,0,{arrayLike:f,index:0,length:k,mapFn:d,subscriber:a});for(g=0;g<k&&!a.isUnsubscribed;g++){var e=d?d(f[g],g):f[g];a.next(e)}a.complete()};return b}(e.Observable);h.ArrayLikeObservable=a},function(e,h,a){var l=function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype= null===b?Object.create(b):(c.prototype=b.prototype,new c)};e=a(1);var k=a(2);a=a(5);var d=function(a){function c(b,d){a.call(this);this.source=b;this.subjectFactory=d}l(c,a);c.prototype._subscribe=function(a){return this.getSubject().subscribe(a)};c.prototype.getSubject=function(){var a=this.subject;return a&&!a.isUnsubscribed?a:this.subject=this.subjectFactory()};c.prototype.connect=function(){var a=this.subscription;if(a&&!a.isUnsubscribed)return a;a=this.source.subscribe(this.getSubject());a.add(new g(this)); return this.subscription=a};c.prototype.refCount=function(){return new b(this)};c.prototype._closeSubscription=function(){this.subscription=this.subject=null};return c}(e.Observable);h.ConnectableObservable=d;var g=function(a){function b(c){a.call(this);this.connectable=c}l(b,a);b.prototype._unsubscribe=function(){this.connectable._closeSubscription();this.connectable=null};return b}(a.Subscription),b=function(a){function b(c,d){void 0===d&&(d=0);a.call(this);this.connectable=c;this.refCount=d}l(b, a);b.prototype._subscribe=function(a){var b=this.connectable;a=new c(a,this);var f=b.subscribe(a);f.isUnsubscribed||1!==++this.refCount||(a.connection=this.connection=b.connect());return f};return b}(e.Observable),c=function(a){function b(c,d){a.call(this,null);this.destination=c;this.refCountObservable=d;this.connection=d.connection;c.add(this)}l(b,a);b.prototype._next=function(a){this.destination.next(a)};b.prototype._error=function(a){this._resetConnectable();this.destination.error(a)};b.prototype._complete= function(){this._resetConnectable();this.destination.complete()};b.prototype._resetConnectable=function(){var a=this.refCountObservable,b=a.connection,c=this.connection;c&&c===b&&(a.refCount=0,b.unsubscribe(),a.connection=null,this.unsubscribe())};b.prototype._unsubscribe=function(){var a=this.refCountObservable;if(0!==a.refCount&&0===--a.refCount){var b=a.connection,c=this.connection;c&&c===b&&(b.unsubscribe(),a.connection=null)}};return b}(k.Subscriber)},function(e,h,a){var l=function(a,d){function g(){this.constructor= a}for(var b in d)d.hasOwnProperty(b)&&(a[b]=d[b]);a.prototype=null===d?Object.create(d):(g.prototype=d.prototype,new g)};e=function(a){function d(d,b){a.call(this);this.error=d;this.scheduler=b}l(d,a);d.create=function(a,b){return new d(a,b)};d.dispatch=function(a){a.subscriber.error(a.error)};d.prototype._subscribe=function(a){var b=this.error,c=this.scheduler;if(c)return c.schedule(d.dispatch,0,{error:b,subscriber:a});a.error(b)};return d}(a(1).Observable);h.ErrorObservable=e},function(e,h,a){var l= "function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol?"symbol":typeof a},k=function(a,b){function c(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},d=a(28),g=a(34),b=a(80),c=a(12),f=a(73),m=a(156),u=a(19),n=a(151),q=a(27),x=a(1),v=a(168);e=function(a){function e(b,c){a.call(this,null);this.ish=b;this.scheduler= c}k(e,a);e.create=function(a,k,h,v){var p=null,t=null;g.isFunction(k)?(p=v||null,t=k):c.isScheduler(p)&&(p=k);if(null!=a){if("function"===typeof a[q.SymbolShim.observable])return a instanceof x.Observable&&!p?a:new e(a,p);if(d.isArray(a))return new u.ArrayObservable(a,p);if(b.isPromise(a))return new f.PromiseObservable(a,p);if("function"===typeof a[q.SymbolShim.iterator]||"string"===typeof a)return new m.IteratorObservable(a,null,null,p);if(a&&"number"===typeof a.length)return new n.ArrayLikeObservable(a, t,h,p)}throw new TypeError((null!==a&&("undefined"===typeof a?"undefined":l(a))||a)+" is not observable");};e.prototype._subscribe=function(a){var b=this.ish,c=this.scheduler;return null==c?b[q.SymbolShim.observable]().subscribe(a):b[q.SymbolShim.observable]().subscribe(new v.ObserveOnSubscriber(a,c,0))};return e}(x.Observable);h.FromObservable=e},function(e,h,a){var l=function(a,b){function c(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b): (c.prototype=b.prototype,new c)},k=a(78);e=a(1);var d=a(26);a=function(a){function b(b,f){void 0===b&&(b=0);void 0===f&&(f=d.asap);a.call(this);this.period=b;this.scheduler=f;if(!k.isNumeric(b)||0>b)this.period=0;f&&"function"===typeof f.schedule||(this.scheduler=d.asap)}l(b,a);b.create=function(a,f){void 0===a&&(a=0);void 0===f&&(f=d.asap);return new b(a,f)};b.dispatch=function(a){var b=a.subscriber,d=a.period;b.next(a.index);b.isUnsubscribed||(a.index+=1,this.schedule(a,d))};b.prototype._subscribe= function(a){var f=this.period;a.add(this.scheduler.schedule(b.dispatch,f,{index:0,subscriber:a,period:f}))};return b}(e.Observable);h.IntervalObservable=a},function(e,h,a){var l=function(a,b){function c(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},k=a(13),d=a(79),g=a(30);e=a(1);var b=a(34),c=a(27),f=a(20);a=function(a){function k(f,g,e,h){a.call(this);if(null==f)throw Error("iterator cannot be null.");if(d.isObject(g))this.thisArg= g,this.scheduler=e;else if(b.isFunction(g))this.project=g,this.thisArg=e,this.scheduler=h;else if(null!=g)throw Error("When provided, `project` must be a function.");if((g=f[c.SymbolShim.iterator])||"string"!==typeof f)if(g||void 0===f.length){if(!g)throw new TypeError("Object is not iterable");f=f[c.SymbolShim.iterator]()}else f=new u(f);else f=new m(f);this.iterator=f}l(k,a);k.create=function(a,b,c,f){return new k(a,b,c,f)};k.dispatch=function(a){var b=a.index,c=a.thisArg,d=a.project,k=a.iterator, e=a.subscriber;a.hasError?e.error(a.error):(k=k.next(),k.done?e.complete():(d?(k=g.tryCatch(d).call(c,k.value,b),k===f.errorObject?(a.error=f.errorObject.e,a.hasError=!0):(e.next(k),a.index=b+1)):(e.next(k.value),a.index=b+1),e.isUnsubscribed||this.schedule(a)))};k.prototype._subscribe=function(a){var b=0,c=this.iterator,d=this.project,e=this.thisArg,h=this.scheduler;if(h)return h.schedule(k.dispatch,0,{index:b,thisArg:e,project:d,iterator:c,subscriber:a});do{h=c.next();if(h.done){a.complete();break}else if(d){h= g.tryCatch(d).call(e,h.value,b++);if(h===f.errorObject){a.error(f.errorObject.e);break}a.next(h)}else a.next(h.value);if(a.isUnsubscribed)break}while(1)};return k}(e.Observable);h.IteratorObservable=a;var m=function(){function a(b,c,f){void 0===c&&(c=0);void 0===f&&(f=b.length);this.str=b;this.idx=c;this.len=f}a.prototype[c.SymbolShim.iterator]=function(){return this};a.prototype.next=function(){return this.idx<this.len?{done:!1,value:this.str.charAt(this.idx++)}:{done:!0,value:void 0}};return a}(), u=function(){function a(b,c,f){void 0===c&&(c=0);if(void 0===f)if(f=+b.length,isNaN(f))f=0;else if(0!==f&&"number"===typeof f&&k.root.isFinite(f)){var d;d=+f;d=0===d?d:isNaN(d)?d:0>d?-1:1;f=d*Math.floor(Math.abs(f));f=0>=f?0:f>n?n:f}this.arr=b;this.idx=c;this.len=f}a.prototype[c.SymbolShim.iterator]=function(){return this};a.prototype.next=function(){return this.idx<this.len?{done:!1,value:this.arr[this.idx++]}:{done:!0,value:void 0}};return a}(),n=Math.pow(2,53)-1},function(e,h,a){var l=function(a, b){function c(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};e=a(2);h._catch=function(a){a=new k(a);var b=this.lift(a);return a.caught=b};var k=function(){function a(b){this.selector=b}a.prototype.call=function(a){return new d(a,this.selector,this.caught)};return a}(),d=function(a){function b(b,f,d){a.call(this,b);this.selector=f;this.caught=d}l(b,a);b.prototype.error=function(a){if(!this.isStopped){var b= void 0;try{b=this.selector(a,this.caught)}catch(d){this.destination.error(d);return}this._innerSub(b)}};b.prototype._innerSub=function(a){this.unsubscribe();this.destination.remove(this);a.subscribe(this.destination)};return b}(e.Subscriber)},function(e,h,a){var l=a(42);h.concatAll=function(){return this.lift(new l.MergeAllOperator(1))}},function(e,h,a){var l=a(75);h.concatMap=function(a,d){return this.lift(new l.MergeMapOperator(a,d,1))}},function(e,h,a){function l(a){a.debouncedNext()}var k=function(a, b){function d(){this.constructor=a}for(var g in b)b.hasOwnProperty(g)&&(a[g]=b[g]);a.prototype=null===b?Object.create(b):(d.prototype=b.prototype,new d)};e=a(2);var d=a(26);h.debounceTime=function(a,b){void 0===b&&(b=d.asap);return this.lift(new g(a,b))};var g=function(){function a(b,c){this.dueTime=b;this.scheduler=c}a.prototype.call=function(a){return new b(a,this.dueTime,this.scheduler)};return a}(),b=function(a){function b(f,d,g){a.call(this,f);this.dueTime=d;this.scheduler=g;this.lastValue=this.debouncedSubscription= null;this.hasValue=!1}k(b,a);b.prototype._next=function(a){this.clearDebounce();this.lastValue=a;this.hasValue=!0;this.add(this.debouncedSubscription=this.scheduler.schedule(l,this.dueTime,this))};b.prototype._complete=function(){this.debouncedNext();this.destination.complete()};b.prototype.debouncedNext=function(){this.clearDebounce();this.hasValue&&(this.destination.next(this.lastValue),this.lastValue=null,this.hasValue=!1)};b.prototype.clearDebounce=function(){var a=this.debouncedSubscription; null!==a&&(this.remove(a),a.unsubscribe(),this.debouncedSubscription=null)};return b}(e.Subscriber)},function(e,h,a){var l=function(a,b){function d(){this.constructor=a}for(var g in b)b.hasOwnProperty(g)&&(a[g]=b[g]);a.prototype=null===b?Object.create(b):(d.prototype=b.prototype,new d)};e=a(2);var k=a(30),d=a(20);h.distinctUntilChanged=function(a,b){return this.lift(new g(a,b))};var g=function(){function a(b,c){this.compare=b;this.keySelector=c}a.prototype.call=function(a){return new b(a,this.compare, this.keySelector)};return a}(),b=function(a){function b(f,d,g){a.call(this,f);this.keySelector=g;this.hasKey=!1;"function"===typeof d&&(this.compare=d)}l(b,a);b.prototype.compare=function(a,b){return a===b};b.prototype._next=function(a){var b=a;if(this.keySelector&&(b=k.tryCatch(this.keySelector)(a),b===d.errorObject))return this.destination.error(d.errorObject.e);var c=!1;if(this.hasKey){if(c=k.tryCatch(this.compare)(this.key,b),c===d.errorObject)return this.destination.error(d.errorObject.e)}else this.hasKey= !0;!1===Boolean(c)&&(this.key=b,this.destination.next(a))};return b}(e.Subscriber)},function(e,h,a){var l="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol?"symbol":typeof a},k=function(a,b){function d(){this.constructor=a}for(var g in b)b.hasOwnProperty(g)&&(a[g]=b[g]);a.prototype=null===b?Object.create(b):(d.prototype=b.prototype,new d)};e=a(2);var d=a(47);h._do=function(a,b,k){var e; a&&"object"===("undefined"===typeof a?"undefined":l(a))?(e=a.next,b=a.error,k=a.complete):e=a;return this.lift(new g(e||d.noop,b||d.noop,k||d.noop))};var g=function(){function a(b,c,d){this.next=b;this.error=c;this.complete=d}a.prototype.call=function(a){return new b(a,this.next,this.error,this.complete)};return a}(),b=function(a){function b(f,d,g,k){a.call(this,f);this.__next=d;this.__error=g;this.__complete=k}k(b,a);b.prototype._next=function(a){try{this.__next(a)}catch(b){this.destination.error(b); return}this.destination.next(a)};b.prototype._error=function(a){try{this.__error(a)}catch(b){this.destination.error(b);return}this.destination.error(a)};b.prototype._complete=function(){try{this.__complete()}catch(a){this.destination.error(a);return}this.destination.complete()};return b}(e.Subscriber)},function(e,h,a){var l=function(a,b){function c(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};e=a(2);h.filter= function(a,b){return this.lift(new k(a,b))};var k=function(){function a(b,c){this.select=b;this.thisArg=c}a.prototype.call=function(a){return new d(a,this.select,this.thisArg)};return a}(),d=function(a){function b(b,f,d){a.call(this,b);this.select=f;this.thisArg=d;this.count=0;this.select=f}l(b,a);b.prototype._next=function(a){var b;try{b=this.select.call(this.thisArg,a,this.count++)}catch(d){this.destination.error(d);return}b&&this.destination.next(a)};return b}(e.Subscriber)},function(e,h,a){var l= function(a,c){function f(){this.constructor=a}for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d]);a.prototype=null===c?Object.create(c):(f.prototype=c.prototype,new f)};e=a(2);var k=a(5);h._finally=function(a){return this.lift(new d(a))};var d=function(){function a(b){this.finallySelector=b}a.prototype.call=function(a){return new g(a,this.finallySelector)};return a}(),g=function(a){function c(c,d){a.call(this,c);this.add(new k.Subscription(d))}l(c,a);return c}(e.Subscriber)},function(e,h,a){var l=function(a, c){function f(){this.constructor=a}for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d]);a.prototype=null===c?Object.create(c):(f.prototype=c.prototype,new f)};e=a(2);var k=a(47);h.ignoreElements=function(){return this.lift(new d)};var d=function(){function a(){}a.prototype.call=function(a){return new g(a)};return a}(),g=function(a){function c(){a.apply(this,arguments)}l(c,a);c.prototype._next=function(a){k.noop()};return c}(e.Subscriber)},function(e,h,a){var l=function(a,b){function c(){this.constructor= a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};e=a(2);h.map=function(a,b){if("function"!==typeof a)throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");return this.lift(new k(a,b))};var k=function(){function a(b,c){this.project=b;this.thisArg=c}a.prototype.call=function(a){return new d(a,this.project,this.thisArg)};return a}(),d=function(a){function b(b,f,d){a.call(this,b);this.project=f;this.count= 0;this.thisArg=d||this}l(b,a);b.prototype._next=function(a){var b;try{b=this.project.call(this.thisArg,a,this.count++)}catch(d){this.destination.error(d);return}this.destination.next(b)};return b}(e.Subscriber)},function(e,h,a){var l=function(a,b){function c(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};e=a(2);h.mapTo=function(a){return this.lift(new k(a))};var k=function(){function a(b){this.value=b}a.prototype.call= function(a){return new d(a,this.value)};return a}(),d=function(a){function b(b,f){a.call(this,b);this.value=f}l(b,a);b.prototype._next=function(a){this.destination.next(this.value)};return b}(e.Subscriber)},function(e,h,a){var l=function(a,b){function d(){this.constructor=a}for(var g in b)b.hasOwnProperty(g)&&(a[g]=b[g]);a.prototype=null===b?Object.create(b):(d.prototype=b.prototype,new d)};e=a(2);var k=a(128);h.observeOn=function(a,b){void 0===b&&(b=0);return this.lift(new d(a,b))};var d=function(){function a(b, c){void 0===c&&(c=0);this.scheduler=b;this.delay=c}a.prototype.call=function(a){return new g(a,this.scheduler,this.delay)};return a}();h.ObserveOnOperator=d;var g=function(a){function f(b,f,d){void 0===d&&(d=0);a.call(this,b);this.scheduler=f;this.delay=d}l(f,a);f.dispatch=function(a){a.notification.observe(a.destination)};f.prototype.scheduleMessage=function(a){this.add(this.scheduler.schedule(f.dispatch,this.delay,new b(a,this.destination)))};f.prototype._next=function(a){this.scheduleMessage(k.Notification.createNext(a))}; f.prototype._error=function(a){this.scheduleMessage(k.Notification.createError(a))};f.prototype._complete=function(){this.scheduleMessage(k.Notification.createComplete())};return f}(e.Subscriber);h.ObserveOnSubscriber=g;var b=function(){return function(a,b){this.notification=a;this.destination=b}}()},function(e,h,a){var l=a(10),k=a(43);h.publish=function(){return k.multicast.call(this,new l.Subject)}},function(e,h,a){var l=function(a,b){function c(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&& (a[f]=b[f]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};e=a(2);h.scan=function(a,b){return this.lift(new k(a,b))};var k=function(){function a(b,c){this.accumulator=b;this.seed=c}a.prototype.call=function(a){return new d(a,this.accumulator,this.seed)};return a}(),d=function(a){function b(b,f,d){a.call(this,b);this.accumulator=f;this.accumulatorSet=!1;this.seed=d;this.accumulator=f;this.accumulatorSet="undefined"!==typeof d}l(b,a);Object.defineProperty(b.prototype,"seed", {get:function(){return this._seed},set:function(a){this.accumulatorSet=!0;this._seed=a},enumerable:!0,configurable:!0});b.prototype._next=function(a){if(this.accumulatorSet)return this._tryNext(a);this.seed=a;this.destination.next(a)};b.prototype._tryNext=function(a){var b;try{b=this.accumulator(this.seed,a)}catch(d){this.destination.error(d)}this.seed=b;this.destination.next(b)};return b}(e.Subscriber)},function(e,h,a){function l(){return new d.Subject}var k=a(43),d=a(10);h.share=function(){return k.multicast.call(this, l).refCount()}},function(e,h,a){var l=function(a,b){function c(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};e=a(2);h.skip=function(a){return this.lift(new k(a))};var k=function(){function a(b){this.total=b}a.prototype.call=function(a){return new d(a,this.total)};return a}(),d=function(a){function b(b,f){a.call(this,b);this.total=f;this.count=0}l(b,a);b.prototype._next=function(a){++this.count>this.total&& this.destination.next(a)};return b}(e.Subscriber)},function(e,h,a){var l=a(19),k=a(40),d=a(6),g=a(74),b=a(12);h.startWith=function(){for(var a=[],f=0;f<arguments.length;f++)a[f-0]=arguments[f];f=a[a.length-1];b.isScheduler(f)?a.pop():f=null;var e=a.length;return 1===e?g.concatStatic(new k.ScalarObservable(a[0],f),this):1<e?g.concatStatic(new l.ArrayObservable(a,f),this):g.concatStatic(new d.EmptyObservable(f),this)}},function(e,h,a){var l=function(a,c){function f(){this.constructor=a}for(var d in c)c.hasOwnProperty(d)&& (a[d]=c[d]);a.prototype=null===c?Object.create(c):(f.prototype=c.prototype,new f)};e=a(24);var k=a(29);h.switchMap=function(a,c){return this.lift(new d(a,c))};var d=function(){function a(b,f){this.project=b;this.resultSelector=f}a.prototype.call=function(a){return new g(a,this.project,this.resultSelector)};return a}(),g=function(a){function c(c,d,g){a.call(this,c);this.project=d;this.resultSelector=g;this.index=0}l(c,a);c.prototype._next=function(a){var b,c=this.index++;try{b=this.project(a,c)}catch(d){this.destination.error(d); return}this._innerSub(b,a,c)};c.prototype._innerSub=function(a,b,c){var d=this.innerSubscription;d&&d.unsubscribe();this.add(this.innerSubscription=k.subscribeToResult(this,a,b,c))};c.prototype._complete=function(){var c=this.innerSubscription;c&&!c.isUnsubscribed||a.prototype._complete.call(this)};c.prototype._unsubscribe=function(){this.innerSubscription=null};c.prototype.notifyComplete=function(c){this.remove(c);this.innerSubscription=null;this.isStopped&&a.prototype._complete.call(this)};c.prototype.notifyNext= function(a,b,c,d,g){this.resultSelector?this._tryNotifyNext(a,b,c,d):this.destination.next(b)};c.prototype._tryNotifyNext=function(a,b,c,d){var g;try{g=this.resultSelector(a,b,c,d)}catch(k){this.destination.error(k);return}this.destination.next(g)};return c}(e.OuterSubscriber)},function(e,h,a){var l=function(a,b){function d(){this.constructor=a}for(var g in b)b.hasOwnProperty(g)&&(a[g]=b[g]);a.prototype=null===b?Object.create(b):(d.prototype=b.prototype,new d)};e=a(2);var k=a(183),d=a(6);h.take=function(a){return 0=== a?new d.EmptyObservable:this.lift(new g(a))};var g=function(){function a(b){this.total=b;if(0>this.total)throw new k.ArgumentOutOfRangeError;}a.prototype.call=function(a){return new b(a,this.total)};return a}(),b=function(a){function b(d,f){a.call(this,d);this.total=f;this.count=0}l(b,a);b.prototype._next=function(a){var b=this.total;++this.count<=b&&(this.destination.next(a),this.count===b&&this.destination.complete())};return b}(e.Subscriber)},function(e,h,a){var l=function(a,c){function d(){this.constructor= a}for(var g in c)c.hasOwnProperty(g)&&(a[g]=c[g]);a.prototype=null===c?Object.create(c):(d.prototype=c.prototype,new d)};e=a(24);var k=a(29);h.takeUntil=function(a){return this.lift(new d(a))};var d=function(){function a(b){this.notifier=b}a.prototype.call=function(a){return new g(a,this.notifier)};return a}(),g=function(a){function c(c,d){a.call(this,c);this.notifier=d;this.add(k.subscribeToResult(this,d))}l(c,a);c.prototype.notifyNext=function(a,b,c,d,g){this.complete()};c.prototype.notifyComplete= function(){};return c}(e.OuterSubscriber)},function(e,h,a){var l=function(a,b){function d(){this.constructor=a}for(var g in b)b.hasOwnProperty(g)&&(a[g]=b[g]);a.prototype=null===b?Object.create(b):(d.prototype=b.prototype,new d)},k=a(26),d=a(77);e=a(2);h.timeout=function(a,b,e){void 0===b&&(b=null);void 0===e&&(e=k.asap);var h=d.isDate(a);a=h?+a-e.now():Math.abs(a);return this.lift(new g(a,h,b,e))};var g=function(){function a(b,c,d,g){this.waitFor=b;this.absoluteTimeout=c;this.errorToSend=d;this.scheduler= g}a.prototype.call=function(a){return new b(a,this.absoluteTimeout,this.waitFor,this.errorToSend,this.scheduler)};return a}(),b=function(a){function b(d,f,g,e,k){a.call(this,d);this.absoluteTimeout=f;this.waitFor=g;this.errorToSend=e;this.scheduler=k;this._previousIndex=this.index=0;this._hasCompleted=!1;this.scheduleTimeout()}l(b,a);Object.defineProperty(b.prototype,"previousIndex",{get:function(){return this._previousIndex},enumerable:!0,configurable:!0});Object.defineProperty(b.prototype,"hasCompleted", {get:function(){return this._hasCompleted},enumerable:!0,configurable:!0});b.dispatchTimeout=function(a){var b=a.subscriber;a=a.index;b.hasCompleted||b.previousIndex!==a||b.notifyTimeout()};b.prototype.scheduleTimeout=function(){var a=this.index;this.scheduler.schedule(b.dispatchTimeout,this.waitFor,{subscriber:this,index:a});this.index++;this._previousIndex=a};b.prototype._next=function(a){this.destination.next(a);this.absoluteTimeout||this.scheduleTimeout()};b.prototype._error=function(a){this.destination.error(a); this._hasCompleted=!0};b.prototype._complete=function(){this.destination.complete();this._hasCompleted=!0};b.prototype.notifyTimeout=function(){this.error(this.errorToSend||Error("timeout"))};return b}(e.Subscriber)},function(e,h,a){var l=function(a,g){function b(){this.constructor=a}for(var c in g)g.hasOwnProperty(c)&&(a[c]=g[c]);a.prototype=null===g?Object.create(g):(b.prototype=g.prototype,new b)},k=a(184);e=function(a){function g(){a.apply(this,arguments)}l(g,a);g.prototype._schedule=function(b, c){void 0===c&&(c=0);if(0<c)return a.prototype._schedule.call(this,b,c);this.delay=c;this.state=b;var f=this.scheduler;f.actions.push(this);f.scheduledId||(f.scheduledId=k.Immediate.setImmediate(function(){f.scheduledId=null;f.flush()}));return this};g.prototype._unsubscribe=function(){var b=this.scheduler,c=b.scheduledId,f=b.actions;a.prototype._unsubscribe.call(this);0===f.length&&(b.active=!1,null!=c&&(b.scheduledId=null,k.Immediate.clearImmediate(c)))};return g}(a(44).FutureAction);h.AsapAction= e},function(e,h,a){var l=function(a,g){function b(){this.constructor=a}for(var c in g)g.hasOwnProperty(c)&&(a[c]=g[c]);a.prototype=null===g?Object.create(g):(b.prototype=g.prototype,new b)},k=a(178);e=function(a){function g(){a.apply(this,arguments)}l(g,a);g.prototype.scheduleNow=function(a,c){return(new k.AsapAction(this,a)).schedule(c)};return g}(a(181).QueueScheduler);h.AsapScheduler=e},function(e,h,a){var l=function(a,d){function g(){this.constructor=a}for(var b in d)d.hasOwnProperty(b)&&(a[b]= d[b]);a.prototype=null===d?Object.create(d):(g.prototype=d.prototype,new g)};e=function(a){function d(){a.apply(this,arguments)}l(d,a);d.prototype._schedule=function(d,b){void 0===b&&(b=0);if(0<b)return a.prototype._schedule.call(this,d,b);this.delay=b;this.state=d;var c=this.scheduler;c.actions.push(this);c.flush();return this};return d}(a(44).FutureAction);h.QueueAction=e},function(e,h,a){var l=a(180),k=a(44);e=function(){function a(){this.active=!1;this.actions=[];this.scheduledId=null}a.prototype.now= function(){return Date.now()};a.prototype.flush=function(){if(!this.active&&!this.scheduledId){this.active=!0;for(var a=this.actions,b=void 0;b=a.shift();)b.execute();this.active=!1}};a.prototype.schedule=function(a,b,c){void 0===b&&(b=0);return 0>=b?this.scheduleNow(a,c):this.scheduleLater(a,b,c)};a.prototype.scheduleNow=function(a,b){return(new l.QueueAction(this,a)).schedule(b)};a.prototype.scheduleLater=function(a,b,c){return(new k.FutureAction(this,a)).schedule(c,b)};return a}();h.QueueScheduler= e},function(e,h,a){var l=function(a,d){function g(){this.constructor=a}for(var b in d)d.hasOwnProperty(b)&&(a[b]=d[b]);a.prototype=null===d?Object.create(d):(g.prototype=d.prototype,new g)};e=function(a){function d(d,b){a.call(this);this.subject=d;this.observer=b;this.isUnsubscribed=!1}l(d,a);d.prototype.unsubscribe=function(){if(!this.isUnsubscribed){this.isUnsubscribed=!0;var a=this.subject,b=a.observers;this.subject=null;b&&0!==b.length&&!a.isUnsubscribed&&(a=b.indexOf(this.observer),-1!==a&&b.splice(a, 1))}};return d}(a(5).Subscription);h.SubjectSubscription=e},function(e,h){var a=function(a,d){function g(){this.constructor=a}for(var b in d)d.hasOwnProperty(b)&&(a[b]=d[b]);a.prototype=null===d?Object.create(d):(g.prototype=d.prototype,new g)},l=function(e){function d(){e.call(this,"argument out of range");this.name="ArgumentOutOfRangeError"}a(d,e);return d}(Error);h.ArgumentOutOfRangeError=l},function(e,h,a){e=a(13);a=function(){function a(e){this.root=e;e.setImmediate&&"function"===typeof e.setImmediate? (this.setImmediate=e.setImmediate.bind(e),this.clearImmediate=e.clearImmediate.bind(e)):(this.nextHandle=1,this.tasksByHandle={},this.currentlyRunningATask=!1,this.canUseProcessNextTick()?this.setImmediate=this.createProcessNextTickSetImmediate():this.canUsePostMessage()?this.setImmediate=this.createPostMessageSetImmediate():this.canUseMessageChannel()?this.setImmediate=this.createMessageChannelSetImmediate():this.canUseReadyStateChange()?this.setImmediate=this.createReadyStateChangeSetImmediate(): this.setImmediate=this.createSetTimeoutSetImmediate(),e=function g(a){delete g.instance.tasksByHandle[a]},e.instance=this,this.clearImmediate=e)}a.prototype.identify=function(a){return this.root.Object.prototype.toString.call(a)};a.prototype.canUseProcessNextTick=function(){return"[object process]"===this.identify(this.root.process)};a.prototype.canUseMessageChannel=function(){return Boolean(this.root.MessageChannel)};a.prototype.canUseReadyStateChange=function(){var a=this.root.document;return Boolean(a&& "onreadystatechange"in a.createElement("script"))};a.prototype.canUsePostMessage=function(){var a=this.root;if(a.postMessage&&!a.importScripts){var d=!0,g=a.onmessage;a.onmessage=function(){d=!1};a.postMessage("","*");a.onmessage=g;return d}return!1};a.prototype.partiallyApplied=function(a){for(var d=[],g=1;g<arguments.length;g++)d[g-1]=arguments[g];g=function c(){var a=c.handler,d=c.args;"function"===typeof a?a.apply(void 0,d):(new Function(""+a))()};g.handler=a;g.args=d;return g};a.prototype.addFromSetImmediateArguments= function(a){this.tasksByHandle[this.nextHandle]=this.partiallyApplied.apply(void 0,a);return this.nextHandle++};a.prototype.createProcessNextTickSetImmediate=function(){var a=function g(){var a=g.instance,c=a.addFromSetImmediateArguments(arguments);a.root.process.nextTick(a.partiallyApplied(a.runIfPresent,c));return c};a.instance=this;return a};a.prototype.createPostMessageSetImmediate=function(){var a=this.root,d="setImmediate$"+a.Math.random()+"$",g=function c(f){var g=c.instance;f.source===a&& "string"===typeof f.data&&0===f.data.indexOf(d)&&g.runIfPresent(+f.data.slice(d.length))};g.instance=this;a.addEventListener("message",g,!1);g=function f(){var a=f,d=a.messagePrefix,a=a.instance,g=a.addFromSetImmediateArguments(arguments);a.root.postMessage(d+g,"*");return g};g.instance=this;g.messagePrefix=d;return g};a.prototype.runIfPresent=function(a){if(this.currentlyRunningATask)this.root.setTimeout(this.partiallyApplied(this.runIfPresent,a),0);else{var d=this.tasksByHandle[a];if(d){this.currentlyRunningATask= !0;try{d()}finally{this.clearImmediate(a),this.currentlyRunningATask=!1}}}};a.prototype.createMessageChannelSetImmediate=function(){var a=this,d=new this.root.MessageChannel;d.port1.onmessage=function(b){a.runIfPresent(b.data)};var g=function c(){var a=c,d=a.channel,a=a.instance.addFromSetImmediateArguments(arguments);d.port2.postMessage(a);return a};g.channel=d;g.instance=this;return g};a.prototype.createReadyStateChangeSetImmediate=function(){var a=function g(){var a=g.instance,c=a.root.document, f=c.documentElement,e=a.addFromSetImmediateArguments(arguments),k=c.createElement("script");k.onreadystatechange=function(){a.runIfPresent(e);k.onreadystatechange=null;f.removeChild(k);k=null};f.appendChild(k);return e};a.instance=this;return a};a.prototype.createSetTimeoutSetImmediate=function(){var a=function g(){var a=g.instance,c=a.addFromSetImmediateArguments(arguments);a.root.setTimeout(a.partiallyApplied(a.runIfPresent,c),0);return c};a.instance=this;return a};return a}();h.ImmediateDefinition= a;h.Immediate=new a(e.root)},function(e,h,a){var l="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol?"symbol":typeof a},k=a(2),d=a(46);h.toSubscriber=function(a,b,c){if(a&&"object"===("undefined"===typeof a?"undefined":l(a))){if(a instanceof k.Subscriber)return a;if("function"===typeof a[d.rxSubscriber])return a[d.rxSubscriber]()}return new k.Subscriber(a,b,c)}},function(e,h){e.exports= function(a){a.webpackPolyfill||(a.deprecate=function(){},a.paths=[],a.children=[],a.webpackPolyfill=1);return a}},function(e,h){function a(a){return function(e,d){return null==e?d:a*d+(1-a)*e}}e.exports=function(e,k){return e.map(function(a){return a.value.response}).filter(function(a){return 2E3<a.size}).map(function(a){return a.size/a.duration*8E3}).scan(a(k.alpha))}},function(e,h,a){function l(a,b){return"number"==typeof a&&0<a?a:b}function k(a,b){var c=2>=arguments.length||void 0===arguments[2]? 0:arguments[2];return x(a,function(a){return a/b<=1-c})||a[0]}function d(a,b){var c=q(a,function(a){return a.width>=b});return c?c.bitrate:Infinity}function g(a,b){return b?q(a,function(a){return a.lang===b}):null}function b(a,b){return a.filter(function(a){return a.type===b})}var c=a(4),f=a(5).Subscription,m=a(45).BehaviorSubject,u=a(25).combineLatestStatic,n=a(15).only,q=a(22),x=a(89),v=a(23),p=a(187),r={defaultLanguage:"fra",defaultSubtitle:"",defaultBufferSize:30,defaultBufferThreshold:.3};e.exports= function(a,e,h){function x(a){return F.distinctUntilChanged().map(function(b){return g(a,b)||a[0]})}function C(a){return J.distinctUntilChanged().map(function(b){return g(a,b)})}var t=v(3>=arguments.length||void 0===arguments[3]?{}:arguments[3],r),B=t.defaultSubtitle,A=t.defaultBufferSize,O=t.defaultBufferThreshold,G=t.initVideoBitrate,E=t.initAudioBitrate,H=h.videoWidth,L=h.inBackground,F=new m(t.defaultLanguage),J=new m(B),K={audio:new m(E||0),video:new m(G||0)},t=[p(b(a,"audio"),{alpha:.6}).multicast(K.audio), p(b(a,"video"),{alpha:.6}).multicast(K.video)],I=new f;t.forEach(function(a){return I.add(a.connect())});var M={audio:new m(Infinity),video:new m(Infinity)},R={audio:new m(Infinity),video:new m(Infinity)},P={audio:new m(A),video:new m(A),text:new m(A)};return{setLanguage:function(a){F.next(a)},setSubtitle:function(a){J.next(a)},getLanguage:function(){return F.value},getSubtitle:function(){return J.value},getAverageBitrates:function(){return K},getAudioMaxBitrate:function(){return R.audio.value},getVideoMaxBitrate:function(){return R.video.value}, getAudioBufferSize:function(){return P.audio.value},getVideoBufferSize:function(){return P.video.value},setAudioBitrate:function(a){M.audio.next(l(a,Infinity))},setVideoBitrate:function(a){M.video.next(l(a,Infinity))},setAudioMaxBitrate:function(a){R.audio.next(l(a,Infinity))},setVideoMaxBitrate:function(a){R.video.next(l(a,Infinity))},setAudioBufferSize:function(a){P.audio.next(l(a,A))},setVideoBufferSize:function(a){P.video.next(l(a,A))},getBufferAdapters:function(a){var b=a.type,f=a.bitrates,g= a.representations;a=g[0];var e=void 0;if(1<g.length){a=M[b];var e=R[b],h=K[b].map(function(a,b){var c=void 0,c=0===b?0:O;return k(f,a,c)}).distinctUntilChanged().debounceTime(2E3).startWith(k(f,K[b].getValue(),0));"video"==b&&(e=u(e,H,L,function(a,b,c){if(c)return f[0];b=d(g,b);return b<a?b:a}));e=u(a,e,h,function(a,b,c){var d=void 0,d=Infinity>a?a:Infinity>b?Math.min(b,c):c;return q(g,function(a){return a.bitrate===k(f,d)})}).distinctUntilChanged(function(a,b){return a.id===b.id})["do"](function(a){return c.info("bitrate", b,a.bitrate)})}else e=n(a);return{representations:e,bufferSizes:P[b]||new m(A)}},getAdaptationsChoice:function(a,b){if("audio"==a)return x(b);if("text"==a)return C(b);if(1==b.length)return n(b[0]);throw Error("adaptive: unknown type "+a+" for adaptation chooser");},unsubscribe:function(){I&&(I.unsubscribe(),I=null)}}}},function(e,h,a){var l=Object.assign||function(a){for(var b=1;b<arguments.length;b++){var c=arguments[b],d;for(d in c)Object.prototype.hasOwnProperty.call(c,d)&&(a[d]=c[d])}return a}, k=a(4);a(3);var d=a(190).BufferingQueue,g=a(31).BufferedRanges,b=a(1).Observable,c=a(10).Subject,f=a(25).combineLatestStatic,m=a(11).mergeStatic,u=a(6).EmptyObservable.create,n=a(154).FromObservable.create,q=a(41).TimerObservable.create,x=a(212).SimpleSet;h=a(83);var v=h.IndexHandler,p=h.OutOfIndexError;e.exports={Buffer:function(a){function e(a,b){for(var c=a.ts,d=a.buffered,f=d.getRange(c),d=d.getOuterRanges(c),g=[],h=0;h<d.length;h++){var l=d[h];c-b<l.end?g.push(l):c+b>l.start&&g.push(l)}f&&(k.debug("buffer: gc removing part of inner range", g),c-b>f.start&&g.push({start:f.start,end:c-b}),c+b<f.end&&g.push({start:c+b,end:f.end}));return g}function h(){k.warn("buffer: running garbage collector");return G.take(1).flatMap(function(a){var b=e(a,240);0===b.length&&(b=e(a,30));k.debug("buffer: gc cleaning",b);return n(b.map(function(a){return M.removeBuffer(a)})).concatAll()})}function z(a){var b=a.parsed.blob;return M.appendBuffer(b)["catch"](function(a){if("QuotaExceededError"!==a.name)throw a;return h().flatMap(function(){return M.appendBuffer(b)})})} function D(a){function c(a){if(e.test(a.getId()))return!1;if(a.isInitSegment()||0>a.getTime())return!0;var b=d.scale(a.getTime()),f=d.scale(a.getDuration());return(b=I.hasRange(b,f))?1.5*b.bitrate<a.getRepresentation().bitrate:!0}var d=new v(B,a),e=new x,h=f(G,K).flatMap(function(b,f){var h=b[0],l=b[1],m=new g(t.buffered);E&&!I.equals(m)&&(k.debug("intersect new buffer",C),I.intersect(m));var q=void 0;try{var n=d,v=[];0===f&&(k.debug("add init segment",C),v.push(n.getInitSegment()));if(0===h.readyState)q= v;else{var A=h.ts,x=Math.max(0,Math.min(l,h.liveGap,(h.duration||Infinity)-A)),h=void 0,r=m.getGap(A),h=r>L&&Infinity>r?Math.min(r,F):0,G=I.getRange(A);if(G&&G.bitrate===a.bitrate){var K=Math.floor(G.end-A);K>h&&(h=K)}var y=n.getSegments(A,h,x),q=v.concat(y)}q=q.filter(c)}catch(w){if(w instanceof p)return H.next({type:"out-of-index",value:w}),u();throw w;}for(m=0;m<q.length;m++)e.add(q[m].getId());return q}).concatMap(function(a){return A({segment:a})}).concatMap(z,function(b){var c=b.parsed;e.remove(b.segment.getId()); var f=c.timescale;f&&d.setTimescale(f);var f=c.nextSegments,c=c.currentSegment,g=void 0,g=f?d.insertNewSegments(f,c):[];c&&I.insert(a.bitrate,d.scale(c.ts),d.scale(c.ts+c.d));return{type:"pipeline",value:l({bufferType:C,addedSegments:g},b)}});return m(h,H)["catch"](function(c){if(412!==c.code)throw c;return b.of({type:"precondition-failed",value:c}).concat(q(2E3)).concat(D(a))}).startWith({type:"buffer",value:{bufferType:C,adaptation:B,representation:a}})}var C=a.bufferType,t=a.sourceBuffer,B=a.adaptation, A=a.pipeline,O=a.adapters,G=a.timings;a=a.seekings;var E="audio"==C||"video"==C,H=new c,L="video"==C?4:1,F="video"==C?6:1,J=O.representations,K=O.bufferSizes,I=new g,M=new d(t);return f(J,a,function(a){return a}).switchMap(D)["finally"](function(){return M.dispose()})},EmptyBuffer:function(a){return b.of({type:"buffer",value:{bufferType:a,adaptation:null,representation:null}})}}},function(e,h,a){var l=a(10).Subject;h=function(){function a(d){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function"); this.buffer=d;this.queue=[];this.flushing=null;this._onUpdate=this.onUpdate.bind(this);this._onError=this.onError.bind(this);this._flush=this.flush.bind(this);this.buffer.addEventListener("update",this._onUpdate);this.buffer.addEventListener("error",this._onError);this.buffer.addEventListener("updateend",this._flush)}a.prototype.dispose=function(){this.buffer.removeEventListener("update",this._onUpdate);this.buffer.removeEventListener("error",this._onError);this.buffer.removeEventListener("updateend", this._flush);this.buffer=null;this.queue.length=0;this.flushing=null};a.prototype.onUpdate=function(a){this.flushing&&(this.flushing.next(a),this.flushing.complete(),this.flushing=null)};a.prototype.onError=function(a){if(this.flushing){var g=void 0,g=a.target&&a.target.error?a.target.error:Error("buffer: error event");this.flushing.error(g);this.flushing=null}};a.prototype.queueAction=function(a,g){var b=new l;1===this.queue.unshift({type:a,args:g,subj:b})&&this.flush();return b};a.prototype.appendBuffer= function(a){return this.queueAction("append",a)};a.prototype.removeBuffer=function(a){return this.queueAction("remove",{start:a.start,end:a.end})};a.prototype.appendStream=function(a){return this.queueAction("stream",a)};a.prototype.flush=function(){if(!this.flushing&&0!==this.queue.length&&!this.buffer.updating){var a=this.queue.pop(),g=a.type,b=a.args;this.flushing=a.subj;switch(g){case "append":this.buffer.appendBuffer(b);break;case "stream":this.buffer.appendStream(b);break;case "remove":this.buffer.removeBuffer(b.start, b.end)}}};return a}();e.exports={BufferingQueue:h}},function(e,h){var a=function(){function a(){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.cache={}}a.prototype.add=function(a,d){var g=a.segment;g.isInitSegment()&&(this.cache[g.getId()]=d)};a.prototype.get=function(a){a=a.segment;return a.isInitSegment()&&(a=this.cache[a.getId()],null!=a)?a:null};return a}();e.exports={InitializationSegmentCache:a}},function(e,h,a){var l=a(11).mergeStatic,k=a(155).IntervalObservable.create; h=a(14);var d=h.visibilityChange,g=h.videoSizeChange,b=window.devicePixelRatio||1;e.exports=function(a){var f=d().filter(function(a){return!1===a}),e=d().debounceTime(6E4).filter(function(a){return!0===a}),f=l(f,e).startWith(!1);return{videoWidth:l(k(2E4),g().debounceTime(500)).startWith("init").map(function(){return a.clientWidth*b}).distinctUntilChanged(),inBackground:f}}},function(e,h,a){function l(a,d){if("function"!==typeof d&&null!==d)throw new TypeError("Super expression must either be null or a function, not "+ typeof d);a.prototype=Object.create(d&&d.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});d&&(Object.setPrototypeOf?Object.setPrototypeOf(a,d):a.__proto__=d)}h=function(a){function d(){if(!(this instanceof d))throw new TypeError("Cannot call a class as a function");var g=a.apply(this,arguments);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!g||"object"!==typeof g&&"function"!==typeof g?this:g}l(d,a);d.getLiveEdge=function(){throw Error("not implemented"); };d.prototype.addSegment=function(a){this.index.timeline.push(a);return!0};return d}(a(84));e.exports=h},function(e,h,a){var l=a(32).Segment;h=function(){function a(d,g,b){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.adaptation=d;this.representation=g;this.index=b}a.getLiveEdge=function(){throw Error("not implemented");};a.prototype.checkRange=function(a){var g=this.index,b=g.list;a=Math.floor(a/g.duration);return 0<=a&&a<b.length};a.prototype.createSegment= function(a,g){var b=this.index,c=b.list[a];return l.create(this.adaptation,this.representation,a,c.media,g,b.duration,0,c.range,null,!1)};a.prototype.getSegments=function(a,g){for(var b=this.index.duration,c=Math.floor(g/b),f=[],e=Math.floor(a/b);e<c;)f.push(this.createSegment(e,e*b)),e++;return f};a.prototype.addSegment=function(){return!1};return a}();e.exports=h},function(e,h,a){var l=a(32).Segment;h=function(){function a(d,g,b){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function"); this.adaptation=d;this.representation=g;this.index=b}a.getLiveEdge=function(a,g){return Date.now()/1E3-g.availabilityStartTime-g.suggestedPresentationDelay};a.prototype.checkRange=function(){return!0};a.prototype.createSegment=function(a){var g=this.index,b=g.startNumber,g=g.duration;a=Math.floor(a/g)+(null==b?1:b);return l.create(this.adaptation,this.representation,a,this.index.media,a*g,this.index.duration,a,null,null,!1)};a.prototype.getSegments=function(a,g){for(var b=this.index.duration,c=[], f=a;f<=g;f+=b)c.push(this.createSegment(f));return c};a.prototype.addSegment=function(){return!1};return a}();e.exports=h},function(e,h,a){function l(a,g,e){function h(a){e.next(a)}function l(a){var d=B.get(a);return null===d?c(z(a).timeout(t,f),A):d&&"function"==typeof d.subscribe?d["catch"](function(){return c(z(a).timeout(t,f),A)}):b.of(d)}function r(b,c){var d=k({response:c},b);B.add(b,c);u.schedule(h,0,{type:a,value:d});return d}function y(a,b){return k({parsed:b},a)}var w=g.resolver,z=g.loader, D=g.parser,C=3>=arguments.length||void 0===arguments[3]?{}:arguments[3];D||(D=b.of);z||(z=b.of);w||(w=b.of);var C=d(C,{totalRetry:3,timeout:1E4,cache:m}),t=C.timeout,B=C.cache,A={retryDelay:500,totalRetry:C.totalRetry,shouldRetry:function(a){return 500<=a.code||200>a.code||/timeout/.test(a.message)||/request: error event/.test(a.message)}};return function(a){return w(a).flatMap(l,r).flatMap(D,y)}}var k=Object.assign||function(a){for(var b=1;b<arguments.length;b++){var c=arguments[b],d;for(d in c)Object.prototype.hasOwnProperty.call(c, d)&&(a[d]=c[d])}return a},d=a(23),g=a(10).Subject;h=a(26).asap;var b=a(1).Observable,c=a(215).retryWithBackoff,f=Error("timeout"),m={add:function(){},get:function(){return null}},u=h;e.exports=function(){var a=new g;return{createPipelines:function(b){var c=1>=arguments.length||void 0===arguments[1]?{}:arguments[1],d={requiresMediaSource:function(){return!0!==b.directFile}},f;for(f in b)d[f]=l(f,b[f],a,c[f]);return d},metrics:a}}},function(e,h,a){function l(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return!b||"object"!==typeof b&&"function"!==typeof b?a:b}function k(a,b){if("function"!==typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function d(a,b){return b?"seeking"==b.name?"SEEKING":"BUFFERING":a?"PLAYING":"PAUSED"}function g(){}function b(a){y(a.man,"player: no manifest loaded")} function c(a,b){return a.filter(function(a){return a.type==b}).map(function(a){return a.value})}var f=Object.assign||function(a){for(var b=1;b<arguments.length;b++){var c=arguments[b],d;for(d in c)Object.prototype.hasOwnProperty.call(c,d)&&(a[d]=c[d])}return a},m=a(4),u=a(23),n=a(5).Subscription,q=a(10).Subject,x=a(45).BehaviorSubject,v=a(25).combineLatestStatic,p=a(15).on;h=a(35);var r=a(213),y=a(3),w=a(14),z=w.HTMLVideoElement_,D=w.exitFullscreen,C=w.requestFullscreen,t=w.isFullscreen,B=w.onFullscreenChange, w=a(85),A=w.getEmptyTimings,O=w.timingsSampler,G=w.toWallClockTime,E=w.fromWallClockTime,H=w.getLiveGap,L=a(191).InitializationSegmentCache,F=a(31).BufferedRanges,J=a(201).parseTimeFragment,K=a(192),I=a(48),M=a(206),R=a(196),P=a(188),Q=a(199),T=a(82);a=function(a){function e(b){if(!(this instanceof e))throw new TypeError("Cannot call a class as a function");var c=b.videoElement,d=b.transport,f=b.transportOptions,g=b.defaultLanguage,k=b.defaultSubtitle,h=b.initVideoBitrate;b=b.initAudioBitrate;var n= l(this,a.call(this));n.defaultTransport=d;n.defaultTransportOptions=f||{};c||(c=document.createElement("video"));y(c instanceof z,"requires an actual HTMLVideoElement");c.preload="auto";n.version="2.0.0-alpha3";n.video=c;n.fullscreen=B(c).subscribe(function(){return n.trigger("fullscreenChange",n.isFullscreen())});n.playing=new x;n.stream=new q;var f=R(),d=f.createPipelines,f=f.metrics,A=O(c),c=K(c);n.createPipelines=d;n.metrics=f;n.timings=A;n.adaptive=P(f,A,c,{initVideoBitrate:h,initAudioBitrate:b, defaultLanguage:g,defaultSubtitle:k});n.muted=.1;n._setPlayerState("STOPPED");n._resetStates();n.log=m;return n}k(e,a);e.prototype._resetStates=function(){this.man=null;this.reps={video:null,audio:null,text:null};this.adas={video:null,audio:null,text:null};this.evts={};this.frag={start:null,end:null}};e.prototype._unsubscribe=function(){this.subscriptions&&(this.subscriptions.unsubscribe(),this.subscriptions=null)};e.prototype.stop=function(){"STOPPED"!==this.state&&(this._resetStates(),this._unsubscribe(), this._setPlayerState("STOPPED"))};e.prototype.dispose=function(){this.stop();this.metrics.unsubscribe();this.adaptive.unsubscribe();this.fullscreen.unsubscribe();this.stream.unsubscribe();this.video=this.createPipelines=this.timings=this.stream=this.fullscreen=this.adaptive=this.metrics=null};e.prototype._recordState=function(a,b){this.evts[a]!==b&&(this.evts[a]=b,this.trigger(a+"Change",b))};e.prototype._parseOptions=function(a){var b=a=u(f({},a),{transport:this.defaultTransport,transportOptions:{}, keySystems:[],timeFragment:{},subtitles:[],autoPlay:!1,directFile:!1}),c=b.transport,d=b.url,e=b.keySystems,g=b.timeFragment,k=b.subtitles,h=a,b=h.transportOptions,l=h.manifests,m=h.autoPlay,h=h.directFile,g=J(g);h&&(c="directfile");y(!!l^!!d,"player: you have to pass either a url or a list of manifests");l&&(e=l[0],d=e.url,k=e.subtitles||[],e=l.map(function(a){return a.keySystem}).filter(Boolean));"string"==typeof c&&(c=M[c]);"function"==typeof c&&(c=c(u(b,this.defaultTransportOptions)));y(c,"player: transport "+ a.transport+" is not supported");return{url:d,keySystems:e,subtitles:k,timeFragment:g,autoPlay:m,transport:c}};e.prototype.loadVideo=function(){var a=0>=arguments.length||void 0===arguments[0]?{}:arguments[0],a=this._parseOptions(a);m.info("loadvideo",a);var b=a.url,f=a.keySystems,e=a.subtitles,k=a.timeFragment,h=a.autoPlay,a=a.transport;this.stop();this.frag=k;this.playing.next(h);var l=this.createPipelines(a,{audio:{cache:new L},video:{cache:new L}}),a=this.timings,q=this.video,b=Q({url:b,keySystems:f, subtitles:e,timings:a,timeFragment:k,adaptive:this.adaptive,pipelines:l,videoElement:q,autoPlay:h}).publish(),e=c(b,"stalled").startWith(null),f=c(b,"loaded").take(1).share(),e=f.mapTo("LOADED").concat(v(this.playing,e,d)).distinctUntilChanged().startWith("LOADING"),q=p(q,["play","pause"]),k=this.subscriptions=new n;k.add(q.subscribe(this._playPauseNext.bind(this),g));k.add(e.subscribe(this._setPlayerState.bind(this),g));k.add(a.subscribe(this._triggerTimeChange.bind(this),g));k.add(b.subscribe(this._streamNext.bind(this), this._streamError.bind(this),this._streamComplete.bind(this)));k.add(b.connect());this.subscriptions?this._triggerTimeChange():k.unsubscribe();return f};e.prototype._streamNext=function(a){var b=a.type,c=a.value;"buffer"==b&&this._bufferNext(c);"manifest"==b&&this._manifestNext(c);"pipeline"==b&&this.trigger("progress",c.segment);this.stream.next(a)};e.prototype._streamError=function(a){this._resetStates();this.trigger("error",a);this._setPlayerState("STOPPED");this._unsubscribe();this.stream.next({type:"error", value:a})};e.prototype._streamComplete=function(){this._resetStates();this._setPlayerState("ENDED");this._unsubscribe();this.stream.next({type:"ended",value:null})};e.prototype._manifestNext=function(a){this.man=a;this.trigger("manifestChange",a)};e.prototype._bufferNext=function(a){var b=a.bufferType,c=a.adaptation;a=a.representation;this.reps[b]=a;this.adas[b]=c;"text"==b&&this._recordState("subtitle",c&&c.lang||"");"video"==b&&this._recordState("videoBitrate",a&&a.bitrate||-1);"audio"==b&&(this._recordState("language", c&&c.lang||""),this._recordState("audioBitrate",a&&a.bitrate||-1))};e.prototype._playPauseNext=function(a){this.playing.next("play"==a.type)};e.prototype._setPlayerState=function(a){this.state!==a&&(this.state=a,m.info("playerStateChange",a),this.trigger("playerStateChange",a))};e.prototype._triggerTimeChange=function(a){this.man&&a?(this.man.isLive&&0<a.ts&&(a.wallClockTime=G(a.ts,this.man),a.liveGap=H(a.ts,this.man)),this.trigger("currentTimeChange",a)):this.trigger("currentTimeChange",A())};e.prototype.getManifest= function(){return this.man};e.prototype.getVideoElement=function(){return this.video};e.prototype.getNativeTextTrack=function(){return 0<this.video.textTracks.length?this.video.textTracks[0]:null};e.prototype.getPlayerState=function(){return this.state};e.prototype.isLive=function(){b(this);return this.man.isLive};e.prototype.getUrl=function(){b(this);return this.man.locations[0]};e.prototype.getVideoDuration=function(){return this.video.duration};e.prototype.getVideoLoadedTime=function(){return(new F(this.video.buffered)).getSize(this.video.currentTime)}; e.prototype.getVideoPlayedTime=function(){return(new F(this.video.buffered)).getLoaded(this.video.currentTime)};e.prototype.getCurrentTime=function(){if(!this.man)return 0;var a=this.video.currentTime;return this.man.isLive?G(a,this.man):a};e.prototype.getStartTime=function(){return this.frag.start};e.prototype.getEndTime=function(){return this.frag.end};e.prototype.getPlaybackRate=function(){return this.video.playbackRate};e.prototype.getVolume=function(){return this.video.volume};e.prototype.isFullscreen= function(){return t()};e.prototype.getAvailableLanguages=function(){return this.man&&I.getAvailableLanguages(this.man)||[]};e.prototype.getAvailableSubtitles=function(){return this.man&&I.getAvailableSubtitles(this.man)||[]};e.prototype.getLanguage=function(){return this.adaptive.getLanguage()};e.prototype.getSubtitle=function(){return this.adaptive.getSubtitle()};e.prototype.getAvailableVideoBitrates=function(){var a=I.getAdaptationsByType(this.man,"video");return a[0]&&a[0].bitrates.slice()||[]}; e.prototype.getAvailableAudioBitrates=function(){var a=this.adas.audio;return a&&a.bitrates.slice()||[]};e.prototype.getVideoBitrate=function(){return this.evts.videoBitrate};e.prototype.getAudioBitrate=function(){return this.evts.audioBitrate};e.prototype.getVideoMaxBitrate=function(){return this.adaptive.getVideoMaxBitrate()};e.prototype.getAudioMaxBitrate=function(){return this.adaptive.getAudioMaxBitrate()};e.prototype.getVideoBufferSize=function(){return this.adaptive.getVideoBufferSize()};e.prototype.getAudioBufferSize= function(){return this.adaptive.getAudioBufferSize()};e.prototype.getAverageBitrates=function(){return this.adaptive.getAverageBitrates()};e.prototype.getMetrics=function(){return this.metrics};e.prototype.getTimings=function(){return this.timings};e.prototype.play=function(){this.video.play()};e.prototype.pause=function(){this.video.pause()};e.prototype.setPlaybackRate=function(a){this.video.playbackRate=a};e.prototype.goToStart=function(){return this.seekTo(this.getStartTime())};e.prototype.seekTo= function(a){y(this.man);var b=this.video.currentTime;this.man.isLive&&(a=E(a,this.man));return a!==b?(m.info("seek to",a),this.video.currentTime=a):b};e.prototype.setFullscreen=function(){!1===(0>=arguments.length||void 0===arguments[0]?!0:arguments[0])?D():C(this.video)};e.prototype.setVolume=function(a){a!==this.video.volume&&(this.video.volume=a,this.trigger("volumeChange",a))};e.prototype.mute=function(){this.muted=this.getVolume()||.1;this.setVolume(0)};e.prototype.unMute=function(){0===this.getVolume()&& this.setVolume(this.muted)};e.prototype.setLanguage=function(a){y(0<=this.getAvailableLanguages().indexOf(a),"player: unknown language");this.adaptive.setLanguage(a)};e.prototype.setSubtitle=function(a){y(!a||0<=this.getAvailableSubtitles().indexOf(a),"player: unknown subtitle");this.adaptive.setSubtitle(a||"");a||this._recordState("subtitle","")};e.prototype.setVideoBitrate=function(a){y(0===a||0<=this.getAvailableVideoBitrates().indexOf(a),"player: video bitrate unavailable");this.adaptive.setVideoBitrate(a)}; e.prototype.setAudioBitrate=function(a){y(0===a||0<=this.getAvailableAudioBitrates().indexOf(a),"player: audio bitrate unavailable");this.adaptive.setAudioBitrate(a)};e.prototype.setVideoMaxBitrate=function(a){this.adaptive.setVideoMaxBitrate(a)};e.prototype.setAudioMaxBitrate=function(a){this.adaptive.setAudioMaxBitrate(a)};e.prototype.setVideoBufferSize=function(a){this.adaptive.setVideoBufferSize(a)};e.prototype.setAudioBufferSize=function(a){this.adaptive.setAudioBufferSize(a)};e.prototype.asObservable= function(){return this.stream};e.prototype.getDebug=function(){return r.getDebug(this)};e.prototype.showDebug=function(){r.showDebug(this,this.video)};e.prototype.hideDebug=function(){r.hideDebug()};e.prototype.toggleDebug=function(){r.toggleDebug(this,this.video)};e.prototype.getCurrentKeySystem=function(){return T.getCurrentKeySystem()};return e}(h);e.exports=a},function(e,h,a){function l(a,c){if("function"!==typeof c&&null!==c)throw new TypeError("Super expression must either be null or a function, not "+ typeof c);a.prototype=Object.create(c&&c.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});c&&(Object.setPrototypeOf?Object.setPrototypeOf(a,c):a.__proto__=c)}h=a(35);var k=a(1).Observable,d=a(31).BufferedRanges,g=a(3);a=function(a){function c(f){if(!(this instanceof c))throw new TypeError("Cannot call a class as a function");var e;e=a.call(this);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");e=!e||"object"!==typeof e&&"function"!== typeof e?this:e;e.codec=f;e.updating=!1;e.readyState="opened";e.buffered=new d;return e}l(c,a);c.prototype.appendBuffer=function(a){var b=this;this._lock(function(){return b._append(a)})};c.prototype.remove=function(a,b){var c=this;this._lock(function(){return c._remove(a,b)})};c.prototype.abort=function(){this.remove(0,Infinity);this.updating=!1;this.readyState="closed";this._abort()};c.prototype._append=function(){};c.prototype._remove=function(){};c.prototype._abort=function(){};c.prototype._lock= function(a){var b=this;g(!this.updating,"text-buffer: cannot remove while updating");this.updating=!0;this.trigger("updatestart");(a=a())&&"function"==a.subscribe||(a=k.of(a));a.subscribe(function(){return b._unlock("update")},function(a){return b._unlock("error",a)})};c.prototype._unlock=function(a,b){this.updating=!1;this.trigger(a,b);this.trigger("updateend")};return c}(h);e.exports={AbstractSourceBuffer:a}},function(e,h,a){function l(a){return"audio"==a||"video"==a}var k=a(4),d=a(3);h=a(85);var g= h.getLiveGap,b=h.seekingsSampler,c=h.fromWallClockTime,f=a(15).retryWithBackoff,m=a(1).Observable;h=a(15);var u=h.first,n=h.on,q=a(6).EmptyObservable.create,x=a(11).mergeStatic,v=a(25).combineLatestStatic,p=Math.min;h=a(14);var r=h.MediaSource_,y=h.sourceOpen,w=h.canPlay,z=h.canSeek,D=h.clearVideoSrc,C=a(200),t=a(83).getLiveEdge,B=a(32).clearSegmentCache;h=a(189);var A=h.Buffer,O=h.EmptyBuffer;h=a(82);var G=h.createEME,E=h.onEncrypted,H=h.EMEError;a=a(48);var L=a.normalizeManifest,F=a.mergeManifestsIndex, J=a.mutateManifestLiveGap,K=a.getAdaptations,I={totalRetry:3,retryDelay:250,resetDelay:6E4,shouldRetry:function(a,b){if(/MEDIA_ERR/.test(a.message)||a instanceof H)return!1;k.warn("stream retry",a,b);return!0}};e.exports=function(a){function e(a,b,c){var d=c.type;c=c.codec;var f=void 0;if(l(d))ba[d]?f=ba[d]:(k.info("add sourcebuffer",c),f=b.addSourceBuffer(c),ba[d]=f);else{if(b=X[d])try{b.abort()}catch(g){k.warn(g)}finally{delete X[d]}if("text"==d)k.info("add text sourcebuffer",c),f=new C(a,c);else throw a= "stream: unknown buffer type "+d,k.error(a),Error(a);X[d]=f}return f}function h(a,b,c){a=c.type;c=void 0;var d=l(a);d?(c=ba[a],delete ba[a]):(c=X[a],delete X[a]);if(c)try{c.abort(),d&&b.removeSourceBuffer(c)}catch(f){k.warn(f)}}function H(a){var c=ga.map(function(b){var c=void 0;na?(c=b.clone(),c.ts=p(b.ts,aa),c.duration=p(b.duration,aa)):c=b;c.liveGap=g(b.ts,a);return c}),d=b(c);return{timings:c,seekings:d}}function T(a,b,c,d){var f=b.type;return ha.getAdaptationsChoice(f,b.adaptations).switchMap(function(g){if(!g)return h(N, a,b),O(f);var m=ha.getBufferAdapters(g);g=A({bufferType:f,sourceBuffer:e(N,a,b),pipeline:da[f],adaptation:g,timings:c,seekings:d,adapters:m});return l(f)?g:g["catch"](function(a){k.error("buffer",f,"has crashed",a);return q()})})}function V(a){var b=z(N)["do"](function(){var b=a.duration,f=ma,e=aa,g=/^\d*(\.\d+)? ?%$/;"string"==typeof f&&g.test(f)&&(f=parseFloat(f)/100*b);"string"==typeof e&&g.test(e)&&(aa=parseFloat(e)/100*b);if(Infinity===e||"100%"===e)e=b;a.isLive?f=f?c(f,a):t(a):d(f<b&&e<=b,"stream: bad startTime and endTime"); k.info("set initial time",f);N.playbackRate=1;N.currentTime=f}),f=w(N)["do"](function(){k.info("canplay event");ia&&N.play();ia=!0});return u(v(b,f)).mapTo({type:"loaded",value:!0})}function S(){return ea&&ea.length?G(N,ea):E(N).map(function(){k.error("eme: ciphered media and no keySystem passed");throw Error("eme: ciphered media and no keySystem passed");})}function W(a,b){var c=b.changePlaybackRate,d=void 0===c?!0:c;return a.distinctUntilChanged(function(a,b){var c=b.stalled,f=a.stalled,e=void 0, e=f||c?f&&c?f.name==c.name:!1:!0;!e&&d&&(f?(k.info("resume playback",b.ts,b.name),N.playbackRate=f.playback):(k.info("stop playback",b.ts,b.name),N.playbackRate=0));c&&(c=b.buffered.getNextRangeGap(b.ts),1>c&&(f=b.ts+c+1/60,N.currentTime=f,k.warn("discontinuity seek",b.ts,c,f)));return e}).map(function(a){return{type:"stalled",value:a.stalled}})}function Y(a){return a&&"out-of-index"==a.type}function U(a,b){if(Y(b))return k.info("out of index"),ja({url:a.locations[0]}).map(function(b){b=b.parsed; return{type:"manifest",value:F(a,L(b.url,b.manifest,fa))}});b&&"precondition-failed"==b.type&&(J(a,1),k.warn("precondition failed",a.presentationLiveGap));return m.of(b)}function Z(a,b,c,d){var f=K(b).map(function(b){return T(a,b,c,d)}),f=x.apply(null,f);return b.isLive?f.distinctUntilChanged(function(a,b){return Y(b)&&Y(a)}).concatMap(function(a){return U(b,a)}):f}function ka(){return n(N,"error").flatMap(function(){var a="stream: video element MEDIA_ERR code "+N.error.code;k.error(a);throw Error(a); })}var la=a.url,ea=a.keySystems,fa=a.subtitles,ga=a.timings,ca=a.timeFragment,ha=a.adaptive,da=a.pipelines,N=a.videoElement,ia=a.autoPlay;B();var ma=ca.start,na=Infinity>aa,aa=ca.end,ja=da.manifest,ba={},X={};a=ga.filter(function(a){var b=a.ts;a=a.duration;return 0<a&&.2>p(a,aa)-b});ca=f(function(a){var b=a.url,c=a.mediaSource;a=c?y(c):m.of(null);return v(ja({url:b}),a).flatMap(function(a){a=a[0].parsed;a=L(a.url,a.manifest,fa);if(c){var b=void 0,b=Infinity===a.duration?Number.MAX_VALUE:a.duration; c.duration!==b&&(c.duration=b,k.info("set duration",c.duration))}var b=H(a),d=b.timings,f=b.seekings,b=m.of({type:"manifest",value:a}),e=S(),g=W(d,{changePlayback:da.requiresMediaSource()}),g=V(a).concat(g);a=Z(c,a,d,f);d=ka();return x(b,g,e,a,d)})},I);return function(a,b){return m.create(function(c){d(r,"player: browser is required to support MediaSource");var f=void 0,e=void 0;da.requiresMediaSource()?(f=new r,e=URL.createObjectURL(f)):(f=null,e=a);b.src=e;c.next({url:a,mediaSource:f});k.info("create mediasource object", e);return function(){if(f&&"closed"!=f.readyState)for(var a=f,c=a.readyState,a=a.sourceBuffers,d=0;d<a.length;d++){var g=a[d];try{"open"==c&&g.abort(),f.removeSourceBuffer(g)}catch(h){k.warn("error while disposing souceBuffer",h)}}Object.keys(X).forEach(function(a){a=X[a];try{a.abort()}catch(b){k.warn("error while disposing souceBuffer",b)}});D(b);if(e)try{URL.revokeObjectURL(e)}catch(h){k.warn("error while revoking ObjectURL",h)}e=f=X=ba=null}})}(la,N).flatMap(ca).takeUntil(a)}},function(e,h,a){function l(a, b){if("function"!==typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}h=a(198).AbstractSourceBuffer;var k=a(14),d=k.addTextTrack,g=k.isVTTSupported,b=a(4),c=window.VTTCue||window.TextTrackCue;a=function(a){function e(b,c){if(!(this instanceof e))throw new TypeError("Cannot call a class as a function"); var g;g=a.call(this,c);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");g=!g||"object"!==typeof g&&"function"!==typeof g?this:g;g.video=b;g.codec=c;g.isVTT=/^text\/vtt/.test(c);var k=d(b),h=k.trackElement;g.track=k.track;g.trackElement=h;return g}l(e,a);e.prototype.createCuesFromArray=function(a){for(var b=[],d=0;d<a.length;d++){var f=a[d],e=f.start,g=f.end;(f=f.text)&&b.push(new c(e,g,f))}return b};e.prototype._append=function(a){var c=this;if(this.isVTT&& g())a=new Blob([a],{type:"text/vtt"}),a=URL.createObjectURL(a),this.trackElement?(this.trackElement.src=a,this.buffered.insert(0,Infinity)):b.warn("vtt subtitles not supported");else if(a=this.createCuesFromArray(a),0<a.length){var d=a[0],f=a[a.length-1],e=this.track.cues;0<e.length&&d.startTime<e[e.length-1].endTime&&this._remove(0,Infinity);a.forEach(function(a){return c.track.addCue(a)});this.buffered.insert(0,d.startTime,f.endTime)}};e.prototype._remove=function(a,b){for(var c=this.track,d=c.cues, f=0;f<d.length;f++){var e=d[f],g=e.startTime,k=e.endTime;g>=a&&g<=b&&k<=b&&c.removeCue(e)}this.buffered.remove(a,b)};e.prototype._abort=function(){var a=this.trackElement,b=this.video;a&&b&&b.hasChildNodes(a)&&b.removeChild(a);this.track.mode="disabled";this.size=0;this.video=this.track=this.trackElement=null};return e}(h);e.exports=a},function(e,h,a){function l(a){if(!a)return!1;a=a.replace(/^npt\:/,"").replace(/\.$/,"");var d=void 0,e=void 0,g=void 0;a=a.split(":");var k=a.length;switch(k){case 3:d= parseInt(a[0],10);e=parseInt(a[1],10);g=parseFloat(a[2]);break;case 2:d=0;e=parseInt(a[0],10);g=parseFloat(a[1]);break;case 1:e=d=0;g=parseFloat(a[0]);break;default:return!1}b(23>=d,c);b(59>=e,c);b(1>=k||60>g,c);return 3600*d+60*e+g}function k(a){if(!a)return!1;var d=void 0,e=void 0,g=void 0,k=void 0,h=void 0;a=a.split(":");switch(a.length){case 3:d=parseInt(a[0],10);e=parseInt(a[1],10);g=parseInt(a[2],10);h=k=0;break;case 4:d=parseInt(a[0],10);e=parseInt(a[1],10);g=parseInt(a[2],10);-1===a[3].indexOf(".")? (k=parseInt(a[3],10),h=0):(a=a[3].split("."),k=parseInt(a[0],10),h=parseInt(a[1],10));break;default:return!1}b(23>=d,c);b(59>=e,c);b(59>=g,c);return 3600*d+60*e+g+.001*k+1E-6*h}function d(a){return new Date(Date.parse(a))}function g(a){return a?a:!1}var b=a(3),c="Invalid MediaFragment";e.exports={parseTimeFragment:function(a){if("string"==typeof a){var e=a,h=e.split(",");b(2>=h.length,c);a=h[0]?h[0]:"";h=h[1]?h[1]:"";b((a||h)&&(!a||h||-1===e.indexOf(",")),c);a=a.replace(/^smpte(-25|-30|-30-drop)?\:/, "").replace("clock:","");var e=/^((npt\:)?((\d+\:(\d\d)\:(\d\d))|((\d\d)\:(\d\d))|(\d+))(\.\d*)?)?$/,n=/^(\d+\:\d\d\:\d\d(\:\d\d(\.\d\d)?)?)?$/,q=/^((\d{4})(-(\d{2})(-(\d{2})(T(\d{2})\:(\d{2})(\:(\d{2})(\.(\d+))?)?(Z|(([-\+])(\d{2})\:(\d{2})))?)?)?)?)?$/,x=/^(\d*(\.\d+)? ?%)?$/,v=void 0;if(e.test(a)&&e.test(h))v=l;else if(n.test(a)&&n.test(h))v=k;else if(q.test(a)&&q.test(h))v=d;else if(x.test(a)&&x.test(h))v=g;else throw Error(c);a=v(a);h=v(h);b(!1!==a||!1!==h,c);a={start:!1===a?"":a,end:!1===h? "":h}}else a={start:a.start,end:a.end};"string"==typeof a.start&&"string"==typeof a.end?(a.start||(a.start="0%"),a.end||(a.end="100%")):(a.start||(a.start=0),a.end||(a.end=Infinity));"string"==typeof a.start&&"string"==typeof a.end?(b(0<=parseFloat(a.start)&&100>=parseFloat(a.start),"player: startTime should be between 0% and 100%"),b(0<=parseFloat(a.end)&&100>=parseFloat(a.end),"player: endTime should be between 0% and 100%")):(b(("number"==typeof a.start||a.start instanceof Date)&&("number"==typeof a.end|| a.end instanceof Date),"player: timeFragment should have interface { start, end } where start and end are numbers or dates"),b(a.start<a.end,"player: startTime should be lower than endTime"),b(0<=a.start,"player: startTime should be greater than 0"));return a}}},function(e,h,a){function l(a){var b=a[0];return(a=a[1])&&Infinity!==a?"bytes="+ +b+"-"+ +a:"bytes="+ +b+"-"}function k(a){return function(b,c,d){b=d?parseInt(d,10):1;return m(""+a,b)}}var d=a(1).Observable,g=a(6).EmptyObservable.create,b= a(11).mergeStatic;a(3);var c=a(51),f=a(36).resolveURL,m=a(87).pad;h=a(203);var u=h.parseSidx,n=h.patchPssh,q=a(204),x=function(a){a.withMetadata=!0;return c(a)};e.exports=function(){var a=(0>=arguments.length||void 0===arguments[0]?{}:arguments[0]).contentProtectionParser;a||(a=function(){});var c={loader:function(a){var c=a.segment,d=c.getMedia(),e=c.getRange();a=c.getIndexRange();if(c.isInitSegment()&&!(d||e||a))return g();var h=void 0,h=e?{Range:l(e)}:null,e=void 0;d?-1===d.indexOf("$")?e=d:(e= c.getRepresentation(),e=d.replace(/\$\$/g,"$").replace(/\$RepresentationID\$/g,e.id).replace(/\$Bandwidth(|\%0(\d+)d)\$/g,k(e.bitrate)).replace(/\$Number(|\%0(\d+)d)\$/g,k(c.getNumber())).replace(/\$Time(|\%0(\d+)d)\$/g,k(c.getTime()))):e="";c=f(c.getResolvedURL(),e);h=x({url:c,format:"arraybuffer",headers:h});return a?(a=x({url:c,format:"arraybuffer",headers:{Range:l(a)}}),b(h,a)):h},parser:function(a){var b=a.segment;a=new Uint8Array(a.response.blob);var c=void 0,e=void 0,f=void 0,g=b.getIndexRange(); if(g=u(a,g?g[0]:0))c=g.segments,e=g.timescale;b.isInitSegment()||(0<=b.getTime()&&0<=b.getDuration()?f={ts:b.getTime(),d:b.getDuration()}:g&&1===g.segments.length&&(f={ts:g.segments[0].ts,d:g.segments[0].d}));b.isInitSegment()&&(b=b.getAdaptation(),b.contentProtection&&(a=n(a,b.contentProtection)));return d.of({blob:a,currentSegment:f,nextSegments:c,timescale:e})}};return{directFile:!1,manifest:{loader:function(a){return x({url:a.url,format:"document"})},parser:function(b){b=b.response;return d.of({manifest:q(b.blob, a),url:b.url})}},audio:c,video:c,text:{loader:function(){}}}}},function(e,h,a){function l(a,b){for(var e=a.length,f=0,g=void 0,h=void 0;f+8<e&&(h=c(a,f),g=c(a,f+4),d(0<h,"dash: out of range size"),g!==b);)f+=h;if(f>=e)return-1;d(f+h<=e,"dash: atom out of range");return f}function k(a){var b=a.systemId;a=a.privateData;b=b.replace(/-/g,"");d(32===b.length);b=n(4,m(b),g(a.length),a);return n(g(b.length+8),u("pssh"),b)}var d=a(3);h=a(21);var g=h.itobe4,b=h.be8toi,c=h.be4toi,f=h.be2toi,m=h.hexToBytes, u=h.strToBytes,n=h.concat;e.exports={parseSidx:function(a,d){var e=l(a,1936286840);if(-1==e)return null;var g=c(a,e),e=e+4+4,h=a[e],e=e+8,k=c(a,e),e=e+4,m=void 0;if(0===h)m=c(a,e),e+=4,d+=c(a,e)+g,e+=4;else if(1===h)m=b(a,e),e+=8,d+=b(a,e)+g,e+=8;else return null;g=[];e+=2;h=f(a,e);for(e+=2;0<=--h;){var n=c(a,e),e=e+4,u=n&2147483647;if(1==(n&2147483648)>>>31)throw Error("not implemented");n=c(a,e);e+=4;e+=4;g.push({ts:m,d:n,r:0,range:[d,d+u-1]});m+=n;d+=u}return{segments:g,timescale:k}},patchPssh:function(a, b){if(!b||!b.length)return a;var d=l(a,1836019574);if(-1==d)return a;for(var e=c(a,d),f=[a.subarray(d,d+e)],h=0;h<b.length;h++)f.push(k(b[h]));f=n.apply(null,f);f.set(g(f.length),0);return n(a.subarray(0,d),f,a.subarray(d+e))}}},function(e,h,a){function l(a){var b=a.timeline[a.timeline.length-1];return(b.ts+(b.r+1)*b.d)/a.timescale}function k(a,b){var c=J[a.nodeName];A(c,"parser: no attributes for "+a.nodeName);for(var d=b||{},e=0;e<c.length;e++){var f=c[e],g=f.k,h=f.fn,k=f.n,f=f.def;a.hasAttribute(g)? d[k||g]=h(a.getAttribute(g)):null!=f&&(d[k||g]=f)}return d}function d(a){return a}function g(a){return"true"==a}function b(a){return"true"==a?!0:"false"==a?!1:parseInt(a)}function c(a){return new Date(Date.parse(a))}function f(a){if(!a)return 0;var b=E.exec(a);A(b,"parser: "+a+" is not a valid ISO8601 duration");return 31536E3*parseFloat(b[2]||0)+2592E3*parseFloat(b[4]||0)+86400*parseFloat(b[6]||0)+3600*parseFloat(b[8]||0)+60*parseFloat(b[10]||0)+parseFloat(b[12]||0)}function m(a){var b=L.exec(a); if(!b)return-1;a=parseInt(b[1])||0;b=parseInt(b[2])||0;return 0<b?a/b:a}function u(a){return a}function n(a){return(a=H.exec(a))?[+a[1],+a[2]]:null}function q(a,b,c){for(a=a.firstElementChild;a;)c=b(c,a.nodeName,a),a=a.nextElementSibling;return c}function x(a){var b=q(a,function(a,b,c){if("Initialization"==b){var d=b=void 0;c.hasAttribute("range")&&(b=n(c.getAttribute("range")));c.hasAttribute("sourceURL")&&(d=c.getAttribute("sourceURL"));a.initialization={range:b,media:d}}return a},k(a));"SegmentBase"== a.nodeName&&(b.indexType="base",b.timeline=[]);return b}function v(a){return q(a,function(a,b,c){"SegmentTimeline"==b&&(a.indexType="timeline",a.timeline=p(c));return a},x(a))}function p(a){return q(a,function(a,b,c){b=a.length;c=k(c);null==c.ts&&(b=0<b&&a[b-1],c.ts=b?b.ts+b.d*(b.r+1):0);null==c.r&&(c.r=0);a.push(c);return a},[])}function r(a){a=v(a);a.indexType||(a.indexType="template");return a}function y(a){var b=v(a);b.list=[];b.indexType="list";return q(a,function(a,b,c){"SegmentURL"==b&&a.list.push(k(c)); return a},b)}function w(a){var b=q(a,function(a,b,c){switch(b){case "BaseURL":a.baseURL=c.textContent;break;case "SegmentBase":a.index=x(c);break;case "SegmentList":a.index=y(c);break;case "SegmentTemplate":a.index=r(c)}return a},{});return k(a,b)}function z(a,b){var c=q(a,function(a,c,d){switch(c){case "ContentProtection":c=b(k(d),d);a.contentProtection=c;break;case "ContentComponent":a.contentComponent=k(d);break;case "BaseURL":a.baseURL=d.textContent;break;case "SegmentBase":a.index=x(d);break; case "SegmentList":a.index=y(d);break;case "SegmentTemplate":a.index=r(d);break;case "Representation":c=w(d),null==c.id&&(c.id=a.representations.length),a.representations.push(c)}return a},{representations:[]});return k(a,c)}function D(a,b){var c=k(a,q(a,function(a,c,d){switch(c){case "BaseURL":a.baseURL=d.textContent;break;case "AdaptationSet":c=z(d,b),null==c.id&&(c.id=a.adaptations.length),a.adaptations.push(c)}return a},{adaptations:[]}));c.baseURL&&c.adaptations.forEach(function(a){return G(a, {baseURL:c.baseURL})});return c}function C(a,b){var c=a.documentElement;A.equal(c.nodeName,"MPD","parser: document root should be MPD");var d=q(c,function(a,c,d){switch(c){case "BaseURL":a.baseURL=d.textContent;break;case "Location":a.locations.push(d.textContent);break;case "Period":a.periods.push(D(d,b))}return a},{transportType:"dash",periods:[],locations:[]}),d=k(c,d);if(/dynamic/.test(d.type)){var c=(c=O(d.periods[0].adaptations,function(a){return"video/mp4"==a.mimeType}))&&c.index,e=void 0, e=c.timeline?l(c):Date.now()/1E3-60;d.availabilityStartTime=d.availabilityStartTime.getTime()/1E3;d.presentationLiveGap=Date.now()/1E3-(e+d.availabilityStartTime)}return d}function t(a,b){return C((new DOMParser).parseFromString(a,"application/xml"),b)}function B(a,b){return"string"==typeof a?t(a,b):C(a,b)}var A=a(3),O=a(22),G=a(23),E=/^P(([\d.]*)Y)?(([\d.]*)M)?(([\d.]*)D)?T?(([\d.]*)H)?(([\d.]*)M)?(([\d.]*)S)?/,H=/([0-9]+)-([0-9]+)/,L=/([0-9]+)(\/([0-9]+))?/;h=[{k:"profiles",fn:d},{k:"width",fn:parseInt}, {k:"height",fn:parseInt},{k:"frameRate",fn:m},{k:"audioSamplingRate",fn:d},{k:"mimeType",fn:d},{k:"segmentProfiles",fn:d},{k:"codecs",fn:d},{k:"maximumSAPPeriod",fn:parseFloat},{k:"maxPlayoutRate",fn:parseFloat},{k:"codingDependency",fn:g}];a=[{k:"timescale",fn:parseInt},{k:"presentationTimeOffset",fn:parseFloat,def:0},{k:"indexRange",fn:n},{k:"indexRangeExact",fn:g},{k:"availabilityTimeOffset",fn:parseFloat},{k:"availabilityTimeComplete",fn:g}];var F=a.concat([{k:"duration",fn:parseInt},{k:"startNumber", fn:parseInt}]),J={ContentProtection:[{k:"schemeIdUri",fn:d},{k:"value",fn:d}],SegmentURL:[{k:"media",fn:d},{k:"mediaRange",fn:n},{k:"index",fn:d},{k:"indexRange",fn:n}],S:[{k:"t",fn:parseInt,n:"ts"},{k:"d",fn:parseInt},{k:"r",fn:parseInt}],SegmentTimeline:[],SegmentBase:a,SegmentTemplate:F.concat([{k:"initialization",fn:function(a){return{media:a,range:void 0}}},{k:"index",fn:d},{k:"media",fn:d},{k:"bitstreamSwitching",fn:d}]),SegmentList:F,ContentComponent:[{k:"id",fn:d},{k:"lang",fn:d},{k:"contentType", fn:d},{k:"par",fn:u}],Representation:h.concat([{k:"id",fn:d},{k:"bandwidth",fn:parseInt,n:"bitrate"},{k:"qualityRanking",fn:parseInt}]),AdaptationSet:h.concat([{k:"id",fn:d},{k:"group",fn:parseInt},{k:"lang",fn:d},{k:"contentType",fn:d},{k:"par",fn:u},{k:"minBandwidth",fn:parseInt,n:"minBitrate"},{k:"maxBandwidth",fn:parseInt,n:"maxBitrate"},{k:"minWidth",fn:parseInt},{k:"maxWidth",fn:parseInt},{k:"minHeight",fn:parseInt},{k:"maxHeight",fn:parseInt},{k:"minFrameRate",fn:m},{k:"maxFrameRate",fn:m}, {k:"segmentAlignment",fn:b},{k:"subsegmentAlignment",fn:b},{k:"bitstreamSwitching",fn:g}]),Period:[{k:"id",fn:d},{k:"start",fn:f},{k:"duration",fn:f},{k:"bitstreamSwitching",fn:g}],MPD:[{k:"id",fn:d},{k:"profiles",fn:d},{k:"type",fn:d,def:"static"},{k:"availabilityStartTime",fn:c},{k:"availabilityEndTime",fn:c},{k:"publishTime",fn:c},{k:"mediaPresentationDuration",fn:f,n:"duration"},{k:"minimumUpdatePeriod",fn:f},{k:"minBufferTime",fn:f},{k:"timeShiftBufferDepth",fn:f},{k:"suggestedPresentationDelay", fn:f},{k:"maxSegmentDuration",fn:f},{k:"maxSubsegmentDuration",fn:f}]};B.parseFromString=t;B.parseFromDocument=C;e.exports=B},function(e,h,a){var l=a(1).Observable;e.exports={directFile:!0,manifest:{parser:function(a){a=a.url;return l.of({manifest:{transportType:"directfile",locations:[a],periods:[],isLive:!1,duration:Infinity,adaptations:null},url:a})}}}},function(e,h,a){e.exports={smooth:a(207),dash:a(202),directfile:a(205)}},function(e,h,a){function l(a){return(a=a.match(C))&&a[1]||""}function k(a, b){return b?a.replace(C,"?token="+b):a.replace(C,"")}function d(a){return a.getResolvedURL().replace(/\{bitrate\}/g,a.getRepresentation().bitrate).replace(/\{start time\}/g,a.getTime())}var g=a(1).Observable,b=a(6).EmptyObservable.create,c=a(51),f=a(21).bytesToStr,m=a(4),u=a(209);h=a(208);var n=h.patchSegment,q=h.createVideoInitSegment,x=h.createAudioInitSegment,v=h.getMdat,p=h.getTraf,r=h.parseTfrf,y=h.parseTfxd;h=a(210).parseSami;a=a(211).parseTTML;var w={"application/x-sami":h,"application/smil":h, "application/ttml+xml":a,"application/ttml+xml+mp4":a,"text/vtt":function(a){return a}},z=/\.(isml?)(\?token=\S+)?$/,D=/\.wsx?(\?token=\S+)?/,C=/\?token=(\S+)/,t=function(a){a.withMetadata=!0;return c(a)};e.exports=function(){function a(b,c){var d=void 0,e=void 0;if(c.getAdaptation().isLive){var f=p(b);f?(d=r(f),e=y(f)):m.warn("smooth: could not find traf atom")}else d=null;e||(e={d:c.getDuration(),ts:c.getTime()});return{nextSegments:d,currentSegment:e}}var c=u(0>=arguments.length||void 0===arguments[0]? {}:arguments[0]),e={loader:function(a){a=a.segment;if(a.isInitSegment()){var b=a.getAdaptation();a=a.getRepresentation();var c=void 0,e=b.smoothProtection||{};switch(b.type){case "video":c=q(a.index.timescale,a.width,a.height,72,72,4,a.codecPrivateData,e.keyId,e.keySystems);break;case "audio":c=x(a.index.timescale,a.channels,a.bitsPerSample,a.packetSize,a.samplingRate,a.codecPrivateData,e.keyId,e.keySystems)}return g.of({blob:c,size:c.length,duration:100})}b=void 0;if(c=a.getRange())b=c[0],b=(c=c[1])&& Infinity!==c?"bytes="+ +b+"-"+ +c:"bytes="+ +b+"-",b={Range:b};a=d(a);return t({url:a,format:"arraybuffer",headers:b})},parser:function(b){var c=b.segment;b=b.response;if(c.isInitSegment())return g.of({blob:b.blob,timings:null});b=new Uint8Array(b.blob);var d=a(b,c),c=d.nextSegments,d=d.currentSegment;return g.of({blob:n(b,d.ts),nextSegments:c,currentSegment:d})}};return{directFile:!1,manifest:{resolver:function(a){a=a.url;var b=void 0,c=l(a),b=D.test(a)?t({url:k(a,""),format:"document"}).map(function(a){return a.blob.getElementsByTagName("media")[0].getAttribute("src")}): g.of(a);return b.map(function(a){var b=a.match(z);a=b?a.replace(b[1],b[1]+"/manifest"):a;return{url:k(a,c)}})},loader:function(a){return t({url:a.url,format:"document"})},parser:function(a){a=a.response;return g.of({manifest:c(a.blob),url:a.url})}},audio:e,video:e,text:{loader:function(a){var c=a.segment;if(c.isInitSegment())return b();a=c.getRepresentation().mimeType;c=d(c);return 0<=a.indexOf("mp4")?t({url:c,format:"arraybuffer"}):t({url:c,format:"text"})},parser:function(b){var c=b.response;b= b.segment;var d=b.getAdaptation().lang,e=b.getRepresentation(),h=e.mimeType,e=e.index,k=w[h];if(!k)throw Error("smooth: could not find a text-track parser for the type "+h);var l=c.blob,c=void 0;0<=h.indexOf("mp4")?(l=new Uint8Array(l),c=f(v(l))):c=l;l=a(l,b);h=l.nextSegments;l=l.currentSegment;return g.of({blob:k(c,d,b.getTime()/e.timescale),currentSegment:l,nextSegments:h})}}}}},function(e,h,a){function l(a,b){var c=y(b.length+8),d;C[a]?d=C[a]:(d=n(a),C[a]=d);return u(c,d,b)}function k(a,b,c,d, e){for(var f=a.length,g=0,h=void 0;g<f;){h=r(a,g);if(1970628964===r(a,g+4)&&r(a,g+8)===b&&r(a,g+12)===c&&r(a,g+16)===d&&r(a,g+20)===e)return a.subarray(g+24,g+h);g+=h}}function d(a,b){for(var c=a.length,d=0,e=void 0,g=void 0;d+8<c&&(g=r(a,d),e=r(a,d+4),f(0<g,"dash: out of range size"),e!==b);)d+=g;return d<c?a.subarray(d+8,d+g):null}function g(a,b,c,d){var e=[a,b,c];d.forEach(function(a){a=t.pssh(a.systemId,a.privateData,a.keyIds);e.push(a)});return e}function b(a,b,c,d){var e=a.length,f=b.length; c=c.length;a=a.subarray(c,e);e=new Uint8Array(f+(e-c));e.set(b,0);e.set(a,f);e.set(y(b.length+8),d+16);return e}function c(a,b,c,d,e,f,h){c=t.mult("stbl",[c,l("stts",new Uint8Array(8)),l("stsc",new Uint8Array(8)),l("stsz",new Uint8Array(12)),l("stco",new Uint8Array(8))]);var k=l("url ",new Uint8Array([0,0,0,1])),k=t.dref(k),k=t.mult("dinf",[k]);d=t.mult("minf",[d,k,c]);b=t.hdlr(b);c=t.mdhd(a);b=t.mult("mdia",[c,b,d]);e=t.tkhd(e,f,1);e=t.mult("trak",[e,b]);f=t.trex(1);f=t.mult("mvex",[f]);a=t.mvhd(a, 1);h=t.mult("moov",g(a,f,e,h));a=t.ftyp("isom",["isom","iso2","iso6","avc1","dash"]);return u(a,h)}var f=a(3),m=a(14).isIE;h=a(21);var u=h.concat,n=h.strToBytes,q=h.hexToBytes,x=h.bytesToHex,v=h.be2toi,p=h.itobe2,r=h.be4toi,y=h.itobe4,w=h.be8toi,z=h.itobe8,D=[96E3,88200,64E3,48E3,44100,32E3,24E3,22050,16E3,12E3,11025,8E3,7350],C={},t={mult:function(a,b){return l(a,u.apply(null,b))},avc1encv:function(a,b,c,d,e,f,g,h,k,m){return l(a,u(6,p(b),16,p(c),p(d),p(e),2,p(f),6,[0,1,g.length],n(g),31-g.length, p(h),[255,255],k,"encv"===a?m:[]))},avcc:function(a,b,c){return l("avcC",u([1,a[1],a[2],a[3],252|(2===c?1:4===c?3:0),225],p(a.length),a,[1],p(b.length),b))},dref:function(a){return l("dref",u(7,[1],a))},esds:function(a,b){return l("esds",u(4,[3,25],p(a),[0,4,17,64,21],11,[5,2],q(b),[6,1,2]))},frma:function(a){return l("frma",n(a))},free:function(a){return l("free",new Uint8Array(a-8))},ftyp:function(a,b){return l("ftyp",u.apply(null,[n(a),[0,0,0,1]].concat(b.map(n))))},hdlr:function(a){return l("hdlr", u(8,n("audio"===a?"soun":"vide"),12,n("Media Handler")))},mdhd:function(a){return l("mdhd",u(12,y(a),8))},moof:function(a,b){return t.mult("moof",[a,b])},mp4aenca:function(a,b,c,d,e,f,g,h){return l(a,u(6,p(b),8,p(c),p(d),2,p(e),p(f),2,g,"enca"===a?h:[]))},mvhd:function(a,b){return l("mvhd",u(12,y(a),4,[0,1],2,[1,0],10,[0,1],14,[0,1],14,[64,0,0,0],26,p(b+1)))},pssh:function(a){var b=1>=arguments.length||void 0===arguments[1]?[]:arguments[1],c=2>=arguments.length||void 0===arguments[2]?[]:arguments[2]; a=a.replace(/-/g,"");f(32===a.length,"wrong system id length");var d=void 0,e=void 0,e=c.length;0<e?(d=1,e=u.apply(null,[y(e)].concat(c))):(d=0,e=[]);return l("pssh",u([d,0,0,0],q(a),e,y(b.length),b))},saio:function(a,b,c,d){return l("saio",u(4,[0,0,0,1],y(a.length+b.length+c.length+d.length+8+8+8+8)))},saiz:function(a){if(0===a.length)return l("saiz",new Uint8Array);var b=r(a,0),c=r(a,4),d=new Uint8Array(9+c);d.set(y(c),5);for(var c=9,e=8,f=void 0,g=void 0;e<a.length;)e+=8,2===(b&2)?(g=2,f=v(a,e), e+=2+6*f):g=f=0,d[c]=6*f+8+g,c++;return l("saiz",d)},schm:function(a,b){return l("schm",u(4,n(a),y(b)))},senc:function(a){return l("senc",a)},smhd:function(){return l("smhd",new Uint8Array(8))},stsd:function(a){return l("stsd",u.apply(null,[7,[a.length]].concat(a)))},tkhd:function(a,b,c){return l("tkhd",u(y(7),8,y(c),20,[1,0,0,0],[0,1,0,0],12,[0,1,0,0],12,[64,0,0,0],p(a),2,p(b),2))},trex:function(a){return l("trex",u(4,y(a),[0,0,0,1],12))},tfdt:function(a){return l("tfdt",u([1,0,0,0],z(a)))},tenc:function(a, b,c){return l("tenc",u(6,[a,b],q(c)))},traf:function(a,b,c,d,e){var f=[a,b,c];d&&f.push(t.senc(d),t.saiz(d),t.saio(e,a,b,c));return t.mult("traf",f)},vmhd:function(){var a=new Uint8Array(12);a[3]=1;return l("vmhd",a)}},B={traf:function(a){return(a=d(a,1836019558))?d(a,1953653094):null},senc:function(a){return k(a,2721664850,1520127764,2722393154,2086964724)},tfxd:function(a){return k(a,1830656773,1121273062,2162299933,2952222642)},tfrf:function(a){return k(a,3565190898,3392751253,2387879627,2655430559)}, mdat:function(a){return d(a,1835295092)}};e.exports={getMdat:B.mdat,getTraf:B.traf,parseTfrf:function(a){a=B.tfrf(a);if(!a)return[];for(var b=[],c=a[0],d=a[4],e=0;e<d;e++){var f=void 0,g=void 0;1==c?(g=w(a,16*e+5),f=w(a,16*e+13)):(g=r(a,8*e+5),f=r(a,8*e+9));b.push({ts:g,d:f})}return b},parseTfxd:function(a){if(a=B.tfxd(a))return{d:w(a,12),ts:w(a,4)}},createVideoInitSegment:function(a,b,d,e,f,g,h,k,l){l||(l=[]);var m=h.split("00000001");h=m[2];m=q(m[1]);h=q(h);g=t.avcc(m,h,g);h=void 0;l.length?(k= t.tenc(1,8,k),k=t.mult("schi",[k]),h=t.schm("cenc",65536),m=t.frma("avc1"),k=t.mult("sinf",[m,h,k]),e=t.avc1encv("encv",1,b,d,e,f,"AVC Coding",24,g,k)):e=t.avc1encv("avc1",1,b,d,e,f,"AVC Coding",24,g);h=t.stsd([e]);return c(a,"video",h,t.vmhd(),b,d,l)},createAudioInitSegment:function(a,b,d,e,f,g,h,k){k||(k=[]);if(!g){g=D.indexOf(f);var l=void 0,l=((32|g&31)<<4|b&31)<<3;g=x(p(l))}g=t.esds(1,g);l=void 0;if(k.length){h=t.tenc(1,8,h);h=t.mult("schi",[h]);var l=t.schm("cenc",65536),m=t.frma("mp4a");h= t.mult("sinf",[m,l,h]);b=t.mp4aenca("enca",1,b,d,e,f,g,h)}else b=t.mp4aenca("mp4a",1,b,d,e,f,g);l=t.stsd([b]);return c(a,"audio",l,t.smhd(),0,0,k)},patchSegment:function(a,c){var d=a.subarray(0,r(a,0)),e=t.tfdt(c),f=e.length,g=r(d,8),h=r(d,8+g),k=r(d,8+g+8),l=r(d,8+g+8+k),n=d.subarray(8,8+g),q=d.subarray(8+g+8,8+g+8+h-8),h=q.subarray(0,k),l=q.subarray(k,k+l);h.set([0,0,0,1],12);q=B.senc(q);e=t.traf(h,e,l,q,n);n=t.moof(n,e);f=8+g+8+k+f;return m?b(a,n,d,f):8<=d.length-n.length?(d=d.length-n.length, a.set(n,0),a.set(t.free(d),n.length),a.set(y(n.length+8+d),f+16),a):b(a,n,d,f)}}},function(e,h,a){function l(a){return"boolean"==typeof a?a:"string"==typeof a?"TRUE"===a.toUpperCase():!1}function k(a){var b=a.timeline[a.timeline.length-1];return(b.ts+(b.r+1)*b.d)/a.timescale}function d(a){return[{systemId:"edef8ba9-79d6-4ace-a3c8-27dcd51d21ed",privateData:c.concat([8,1,18,16],a)}]}var g=a(3),b=a(22),c=a(21),f={audio:"audio/mp4",video:"video/mp4",text:"application/ttml+xml"},m={audio:"mp4a.40.2",video:"avc1.4D401E"}; h={AACL:"audio/mp4",AVC1:"video/mp4",H264:"video/mp4",TTML:"application/ttml+xml+mp4"};var u={audio:[["Bitrate","bitrate",parseInt],["AudioTag","audiotag",parseInt],["FourCC","mimeType",h],["Channels","channels",parseInt],["SamplingRate","samplingRate",parseInt],["BitsPerSample","bitsPerSample",parseInt],["PacketSize","packetSize",parseInt],["CodecPrivateData","codecPrivateData",String]],video:[["Bitrate","bitrate",parseInt],["FourCC","mimeType",h],["CodecPrivateData","codecs",function(a){return(a= (/00000001\d7([0-9a-fA-F]{6})/.exec(a)||[])[1])?"avc1."+a:""}],["MaxWidth","width",parseInt],["MaxHeight","height",parseInt],["CodecPrivateData","codecPrivateData",String]],text:[["Bitrate","bitrate",parseInt],["FourCC","mimeType",h]]};e.exports=function(){function a(b,c,d){for(b=b.firstElementChild;b;)d=c(d,b.nodeName,b),b=b.nextElementSibling;return d}function e(b,c){b.hasAttribute("Timescale")&&(c=+b.getAttribute("Timescale"));var d=b.getAttribute("Type"),h=b.getAttribute("Subtype"),k=u[d];g(k, "parser: unrecognized QualityLevel type "+d);var l=0,q=a(b,function(a,b,c){switch(b){case "QualityLevel":b={};for(var e=0;e<k.length;e++){var f=k[e],g=f[0],h=f[2];b[f[1]]="function"==typeof h?h(c.getAttribute(g)):h[c.getAttribute(g)]}"audio"==d&&(c=c.getAttribute("FourCC")||"",e=b.codecPrivateData,f=void 0,f="AACH"==c?5:e?(parseInt(e.substr(0,2),16)&248)>>3:2,b.codecs=f?"mp4a.40."+f:"");if("video"!=d||b.bitrate>z)b.id=l++,a.representations.push(b);break;case "c":b=a.index;var e=a.index.timeline,f= e.length,g=0<f?e[f-1]:{d:0,ts:0,r:0},h=+c.getAttribute("d"),m=c.getAttribute("t");(c=+c.getAttribute("r"))&&c--;0<f&&!g.d&&(g.d=m-g.ts,e[f-1]=g);0<f&&h==g.d&&null==m?g.r+=(c||0)+1:e.push({d:h,ts:null==m?g.ts+g.d*(g.r+1):+m,r:c});b.timeline=e}return a},{representations:[],index:{timeline:[],indexType:"timeline",timescale:c,initialization:{}}}),p=q.representations,q=q.index;g(p.length,"parser: adaptation should have at least one representation");p.forEach(function(a){return a.codecs=a.codecs||m[d]}); p.forEach(function(a){return a.mimeType=a.mimeType||f[d]});return"ADVT"==h?null:{type:d,index:q,representations:p,name:b.getAttribute("Name"),lang:b.getAttribute("Language"),baseURL:b.getAttribute("Url")}}function h(a){return v((new DOMParser).parseFromString(a,"application/xml"))}function v(d){d=d.documentElement;g.equal(d.nodeName,"SmoothStreamingMedia","parser: document root should be SmoothStreamingMedia");g(/^[2]-[0-2]$/.test(d.getAttribute("MajorVersion")+"-"+d.getAttribute("MinorVersion")), "Version should be 2.0, 2.1 or 2.2");var f=+d.getAttribute("Timescale")||1E7,h=0,m=a(d,function(a,b,d){switch(b){case "Protection":d=d.firstElementChild;g.equal(d.nodeName,"ProtectionHeader","parser: Protection should have ProtectionHeader child");b=c.strToBytes(atob(d.textContent));var k;k=c.le2toi(b,8);k=c.bytesToUTF16Str(b.subarray(10,10+k));k=(new DOMParser).parseFromString(k,"application/xml").querySelector("KID").textContent;k=c.guidToUuid(atob(k)).toLowerCase();var l=c.hexToBytes(k);d=d.getAttribute("SystemID").toLowerCase().replace(/\{|\}/g, "");b={keyId:k,keySystems:[{systemId:d,privateData:b}].concat(D(l))};a.protection=b;break;case "StreamIndex":if(b=e(d,f))b.id=h++,a.adaptations.push(b)}return a},{protection:null,adaptations:[]}),p=m.protection,m=m.adaptations;m.forEach(function(a){return a.smoothProtection=p});var r=void 0,x=void 0,u=void 0,v=void 0,z=l(d.getAttribute("IsLive"));if(z)var r=y,u=+d.getAttribute("DVRWindowLength")/f,v=w,x=b(m,function(a){return"video"==a.type}),J=b(m,function(a){return"audio"==a.type}),x=Math.min(k(x.index), k(J.index)),x=Date.now()/1E3-(x+v);return{transportType:"smoothstreaming",profiles:"",type:z?"dynamic":"static",suggestedPresentationDelay:r,timeShiftBufferDepth:u,presentationLiveGap:x,availabilityStartTime:v,periods:[{duration:(+d.getAttribute("Duration")||Infinity)/f,adaptations:m,laFragCount:+d.getAttribute("LookAheadFragmentCount")}]}}function p(a){return"string"==typeof a?h(a):v(a)}var r=0>=arguments.length||void 0===arguments[0]?{}:arguments[0],y=r.suggestedPresentationDelay||20,w=r.referenceDateTime|| Date.UTC(1970,0,1,0,0,0,0)/1E3,z=r.minRepresentationBitrate||19E4,D=r.keySystems||d;p.parseFromString=h;p.parseFromDocument=v;return p}},function(e,h,a){function l(a){return a.replace(g,"\n").replace(d,function(a,b){return String.fromCharCode(b)})}var k=a(3),d=/&#([0-9]+);/g,g=/<br>/gi,b=/<style[^>]*>([\s\S]*?)<\/style[^>]*>/i,c=/\s*<p class=([^>]+)>(.*)/i,f=/<sync[^>]+?start="?([0-9]*)"?[^0-9]/i;e.exports={parseSami:function(a,d){for(var e=/<sync[ >]/ig,g=/<sync[ >]|<\/body>/ig,h=[],v=a.match(b)[1], p=void 0,r=g.exec(a),p=/\.(\S+)\s*{([^}]*)}/gi,r={},y=void 0;y=p.exec(v);){var w=y[1],y=y[2].match(/\s*lang:\s*(\S+);/i)[1];w&&y&&(r[y]=w)}v=r[d];for(k(v,"sami: could not find lang "+d+" in CSS");;){p=e.exec(a);r=g.exec(a);if(!p&&!r)break;if(!p||!r||p.index>=r.index)throw Error("parse error");r=a.slice(p.index,r.index);p=r.match(f);if(!p)throw Error("parse error: sync time attribute");w=+p[1];if(isNaN(w))throw Error("parse error: sync time attribute NaN");for(var p=h,r=r.split("\n"),w=w/1E3,y=r.length, z=void 0;0<=--y;)if(z=r[y].match(c)){var D=z[2];v===z[1]&&("&nbsp;"===D?p[p.length-1].end=w:p.push({text:l(D),start:w}))}}return h}}},function(e,h){function a(b,e){var f=0;b=b.firstChild;for(var g=[],h=void 0;b;){if(1===b.nodeType)switch(b.tagName.toUpperCase()){case "P":var h=b,v=e,p=l(h.getAttribute("begin"),v),r=l(h.getAttribute("end"),v),y=l(h.getAttribute("dur"),0);if("number"==!("undefined"===typeof p||k(p))&&"number"==!("undefined"===typeof r||k(r))&&"number"==!("undefined"===typeof y||k(y)))throw Error("ttml: unsupported timestamp format"); 0<y?(null==p&&(p=f||v),null==r&&(r=p+y)):null==r&&(r=l(h.getAttribute("duration"),0),r=0<=r?r+p:Number.MAX_VALUE);h={id:h.getAttribute("xml:id")||h.getAttribute("id"),text:decodeURIComponent(c(h.innerHTML.replace(d,"\n"))),start:p,end:r};f=h.end;g.push(h);break;case "DIV":h=l(b.getAttribute("begin"),0),null==h&&(h=e),g.push.apply(g,a(b,h))}b=b.nextSibling}return g}function l(a,c){if(!a)return null;var d=void 0;if(d=a.match(g)){var e=d[3],h=d[4],k=d[6];return 3600*parseInt(d[2]||0,10)+60*parseInt(e, 10)+parseInt(h,10)+parseFloat("0."+k)}return(d=a.match(b))?(e=d[4],parseFloat(d[1])*f[e]+c):null}var k="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol?"symbol":typeof a},d=/<br[^>]+>/gm,g=/^(([0-9]+):)?([0-9]+):([0-9]+)(\.([0-9]+))?$/,b=/(([0-9]+)(\.[0-9]+)?)(ms|h|m|s)/,c=window.escape,f={h:3600,m:60,s:1,ms:.001};e.exports={parseTTML:function(b,c,d){c=void 0;c="string"==typeof b?(new DOMParser).parseFromString(b, "text/xml"):b;if(!(c instanceof window.Document||c instanceof window.HTMLElement))throw Error("ttml: needs a Document to parse");b=c.querySelector("tt");if(!b)throw Error("ttml: could not find <tt> tag");b=a(b.querySelector("body"),0);for(c=0;c<b.length;c++){var e=b[c];e.start+=d;e.end+=d}return b}}},function(e,h){var a=function(){function a(){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.hash={}}a.prototype.add=function(a){this.hash[a]=!0};a.prototype.remove= function(a){delete this.hash[a]};a.prototype.test=function(a){return!0===this.hash[a]};return a}();e.exports={SimpleSet:a}},function(e,h,a){function l(a){return null==a?"":String(a).replace(u,function(a){return n[a]})}function k(a){var b=a.getAverageBitrates(),d=void 0,e=void 0;b.video.take(1).subscribe(function(a){return e=a|0});b.audio.take(1).subscribe(function(a){return d=a|0});return{manifest:a.man,version:a.version,timeFragment:a.frag,currentTime:a.getCurrentTime(),state:a.getPlayerState(), buffer:c(a.video.buffered),volume:a.getVolume(),video:{adaptation:a.adas.video,representation:a.reps.video,maxBitrate:a.getVideoMaxBitrate(),bufferSize:a.getVideoBufferSize(),avrBitrate:e},audio:{adaptation:a.adas.audio,representation:a.reps.audio,maxBitrate:a.getAudioMaxBitrate(),bufferSize:a.getAudioBufferSize(),avrBitrate:d}}}function d(a,b){var c=b.parentNode.querySelector("#cp--debug-infos-content");if(c){var d=void 0;try{d=k(a)}catch(e){return}var f=d,g=f.video,h=f.audio,f=f.manifest,d="<b>Player v"+ d.version+"</b> ("+d.state+")<br>";f&&g&&h&&(d+=["Container: "+l(f.transportType),"Live: "+l(""+f.isLive),"Downloading bitrate (Kbit/s):\n "+(g.representation.bitrate/1E3).toFixed(3)+"/"+(h.representation.bitrate/1E3).toFixed(3),"Estimated bandwidth (Kbit/s):\n "+(g.avrBitrate/1E3).toFixed(3)+"/"+(h.avrBitrate/1E3).toFixed(3),"Location: "+f.locations[0]].join("<br>"));c.innerHTML=d}}function g(a,c){var e="<style>\n#cp--debug-infos {\n position: absolute;\n top: "+l(c.offsetTop+ 10)+"px;\n left: "+l(c.offsetLeft+10)+'px;\n width: 500px;\n height: 300px;\n background-color: rgba(10, 10, 10, 0.83);\n overflow: hidden;\n color: white;\n text-align: left;\n padding: 2em;\n box-sizing: border-box;\n}\n#cp--debug-hide-infos {\n float: right;\n cursor: pointer;\n}\n</style>\n<div id="cp--debug-infos">\n <a id="cp--debug-hide-infos">[x]</a>\n <p id="cp--debug-infos-content"></p>\n</div>',g=c.parentNode,h=g.querySelector("#cp--debug-infos-container");h||(h=document.createElement("div"), h.setAttribute("id","cp--debug-infos-container"),g.appendChild(h));h.innerHTML=e;m||(m=g.querySelector("#cp--debug-hide-infos"),m.addEventListener("click",function(){return b(c)}));f&&clearInterval(f);f=setInterval(function(){return d(a,c)},1E3);d(a,c)}function b(a){(a=a.parentNode.querySelector("#cp--debug-infos-container"))&&a.parentNode.removeChild(a);f&&(clearInterval(f),f=null);m&&(m.removeEventListener("click",b),m=null)}var c=a(31).bufferedToArray,f=void 0,m=void 0,u=/[&<>"']/g,n={"&":"&amp;", "<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};e.exports={getDebug:k,showDebug:g,hideDebug:b,toggleDebug:function(a,c){c.parentNode.querySelector("#cp--debug-infos-container")?b(c):g(a,c)}}},function(e,h){var a=function(){function a(e){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.size=0;this.limit=e;this._keymap={};this.tail=this.head=null}a.prototype.set=function(a,d){var e={key:a,value:d,newer:null,older:null};this._keymap[a]=e;this.tail?(this.tail.newer= e,e.older=this.tail):this.head=e;this.tail=e;if(this.size===this.limit)return this.shift();this.size++;return null};a.prototype.shift=function(){var a=this.head;a&&(this.head.newer?(this.head=this.head.newer,this.head.older=null):this.head=null,a.newer=a.older=null,delete this._keymap[a.key]);return a};a.prototype.get=function(a){a=this._keymap[a];if(null!=a){if(a===this.tail)return a.value;a.newer&&(a===this.head&&(this.head=a.newer),a.newer.older=a.older);a.older&&(a.older.newer=a.newer);a.newer= null;if(a.older=this.tail)this.tail.newer=a;this.tail=a;return a.value}};return a}();e.exports=a},function(e,h,a){var l=a(49).getBackedoffDelay,k=a(41).TimerObservable.create,d=a(50);e.exports={retryWithBackoff:function(a,b){var c=b.retryDelay,e=b.totalRetry,h=b.shouldRetry,u=b.resetDelay,n=0,q=void 0;0<u&&(q=d(function(){return n=0},u));return a["catch"](function(a,b){if(h&&!h(a,n)||n++>=e)throw a;var d=l(c,n);return k(d).flatMap(function(){q&&q();return b})})}}}])});
joeyparrish/cdnjs
ajax/libs/rx-player/2.0.0-alpha3/rx-player.min.js
JavaScript
mit
184,678
// HumanizeDuration.js - https://git.io/j0HgmQ ;(function () { // This has to be defined separately because of a bug: we want to alias // `gr` and `el` for backwards-compatiblity. In a breaking change, we can // remove `gr` entirely. // See https://github.com/EvanHahn/HumanizeDuration.js/issues/143 for more. var greek = { y: function (c) { return c === 1 ? 'χρόνος' : 'χρόνια' }, mo: function (c) { return c === 1 ? 'μήνας' : 'μήνες' }, w: function (c) { return c === 1 ? 'εβδομάδα' : 'εβδομάδες' }, d: function (c) { return c === 1 ? 'μέρα' : 'μέρες' }, h: function (c) { return c === 1 ? 'ώρα' : 'ώρες' }, m: function (c) { return c === 1 ? 'λεπτό' : 'λεπτά' }, s: function (c) { return c === 1 ? 'δευτερόλεπτο' : 'δευτερόλεπτα' }, ms: function (c) { return c === 1 ? 'χιλιοστό του δευτερολέπτου' : 'χιλιοστά του δευτερολέπτου' }, decimal: ',' } var languages = { ar: { y: function (c) { return c === 1 ? 'سنة' : 'سنوات' }, mo: function (c) { return c === 1 ? 'شهر' : 'أشهر' }, w: function (c) { return c === 1 ? 'أسبوع' : 'أسابيع' }, d: function (c) { return c === 1 ? 'يوم' : 'أيام' }, h: function (c) { return c === 1 ? 'ساعة' : 'ساعات' }, m: function (c) { return ['دقيقة', 'دقائق'][getArabicForm(c)] }, s: function (c) { return c === 1 ? 'ثانية' : 'ثواني' }, ms: function (c) { return c === 1 ? 'جزء من الثانية' : 'أجزاء من الثانية' }, decimal: ',' }, bg: { y: function (c) { return ['години', 'година', 'години'][getSlavicForm(c)] }, mo: function (c) { return ['месеца', 'месец', 'месеца'][getSlavicForm(c)] }, w: function (c) { return ['седмици', 'седмица', 'седмици'][getSlavicForm(c)] }, d: function (c) { return ['дни', 'ден', 'дни'][getSlavicForm(c)] }, h: function (c) { return ['часа', 'час', 'часа'][getSlavicForm(c)] }, m: function (c) { return ['минути', 'минута', 'минути'][getSlavicForm(c)] }, s: function (c) { return ['секунди', 'секунда', 'секунди'][getSlavicForm(c)] }, ms: function (c) { return ['милисекунди', 'милисекунда', 'милисекунди'][getSlavicForm(c)] }, decimal: ',' }, ca: { y: function (c) { return 'any' + (c === 1 ? '' : 's') }, mo: function (c) { return 'mes' + (c === 1 ? '' : 'os') }, w: function (c) { return 'setman' + (c === 1 ? 'a' : 'es') }, d: function (c) { return 'di' + (c === 1 ? 'a' : 'es') }, h: function (c) { return 'hor' + (c === 1 ? 'a' : 'es') }, m: function (c) { return 'minut' + (c === 1 ? '' : 's') }, s: function (c) { return 'segon' + (c === 1 ? '' : 's') }, ms: function (c) { return 'milisegon' + (c === 1 ? '' : 's') }, decimal: ',' }, cs: { y: function (c) { return ['rok', 'roku', 'roky', 'let'][getCzechOrSlovakForm(c)] }, mo: function (c) { return ['měsíc', 'měsíce', 'měsíce', 'měsíců'][getCzechOrSlovakForm(c)] }, w: function (c) { return ['týden', 'týdne', 'týdny', 'týdnů'][getCzechOrSlovakForm(c)] }, d: function (c) { return ['den', 'dne', 'dny', 'dní'][getCzechOrSlovakForm(c)] }, h: function (c) { return ['hodina', 'hodiny', 'hodiny', 'hodin'][getCzechOrSlovakForm(c)] }, m: function (c) { return ['minuta', 'minuty', 'minuty', 'minut'][getCzechOrSlovakForm(c)] }, s: function (c) { return ['sekunda', 'sekundy', 'sekundy', 'sekund'][getCzechOrSlovakForm(c)] }, ms: function (c) { return ['milisekunda', 'milisekundy', 'milisekundy', 'milisekund'][getCzechOrSlovakForm(c)] }, decimal: ',' }, da: { y: 'år', mo: function (c) { return 'måned' + (c === 1 ? '' : 'er') }, w: function (c) { return 'uge' + (c === 1 ? '' : 'r') }, d: function (c) { return 'dag' + (c === 1 ? '' : 'e') }, h: function (c) { return 'time' + (c === 1 ? '' : 'r') }, m: function (c) { return 'minut' + (c === 1 ? '' : 'ter') }, s: function (c) { return 'sekund' + (c === 1 ? '' : 'er') }, ms: function (c) { return 'millisekund' + (c === 1 ? '' : 'er') }, decimal: ',' }, de: { y: function (c) { return 'Jahr' + (c === 1 ? '' : 'e') }, mo: function (c) { return 'Monat' + (c === 1 ? '' : 'e') }, w: function (c) { return 'Woche' + (c === 1 ? '' : 'n') }, d: function (c) { return 'Tag' + (c === 1 ? '' : 'e') }, h: function (c) { return 'Stunde' + (c === 1 ? '' : 'n') }, m: function (c) { return 'Minute' + (c === 1 ? '' : 'n') }, s: function (c) { return 'Sekunde' + (c === 1 ? '' : 'n') }, ms: function (c) { return 'Millisekunde' + (c === 1 ? '' : 'n') }, decimal: ',' }, el: greek, en: { y: function (c) { return 'year' + (c === 1 ? '' : 's') }, mo: function (c) { return 'month' + (c === 1 ? '' : 's') }, w: function (c) { return 'week' + (c === 1 ? '' : 's') }, d: function (c) { return 'day' + (c === 1 ? '' : 's') }, h: function (c) { return 'hour' + (c === 1 ? '' : 's') }, m: function (c) { return 'minute' + (c === 1 ? '' : 's') }, s: function (c) { return 'second' + (c === 1 ? '' : 's') }, ms: function (c) { return 'millisecond' + (c === 1 ? '' : 's') }, decimal: '.' }, es: { y: function (c) { return 'año' + (c === 1 ? '' : 's') }, mo: function (c) { return 'mes' + (c === 1 ? '' : 'es') }, w: function (c) { return 'semana' + (c === 1 ? '' : 's') }, d: function (c) { return 'día' + (c === 1 ? '' : 's') }, h: function (c) { return 'hora' + (c === 1 ? '' : 's') }, m: function (c) { return 'minuto' + (c === 1 ? '' : 's') }, s: function (c) { return 'segundo' + (c === 1 ? '' : 's') }, ms: function (c) { return 'milisegundo' + (c === 1 ? '' : 's') }, decimal: ',' }, et: { y: function (c) { return 'aasta' + (c === 1 ? '' : 't') }, mo: function (c) { return 'kuu' + (c === 1 ? '' : 'd') }, w: function (c) { return 'nädal' + (c === 1 ? '' : 'at') }, d: function (c) { return 'päev' + (c === 1 ? '' : 'a') }, h: function (c) { return 'tund' + (c === 1 ? '' : 'i') }, m: function (c) { return 'minut' + (c === 1 ? '' : 'it') }, s: function (c) { return 'sekund' + (c === 1 ? '' : 'it') }, ms: function (c) { return 'millisekund' + (c === 1 ? '' : 'it') }, decimal: ',' }, fa: { y: 'سال', mo: 'ماه', w: 'هفته', d: 'روز', h: 'ساعت', m: 'دقیقه', s: 'ثانیه', ms: 'میلی ثانیه', decimal: '.' }, fi: { y: function (c) { return c === 1 ? 'vuosi' : 'vuotta' }, mo: function (c) { return c === 1 ? 'kuukausi' : 'kuukautta' }, w: function (c) { return 'viikko' + (c === 1 ? '' : 'a') }, d: function (c) { return 'päivä' + (c === 1 ? '' : 'ä') }, h: function (c) { return 'tunti' + (c === 1 ? '' : 'a') }, m: function (c) { return 'minuutti' + (c === 1 ? '' : 'a') }, s: function (c) { return 'sekunti' + (c === 1 ? '' : 'a') }, ms: function (c) { return 'millisekunti' + (c === 1 ? '' : 'a') }, decimal: ',' }, fr: { y: function (c) { return 'an' + (c >= 2 ? 's' : '') }, mo: 'mois', w: function (c) { return 'semaine' + (c >= 2 ? 's' : '') }, d: function (c) { return 'jour' + (c >= 2 ? 's' : '') }, h: function (c) { return 'heure' + (c >= 2 ? 's' : '') }, m: function (c) { return 'minute' + (c >= 2 ? 's' : '') }, s: function (c) { return 'seconde' + (c >= 2 ? 's' : '') }, ms: function (c) { return 'milliseconde' + (c >= 2 ? 's' : '') }, decimal: ',' }, gr: greek, hr: { y: function (c) { if (c % 10 === 2 || c % 10 === 3 || c % 10 === 4) { return 'godine' } return 'godina' }, mo: function (c) { if (c === 1) { return 'mjesec' } else if (c === 2 || c === 3 || c === 4) { return 'mjeseca' } return 'mjeseci' }, w: function (c) { if (c % 10 === 1 && c !== 11) { return 'tjedan' } return 'tjedna' }, d: function (c) { return c === 1 ? 'dan' : 'dana' }, h: function (c) { if (c === 1) { return 'sat' } else if (c === 2 || c === 3 || c === 4) { return 'sata' } return 'sati' }, m: function (c) { var mod10 = c % 10 if ((mod10 === 2 || mod10 === 3 || mod10 === 4) && (c < 10 || c > 14)) { return 'minute' } return 'minuta' }, s: function (c) { if ((c === 10 || c === 11 || c === 12 || c === 13 || c === 14 || c === 16 || c === 17 || c === 18 || c === 19) || (c % 10 === 5)) { return 'sekundi' } else if (c % 10 === 1) { return 'sekunda' } else if (c % 10 === 2 || c % 10 === 3 || c % 10 === 4) { return 'sekunde' } return 'sekundi' }, ms: function (c) { if (c === 1) { return 'milisekunda' } else if (c % 10 === 2 || c % 10 === 3 || c % 10 === 4) { return 'milisekunde' } return 'milisekundi' }, decimal: ',' }, hu: { y: 'év', mo: 'hónap', w: 'hét', d: 'nap', h: 'óra', m: 'perc', s: 'másodperc', ms: 'ezredmásodperc', decimal: ',' }, id: { y: 'tahun', mo: 'bulan', w: 'minggu', d: 'hari', h: 'jam', m: 'menit', s: 'detik', ms: 'milidetik', decimal: '.' }, is: { y: 'ár', mo: function (c) { return 'mánuð' + (c === 1 ? 'ur' : 'ir') }, w: function (c) { return 'vik' + (c === 1 ? 'a' : 'ur') }, d: function (c) { return 'dag' + (c === 1 ? 'ur' : 'ar') }, h: function (c) { return 'klukkutím' + (c === 1 ? 'i' : 'ar') }, m: function (c) { return 'mínút' + (c === 1 ? 'a' : 'ur') }, s: function (c) { return 'sekúnd' + (c === 1 ? 'a' : 'ur') }, ms: function (c) { return 'millisekúnd' + (c === 1 ? 'a' : 'ur') }, decimal: '.' }, it: { y: function (c) { return 'ann' + (c === 1 ? 'o' : 'i') }, mo: function (c) { return 'mes' + (c === 1 ? 'e' : 'i') }, w: function (c) { return 'settiman' + (c === 1 ? 'a' : 'e') }, d: function (c) { return 'giorn' + (c === 1 ? 'o' : 'i') }, h: function (c) { return 'or' + (c === 1 ? 'a' : 'e') }, m: function (c) { return 'minut' + (c === 1 ? 'o' : 'i') }, s: function (c) { return 'second' + (c === 1 ? 'o' : 'i') }, ms: function (c) { return 'millisecond' + (c === 1 ? 'o' : 'i') }, decimal: ',' }, ja: { y: '年', mo: '月', w: '週', d: '日', h: '時間', m: '分', s: '秒', ms: 'ミリ秒', decimal: '.' }, ko: { y: '년', mo: '개월', w: '주일', d: '일', h: '시간', m: '분', s: '초', ms: '밀리 초', decimal: '.' }, lo: { y: 'ປີ', mo: 'ເດືອນ', w: 'ອາທິດ', d: 'ມື້', h: 'ຊົ່ວໂມງ', m: 'ນາທີ', s: 'ວິນາທີ', ms: 'ມິນລິວິນາທີ', decimal: ',' }, lt: { y: function (c) { return ((c % 10 === 0) || (c % 100 >= 10 && c % 100 <= 20)) ? 'metų' : 'metai' }, mo: function (c) { return ['mėnuo', 'mėnesiai', 'mėnesių'][getLithuanianForm(c)] }, w: function (c) { return ['savaitė', 'savaitės', 'savaičių'][getLithuanianForm(c)] }, d: function (c) { return ['diena', 'dienos', 'dienų'][getLithuanianForm(c)] }, h: function (c) { return ['valanda', 'valandos', 'valandų'][getLithuanianForm(c)] }, m: function (c) { return ['minutė', 'minutės', 'minučių'][getLithuanianForm(c)] }, s: function (c) { return ['sekundė', 'sekundės', 'sekundžių'][getLithuanianForm(c)] }, ms: function (c) { return ['milisekundė', 'milisekundės', 'milisekundžių'][getLithuanianForm(c)] }, decimal: ',' }, lv: { y: function (c) { return ['gads', 'gadi'][getLatvianForm(c)] }, mo: function (c) { return ['mēnesis', 'mēneši'][getLatvianForm(c)] }, w: function (c) { return ['nedēļa', 'nedēļas'][getLatvianForm(c)] }, d: function (c) { return ['diena', 'dienas'][getLatvianForm(c)] }, h: function (c) { return ['stunda', 'stundas'][getLatvianForm(c)] }, m: function (c) { return ['minūte', 'minūtes'][getLatvianForm(c)] }, s: function (c) { return ['sekunde', 'sekundes'][getLatvianForm(c)] }, ms: function (c) { return ['milisekunde', 'milisekundes'][getLatvianForm(c)] }, decimal: ',' }, ms: { y: 'tahun', mo: 'bulan', w: 'minggu', d: 'hari', h: 'jam', m: 'minit', s: 'saat', ms: 'milisaat', decimal: '.' }, nl: { y: 'jaar', mo: function (c) { return c === 1 ? 'maand' : 'maanden' }, w: function (c) { return c === 1 ? 'week' : 'weken' }, d: function (c) { return c === 1 ? 'dag' : 'dagen' }, h: 'uur', m: function (c) { return c === 1 ? 'minuut' : 'minuten' }, s: function (c) { return c === 1 ? 'seconde' : 'seconden' }, ms: function (c) { return c === 1 ? 'milliseconde' : 'milliseconden' }, decimal: ',' }, no: { y: 'år', mo: function (c) { return 'måned' + (c === 1 ? '' : 'er') }, w: function (c) { return 'uke' + (c === 1 ? '' : 'r') }, d: function (c) { return 'dag' + (c === 1 ? '' : 'er') }, h: function (c) { return 'time' + (c === 1 ? '' : 'r') }, m: function (c) { return 'minutt' + (c === 1 ? '' : 'er') }, s: function (c) { return 'sekund' + (c === 1 ? '' : 'er') }, ms: function (c) { return 'millisekund' + (c === 1 ? '' : 'er') }, decimal: ',' }, pl: { y: function (c) { return ['rok', 'roku', 'lata', 'lat'][getPolishForm(c)] }, mo: function (c) { return ['miesiąc', 'miesiąca', 'miesiące', 'miesięcy'][getPolishForm(c)] }, w: function (c) { return ['tydzień', 'tygodnia', 'tygodnie', 'tygodni'][getPolishForm(c)] }, d: function (c) { return ['dzień', 'dnia', 'dni', 'dni'][getPolishForm(c)] }, h: function (c) { return ['godzina', 'godziny', 'godziny', 'godzin'][getPolishForm(c)] }, m: function (c) { return ['minuta', 'minuty', 'minuty', 'minut'][getPolishForm(c)] }, s: function (c) { return ['sekunda', 'sekundy', 'sekundy', 'sekund'][getPolishForm(c)] }, ms: function (c) { return ['milisekunda', 'milisekundy', 'milisekundy', 'milisekund'][getPolishForm(c)] }, decimal: ',' }, pt: { y: function (c) { return 'ano' + (c === 1 ? '' : 's') }, mo: function (c) { return c === 1 ? 'mês' : 'meses' }, w: function (c) { return 'semana' + (c === 1 ? '' : 's') }, d: function (c) { return 'dia' + (c === 1 ? '' : 's') }, h: function (c) { return 'hora' + (c === 1 ? '' : 's') }, m: function (c) { return 'minuto' + (c === 1 ? '' : 's') }, s: function (c) { return 'segundo' + (c === 1 ? '' : 's') }, ms: function (c) { return 'milissegundo' + (c === 1 ? '' : 's') }, decimal: ',' }, ro: { y: function (c) { return c === 1 ? 'an' : 'ani' }, mo: function (c) { return c === 1 ? 'lună' : 'luni' }, w: function (c) { return c === 1 ? 'săptămână' : 'săptămâni' }, d: function (c) { return c === 1 ? 'zi' : 'zile' }, h: function (c) { return c === 1 ? 'oră' : 'ore' }, m: function (c) { return c === 1 ? 'minut' : 'minute' }, s: function (c) { return c === 1 ? 'secundă' : 'secunde' }, ms: function (c) { return c === 1 ? 'milisecundă' : 'milisecunde' }, decimal: ',' }, ru: { y: function (c) { return ['лет', 'год', 'года'][getSlavicForm(c)] }, mo: function (c) { return ['месяцев', 'месяц', 'месяца'][getSlavicForm(c)] }, w: function (c) { return ['недель', 'неделя', 'недели'][getSlavicForm(c)] }, d: function (c) { return ['дней', 'день', 'дня'][getSlavicForm(c)] }, h: function (c) { return ['часов', 'час', 'часа'][getSlavicForm(c)] }, m: function (c) { return ['минут', 'минута', 'минуты'][getSlavicForm(c)] }, s: function (c) { return ['секунд', 'секунда', 'секунды'][getSlavicForm(c)] }, ms: function (c) { return ['миллисекунд', 'миллисекунда', 'миллисекунды'][getSlavicForm(c)] }, decimal: ',' }, uk: { y: function (c) { return ['років', 'рік', 'роки'][getSlavicForm(c)] }, mo: function (c) { return ['місяців', 'місяць', 'місяці'][getSlavicForm(c)] }, w: function (c) { return ['тижнів', 'тиждень', 'тижні'][getSlavicForm(c)] }, d: function (c) { return ['днів', 'день', 'дні'][getSlavicForm(c)] }, h: function (c) { return ['годин', 'година', 'години'][getSlavicForm(c)] }, m: function (c) { return ['хвилин', 'хвилина', 'хвилини'][getSlavicForm(c)] }, s: function (c) { return ['секунд', 'секунда', 'секунди'][getSlavicForm(c)] }, ms: function (c) { return ['мілісекунд', 'мілісекунда', 'мілісекунди'][getSlavicForm(c)] }, decimal: ',' }, ur: { y: 'سال', mo: function (c) { return c === 1 ? 'مہینہ' : 'مہینے' }, w: function (c) { return c === 1 ? 'ہفتہ' : 'ہفتے' }, d: 'دن', h: function (c) { return c === 1 ? 'گھنٹہ' : 'گھنٹے' }, m: 'منٹ', s: 'سیکنڈ', ms: 'ملی سیکنڈ', decimal: '.' }, sk: { y: function (c) { return ['rok', 'roky', 'roky', 'rokov'][getCzechOrSlovakForm(c)] }, mo: function (c) { return ['mesiac', 'mesiace', 'mesiace', 'mesiacov'][getCzechOrSlovakForm(c)] }, w: function (c) { return ['týždeň', 'týždne', 'týždne', 'týždňov'][getCzechOrSlovakForm(c)] }, d: function (c) { return ['deň', 'dni', 'dni', 'dní'][getCzechOrSlovakForm(c)] }, h: function (c) { return ['hodina', 'hodiny', 'hodiny', 'hodín'][getCzechOrSlovakForm(c)] }, m: function (c) { return ['minúta', 'minúty', 'minúty', 'minút'][getCzechOrSlovakForm(c)] }, s: function (c) { return ['sekunda', 'sekundy', 'sekundy', 'sekúnd'][getCzechOrSlovakForm(c)] }, ms: function (c) { return ['milisekunda', 'milisekundy', 'milisekundy', 'milisekúnd'][getCzechOrSlovakForm(c)] }, decimal: ',' }, sv: { y: 'år', mo: function (c) { return 'månad' + (c === 1 ? '' : 'er') }, w: function (c) { return 'veck' + (c === 1 ? 'a' : 'or') }, d: function (c) { return 'dag' + (c === 1 ? '' : 'ar') }, h: function (c) { return 'timm' + (c === 1 ? 'e' : 'ar') }, m: function (c) { return 'minut' + (c === 1 ? '' : 'er') }, s: function (c) { return 'sekund' + (c === 1 ? '' : 'er') }, ms: function (c) { return 'millisekund' + (c === 1 ? '' : 'er') }, decimal: ',' }, tr: { y: 'yıl', mo: 'ay', w: 'hafta', d: 'gün', h: 'saat', m: 'dakika', s: 'saniye', ms: 'milisaniye', decimal: ',' }, th: { y: 'ปี', mo: 'เดือน', w: 'อาทิตย์', d: 'วัน', h: 'ชั่วโมง', m: 'นาที', s: 'วินาที', ms: 'มิลลิวินาที', decimal: '.' }, vi: { y: 'năm', mo: 'tháng', w: 'tuần', d: 'ngày', h: 'giờ', m: 'phút', s: 'giây', ms: 'mili giây', decimal: ',' }, zh_CN: { y: '年', mo: '个月', w: '周', d: '天', h: '小时', m: '分钟', s: '秒', ms: '毫秒', decimal: '.' }, zh_TW: { y: '年', mo: '個月', w: '周', d: '天', h: '小時', m: '分鐘', s: '秒', ms: '毫秒', decimal: '.' } } // You can create a humanizer, which returns a function with default // parameters. function humanizer (passedOptions) { var result = function humanizer (ms, humanizerOptions) { var options = extend({}, result, humanizerOptions || {}) return doHumanization(ms, options) } return extend(result, { language: 'en', delimiter: ', ', spacer: ' ', conjunction: '', serialComma: true, units: ['y', 'mo', 'w', 'd', 'h', 'm', 's'], languages: {}, round: false, unitMeasures: { y: 31557600000, mo: 2629800000, w: 604800000, d: 86400000, h: 3600000, m: 60000, s: 1000, ms: 1 } }, passedOptions) } // The main function is just a wrapper around a default humanizer. var humanizeDuration = humanizer({}) // Build dictionary from options function getDictionary (options) { var languagesFromOptions = [options.language] if (has(options, 'fallbacks')) { if (isArray(options.fallbacks) && options.fallbacks.length) { languagesFromOptions = languagesFromOptions.concat(options.fallbacks) } else { throw new Error('fallbacks must be an array with at least one element') } } for (var i = 0; i < languagesFromOptions.length; i++) { var languageToTry = languagesFromOptions[i] if (has(options.languages, languageToTry)) { return options.languages[languageToTry] } else if (has(languages, languageToTry)) { return languages[languageToTry] } } throw new Error('No language found.') } // doHumanization does the bulk of the work. function doHumanization (ms, options) { var i, len, piece // Make sure we have a positive number. // Has the nice sideffect of turning Number objects into primitives. ms = Math.abs(ms) var dictionary = getDictionary(options) var pieces = [] // Start at the top and keep removing units, bit by bit. var unitName, unitMS, unitCount for (i = 0, len = options.units.length; i < len; i++) { unitName = options.units[i] unitMS = options.unitMeasures[unitName] // What's the number of full units we can fit? if (i + 1 === len) { if (has(options, 'maxDecimalPoints')) { // We need to use this expValue to avoid rounding functionality of toFixed call var expValue = Math.pow(10, options.maxDecimalPoints) var unitCountFloat = (ms / unitMS) unitCount = parseFloat((Math.floor(expValue * unitCountFloat) / expValue).toFixed(options.maxDecimalPoints)) } else { unitCount = ms / unitMS } } else { unitCount = Math.floor(ms / unitMS) } // Add the string. pieces.push({ unitCount: unitCount, unitName: unitName }) // Remove what we just figured out. ms -= unitCount * unitMS } var firstOccupiedUnitIndex = 0 for (i = 0; i < pieces.length; i++) { if (pieces[i].unitCount) { firstOccupiedUnitIndex = i break } } if (options.round) { var ratioToLargerUnit, previousPiece for (i = pieces.length - 1; i >= 0; i--) { piece = pieces[i] piece.unitCount = Math.round(piece.unitCount) if (i === 0) { break } previousPiece = pieces[i - 1] ratioToLargerUnit = options.unitMeasures[previousPiece.unitName] / options.unitMeasures[piece.unitName] if ((piece.unitCount % ratioToLargerUnit) === 0 || (options.largest && ((options.largest - 1) < (i - firstOccupiedUnitIndex)))) { previousPiece.unitCount += piece.unitCount / ratioToLargerUnit piece.unitCount = 0 } } } var result = [] for (i = 0, pieces.length; i < len; i++) { piece = pieces[i] if (piece.unitCount) { result.push(render(piece.unitCount, piece.unitName, dictionary, options)) } if (result.length === options.largest) { break } } if (result.length) { if (!options.conjunction || result.length === 1) { return result.join(options.delimiter) } else if (result.length === 2) { return result.join(options.conjunction) } else if (result.length > 2) { return result.slice(0, -1).join(options.delimiter) + (options.serialComma ? ',' : '') + options.conjunction + result.slice(-1) } } else { return render(0, options.units[options.units.length - 1], dictionary, options) } } function render (count, type, dictionary, options) { var decimal if (has(options, 'decimal')) { decimal = options.decimal } else if (has(dictionary, 'decimal')) { decimal = dictionary.decimal } else { decimal = '.' } var countStr = count.toString().replace('.', decimal) var dictionaryValue = dictionary[type] var word if (typeof dictionaryValue === 'function') { word = dictionaryValue(count) } else { word = dictionaryValue } return countStr + options.spacer + word } function extend (destination) { var source for (var i = 1; i < arguments.length; i++) { source = arguments[i] for (var prop in source) { if (has(source, prop)) { destination[prop] = source[prop] } } } return destination } // Internal helper function for Polish language. function getPolishForm (c) { if (c === 1) { return 0 } else if (Math.floor(c) !== c) { return 1 } else if (c % 10 >= 2 && c % 10 <= 4 && !(c % 100 > 10 && c % 100 < 20)) { return 2 } else { return 3 } } // Internal helper function for Russian and Ukranian languages. function getSlavicForm (c) { if (Math.floor(c) !== c) { return 2 } else if ((c % 100 >= 5 && c % 100 <= 20) || (c % 10 >= 5 && c % 10 <= 9) || c % 10 === 0) { return 0 } else if (c % 10 === 1) { return 1 } else if (c > 1) { return 2 } else { return 0 } } // Internal helper function for Slovak language. function getCzechOrSlovakForm (c) { if (c === 1) { return 0 } else if (Math.floor(c) !== c) { return 1 } else if (c % 10 >= 2 && c % 10 <= 4 && c % 100 < 10) { return 2 } else { return 3 } } // Internal helper function for Lithuanian language. function getLithuanianForm (c) { if (c === 1 || (c % 10 === 1 && c % 100 > 20)) { return 0 } else if (Math.floor(c) !== c || (c % 10 >= 2 && c % 100 > 20) || (c % 10 >= 2 && c % 100 < 10)) { return 1 } else { return 2 } } // Internal helper function for Latvian language. function getLatvianForm (c) { if (c === 1 || (c % 10 === 1 && c % 100 !== 11)) { return 0 } else { return 1 } } // Internal helper function for Arabic language. function getArabicForm (c) { if (c <= 2) { return 0 } if (c > 2 && c < 11) { return 1 } return 0 } // We need to make sure we support browsers that don't have // `Array.isArray`, so we define a fallback here. var isArray = Array.isArray || function (arg) { return Object.prototype.toString.call(arg) === '[object Array]' } function has (obj, key) { return Object.prototype.hasOwnProperty.call(obj, key) } humanizeDuration.getSupportedLanguages = function getSupportedLanguages () { var result = [] for (var language in languages) { if (has(languages, language) && language !== 'gr') { result.push(language) } } return result } humanizeDuration.humanizer = humanizer if (typeof define === 'function' && define.amd) { define(function () { return humanizeDuration }) } else if (typeof module !== 'undefined' && module.exports) { module.exports = humanizeDuration } else { this.humanizeDuration = humanizeDuration } })(); // eslint-disable-line semi
extend1994/cdnjs
ajax/libs/humanize-duration/3.20.1/humanize-duration.js
JavaScript
mit
28,768
// Copyright (c) 2013-2015 Titanium I.T. LLC. All rights reserved. See LICENSE.TXT for details. (function() { "use strict"; var arrayToSentence = require("array-to-sentence"); var objectAssign = require("object-assign"); // ponyfill for Object.assign(); check if Node supports it yet exports.check = function(arg, type, options) { var argType = getType(arg); if (!Array.isArray(type)) type = [ type ]; options = options || {}; options.name = options.name || "argument"; for (var i = 0; i < type.length; i++) { if (oneTypeMatches(arg, argType, type[i])) { if (isStructComparison(argType, type[i])) return checkStruct(arg, type[i], options); else return null; } } return describeError(argType, type, options.name); function oneTypeMatches(arg, argType, type) { if (argType === Object) return checkObject(arg, type); else if (Number.isNaN(argType)) return Number.isNaN(type); else return argType === type; function checkObject(arg, type) { if (typeof type === "function") return arg instanceof type; else if (typeof type === "object") return typeof arg === "object"; else throw new Error("unrecognized type: " + type); } } function isStructComparison(argType, type) { return argType === Object && typeof type === "object"; } function checkStruct(arg, type, options) { if (typeof type !== "object") throw new Error("unrecognized type: " + type); var keys = Object.getOwnPropertyNames(type); for (var i = 0; i < keys.length; i++) { var newOptions = objectAssign({}, options); newOptions.name = options.name + "." + keys[i]; var checkResult = exports.check(arg[keys[i]], type[keys[i]], newOptions); if (checkResult !== null) return checkResult; } return null; } function describeError(argType, type, name) { var describe = exports.describe; var articles = { articles: true }; return name + " must be " + describe(type, articles) + ", but it was " + describe(argType, articles); } }; exports.describe = function(type, options) { if (!Array.isArray(type)) type = [ type ]; if (options === undefined) options = {}; var descriptions = type.map(function(oneType) { return describeOneType(oneType); }); if (descriptions.length <= 2) return descriptions.join(" or "); else return arrayToSentence(descriptions, { lastSeparator: ", or " }); // dat Oxford comma function describeOneType(type) { switch(type) { case Boolean: return options.articles ? "a boolean" : "boolean"; case String: return options.articles ? "a string" : "string"; case Number: return options.articles ? "a number" : "number"; case Function: return options.articles ? "a function" : "function"; case Array: return options.articles ? "an array" : "array"; case undefined: return "undefined"; case null: return "null"; default: if (Number.isNaN(type)) return "NaN"; else if (typeof type === "function") return describeObject(type, options); else if (typeof type === "object") return describeStruct(type, options); else throw new Error("unrecognized type: " + type); } } function describeObject(type, options) { var articles = options.articles; if (type === Object) return articles ? "an object" : "object"; else if (type === RegExp) return articles ? "a regular expression" : "regular expression"; var name = type.name; if (name) { if (articles) name = "a " + name; } else { name = articles ? "an <anon>" : "<anon>"; } return name + " instance"; } function describeStruct(type, options) { var properties = Object.getOwnPropertyNames(type).map(function(key) { return key + ": <" + exports.describe(type[key]) + ">"; }); if (properties.length === 0) return options.articles ? "an object" : "object"; var description = " " + properties.join(", ") + " "; return (options.articles ? "an " : "") + "object containing {" + description + "}"; } }; function getType(variable) { if (variable === null) return null; if (Array.isArray(variable)) return Array; if (Number.isNaN(variable)) return NaN; switch (typeof variable) { case "boolean": return Boolean; case "string": return String; case "number": return Number; case "function": return Function; case "object": return Object; case "undefined": return undefined; default: throw new Error("Unreachable code executed. Unknown typeof value: " + typeof variable); } } }());
evrimfeyyaz/ios-calculator
node_modules/simplebuild/lib/type.js
JavaScript
mit
4,496
var searchData= [ ['cache',['cache',['../classglobals.html#a5637b6b2c65cc2b027616212978a0e47',1,'globals']]], ['camera',['camera',['../classglobals.html#af37dc090d333e3a996373643f7c2c31f',1,'globals']]], ['camera_5fdistance',['camera_distance',['../classplayer.html#ae80ee7bccfac6b0b1167e3260db03206',1,'player']]], ['camera_5ffirst_5fperson',['camera_first_person',['../classplayer.html#ac31f384bb1a62333fc79fd1abd6fe4c4',1,'player']]], ['camera_5fpitch',['camera_pitch',['../classplayer.html#abb7b860ec40207dcc5f6e8ab414db5e5',1,'player']]], ['camera_5fyaw',['camera_yaw',['../classplayer.html#af3291faa017eb5a379d18f4efb86f8df',1,'player']]], ['cameranode_5f',['cameraNode_',['../class_u_s_p.html#a7cfd1fc925146d7b7700eaaf843ec5da',1,'USP']]], ['context',['context',['../classglobals.html#a90d6620c5d95436101be5e76b18a9002',1,'globals']]], ['current_5flevel',['current_level',['../classgs__playing.html#ad5484e116fdab7774ccd9e1a3c0c8789',1,'gs_playing']]] ];
gawag/Urho-Sample-Platformer
doxygen/html/search/variables_2.js
JavaScript
mit
980
/*! * OverlayScrollbars * https://github.com/KingSora/OverlayScrollbars * * Version: 1.7.3 * * Copyright KingSora. * https://github.com/KingSora * * Released under the MIT license. * Date: 23.06.2019 */ (function (global, factory) { if (typeof define === 'function' && define.amd) define(function() { return factory(global, global.document, undefined); }); else if (typeof module === 'object' && typeof module.exports === 'object') module.exports = factory(global, global.document, undefined); else factory(global, global.document, undefined); }(typeof window !== 'undefined' ? window : this, function(window, document, undefined) { 'use strict'; var PLUGINNAME = 'OverlayScrollbars'; var TYPES = { o : 'object', f : 'function', a : 'array', s : 'string', b : 'boolean', n : 'number', u : 'undefined', z : 'null' //d : 'date', //e : 'error', //r : 'regexp', //y : 'symbol' }; var LEXICON = { c : 'class', s : 'style', i : 'id', l : 'length', p : 'prototype', oH : 'offsetHeight', cH : 'clientHeight', sH : 'scrollHeight', oW : 'offsetWidth', cW : 'clientWidth', sW : 'scrollWidth' }; var VENDORS = { //https://developer.mozilla.org/en-US/docs/Glossary/Vendor_Prefix _jsCache : { }, _cssCache : { }, _cssPrefixes : ['-webkit-', '-moz-', '-o-', '-ms-'], _jsPrefixes : ['WebKit', 'Moz', 'O', 'MS'], _cssProperty : function(name) { var cache = this._cssCache; if(cache[name]) return cache[name]; var prefixes = this._cssPrefixes; var uppercasedName = this._firstLetterToUpper(name); var elmStyle = document.createElement('div')[LEXICON.s]; var resultPossibilities; var i = 0; var v = 0; var currVendorWithoutDashes; for (; i < prefixes.length; i++) { currVendorWithoutDashes = prefixes[i].replace(/-/g, ''); resultPossibilities = [ name, //transition prefixes[i] + name, //-webkit-transition currVendorWithoutDashes + uppercasedName, //webkitTransition this._firstLetterToUpper(currVendorWithoutDashes) + uppercasedName //WebkitTransition ]; for(v = 0; v < resultPossibilities[LEXICON.l]; v++) { if(elmStyle[resultPossibilities[v]] !== undefined) { cache[name] = resultPossibilities[v]; return resultPossibilities[v]; } } } return null; }, _jsAPI : function(name, isInterface, fallback) { var prefixes = this._jsPrefixes; var cache = this._jsCache; var i = 0; var result = cache[name]; if(!result) { result = window[name]; for(; i < prefixes[LEXICON.l]; i++) result = result || window[(isInterface ? prefixes[i] : prefixes[i].toLowerCase()) + this._firstLetterToUpper(name)]; cache[name] = result; } return result || fallback; }, _firstLetterToUpper : function(str) { return str.charAt(0).toUpperCase() + str.slice(1); } }; var COMPATIBILITY = { /** * Gets the current window width. * @returns {Number|number} The current window width in pixel. */ wW: function() { return window.innerWidth || document.documentElement[LEXICON.cW] || document.body[LEXICON.cW]; }, /** * Gets the current window height. * @returns {Number|number} The current window height in pixel. */ wH: function() { return window.innerHeight || document.documentElement[LEXICON.cH] || document.body[LEXICON.cH]; }, /** * Gets the MutationObserver Object or undefined if not supported. * @returns {MutationObserver|*|undefined} The MutationsObserver Object or undefined. */ mO: function() { return VENDORS._jsAPI('MutationObserver', true); }, /** * Gets the ResizeObserver Object or undefined if not supported. * @returns {MutationObserver|*|undefined} The ResizeObserver Object or undefined. */ rO: function() { return VENDORS._jsAPI('ResizeObserver', true); }, /** * Gets the RequestAnimationFrame method or it's corresponding polyfill. * @returns {*|Function} The RequestAnimationFrame method or it's corresponding polyfill. */ rAF: function() { return VENDORS._jsAPI('requestAnimationFrame', false, function (func) { return window.setTimeout(func, 1000 / 60); }); }, /** * Gets the CancelAnimationFrame method or it's corresponding polyfill. * @returns {*|Function} The CancelAnimationFrame method or it's corresponding polyfill. */ cAF: function() { return VENDORS._jsAPI('cancelAnimationFrame', false, function (id) { return window.clearTimeout(id); }); }, /** * Gets the current time. * @returns {number} The current time. */ now: function() { return Date.now && Date.now() || new Date().getTime(); }, /** * Stops the propagation of the given event. * @param event The event of which the propagation shall be stoped. */ stpP: function(event) { if(event.stopPropagation) event.stopPropagation(); else event.cancelBubble = true; }, /** * Prevents the default action of the given event. * @param event The event of which the default action shall be prevented. */ prvD: function(event) { if(event.preventDefault && event.cancelable) event.preventDefault(); else event.returnValue = false; }, /** * Gets the pageX and pageY values of the given mouse event. * @param event The mouse event of which the pageX and pageX shall be got. * @returns {{x: number, y: number}} x = pageX value, y = pageY value. */ page: function(event) { event = event.originalEvent || event; var strPage = 'page'; var strClient = 'client'; var strX = 'X'; var strY = 'Y'; var target = event.target || event.srcElement || document; var eventDoc = target.ownerDocument || document; var doc = eventDoc.documentElement; var body = eventDoc.body; //if touch event return return pageX/Y of it if(event.touches !== undefined) { var touch = event.touches[0]; return { x : touch[strPage + strX], y : touch[strPage + strY] } } // Calculate pageX/Y if not native supported if (!event[strPage + strX] && event[strClient + strX] && event[strClient + strX] != null) { return { x : event[strClient + strX] + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0), y : event[strClient + strY] + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0) } } return { x : event[strPage + strX], y : event[strPage + strY] }; }, /** * Gets the clicked mouse button of the given mouse event. * @param event The mouse event of which the clicked button shal be got. * @returns {number} The number of the clicked mouse button. (0 : none | 1 : leftButton | 2 : middleButton | 3 : rightButton) */ mBtn: function(event) { var button = event.button; if (!event.which && button !== undefined) return (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0))); else return event.which; }, /** * Checks whether a item is in the given array and returns its index. * @param item The item of which the position in the array shall be determined. * @param arr The array. * @returns {number} The zero based index of the item or -1 if the item isn't in the array. */ inA : function(item, arr) { for (var i = 0; i < arr[LEXICON.l]; i++) //Sometiems in IE a "SCRIPT70" Permission denied error occurs if HTML elements in a iFrame are compared try { if (arr[i] === item) return i; } catch(e) { } return -1; }, /** * Returns true if the given value is a array. * @param arr The potential array. * @returns {boolean} True if the given value is a array, false otherwise. */ isA: function(arr) { var def = Array.isArray; return def ? def(arr) : this.type(arr) == TYPES.a; }, /** * Determine the internal JavaScript [[Class]] of the given object. * @param obj The object of which the type shall be determined. * @returns {string} The type of the given object. */ type: function(obj) { if (obj === undefined) return obj + ""; if (obj === null) return obj + ""; return Object[LEXICON.p].toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase(); }, bind: function(func, thisObj) { if (typeof func != TYPES.f) { throw "Can't bind function!"; // closest thing possible to the ECMAScript 5 // internal IsCallable function //throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var proto = LEXICON.p; var aArgs = Array[proto].slice.call(arguments, 2); var fNOP = function() {}; var fBound = function() { return func.apply(this instanceof fNOP ? this : thisObj, aArgs.concat(Array[proto].slice.call(arguments))); }; if (func[proto]) fNOP[proto] = func[proto]; // Function.prototype doesn't have a prototype property fBound[proto] = new fNOP(); return fBound; } /** * Gets the vendor-prefixed CSS property by the given name. * For example the given name is "transform" and you're using a old Firefox browser then the returned value would be "-moz-transform". * If the browser doesn't need a vendor-prefix, then the returned string is the given name. * If the browser doesn't support the given property name at all (not even with a vendor-prefix) the returned value is null. * @param propName The unprefixed CSS property name. * @returns {string|null} The vendor-prefixed CSS property or null if the browser doesn't support the given CSS property. cssProp : function(propName) { return VENDORS._cssProperty(propName); } */ }; var MATH = Math; var JQUERY = window.jQuery; var EASING = (function() { var _easingsMath = { p : MATH.PI, c : MATH.cos, s : MATH.sin, w : MATH.pow, t : MATH.sqrt, n : MATH.asin, a : MATH.abs, o : 1.70158 }; /* x : current percent (0 - 1), t : current time (duration * percent), b : start value (from), c : end value (to), d : duration easingName : function(x, t, b, c, d) { return easedValue; } */ return { swing: function (x, t, b, c, d) { return 0.5 - _easingsMath.c(x * _easingsMath.p) / 2; }, linear: function(x, t, b, c, d) { return x; }, easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { return ((t/=d/2) < 1) ? c/2*t*t + b : -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { return ((t/=d/2) < 1) ? c/2*t*t*t + b : c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { return ((t/=d/2) < 1) ? c/2*t*t*t*t + b : -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { return ((t/=d/2) < 1) ? c/2*t*t*t*t*t + b : c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * _easingsMath.c(t/d * (_easingsMath.p/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * _easingsMath.s(t/d * (_easingsMath.p/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (_easingsMath.c(_easingsMath.p*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * _easingsMath.w(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t==d) ? b+c : c * (-_easingsMath.w(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * _easingsMath.w(2, 10 * (t - 1)) + b; return c/2 * (-_easingsMath.w(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (_easingsMath.t(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * _easingsMath.t(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, t, b, c, d) { return ((t/=d/2) < 1) ? -c/2 * (_easingsMath.t(1 - t*t) - 1) + b : c/2 * (_easingsMath.t(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s=_easingsMath.o;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < _easingsMath.a(c)) { a=c; s=p/4; } else s = p/(2*_easingsMath.p) * _easingsMath.n (c/a); return -(a*_easingsMath.w(2,10*(t-=1)) * _easingsMath.s( (t*d-s)*(2*_easingsMath.p)/p )) + b; }, easeOutElastic: function (x, t, b, c, d) { var s=_easingsMath.o;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < _easingsMath.a(c)) { a=c; s=p/4; } else s = p/(2*_easingsMath.p) * _easingsMath.n (c/a); return a*_easingsMath.w(2,-10*t) * _easingsMath.s( (t*d-s)*(2*_easingsMath.p)/p ) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s=_easingsMath.o;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < _easingsMath.a(c)) { a=c; s=p/4; } else s = p/(2*_easingsMath.p) * _easingsMath.n (c/a); if (t < 1) return -.5*(a*_easingsMath.w(2,10*(t-=1)) * _easingsMath.s( (t*d-s)*(2*_easingsMath.p)/p )) + b; return a*_easingsMath.w(2,-10*(t-=1)) * _easingsMath.s( (t*d-s)*(2*_easingsMath.p)/p )*.5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { s = s || _easingsMath.o; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { s = s || _easingsMath.o; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { s = s || _easingsMath.o; return ((t/=d/2) < 1) ? c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b : c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - this.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { var o = 7.5625; if ((t/=d) < (1/2.75)) { return c*(o*t*t) + b; } else if (t < (2/2.75)) { return c*(o*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(o*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(o*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { return (t < d/2) ? this.easeInBounce (x, t*2, 0, c, d) * .5 + b : this.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; } }; /* * * TERMS OF USE - EASING EQUATIONS * * Open source under the BSD License. * * Copyright © 2001 Robert Penner * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of 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 OWNER 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. * */ })(); var FRAMEWORK = (function() { var _rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); var _strSpace = ' '; var _strEmpty = ''; var _strScrollLeft = 'scrollLeft'; var _strScrollTop = 'scrollTop'; var _animations = [ ]; var _type = COMPATIBILITY.type; var _cssNumber = { "animationIterationCount": true, "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }; var extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments[LEXICON.l], deep = false; // Handle a deep copy situation if (_type(target) == TYPES.b) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if (_type(target) != TYPES.o && !_type(target) == TYPES.f) { target = {}; } // extend jQuery itself if only one argument is passed if (length === i) { target = FakejQuery; --i; } for (; i < length; i++) { // Only deal with non-null/undefined values if ((options = arguments[i]) != null) { // Extend the base object for (name in options) { src = target[name]; copy = options[name]; // Prevent never-ending loop if (target === copy) { continue; } // Recurse if we're merging plain objects or arrays if (deep && copy && (isPlainObject(copy) || (copyIsArray = COMPATIBILITY.isA(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && COMPATIBILITY.isA(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[name] = extend(deep, clone, copy); // Don't bring in undefined values } else if (copy !== undefined) { target[name] = copy; } } } } // Return the modified object return target; }; var inArray = function(item, arr, fromIndex) { for (var i = fromIndex || 0; i < arr[LEXICON.l]; i++) if (arr[i] === item) return i; return -1; } var isFunction = function(obj) { return _type(obj) == TYPES.f; }; var isEmptyObject = function(obj) { for (var name in obj ) return false; return true; }; var isPlainObject = function(obj) { if (!obj || _type(obj) != TYPES.o) return false; var key; var proto = LEXICON.p; var hasOwnProperty = Object[proto].hasOwnProperty; var hasOwnConstructor = hasOwnProperty.call(obj, 'constructor'); var hasIsPrototypeOf = obj.constructor && obj.constructor[proto] && hasOwnProperty.call(obj.constructor[proto], 'isPrototypeOf'); if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { return false; } for (key in obj) { /**/ } return _type(key) == TYPES.u || hasOwnProperty.call(obj, key); }; var each = function(obj, callback) { var i = 0; if (isArrayLike(obj)) { for (; i < obj[LEXICON.l]; i++) { if (callback.call(obj[i], i, obj[i]) === false) break; } } else { for (i in obj) { if (callback.call(obj[i], i, obj[i]) === false) break; } } return obj; }; var FakejQuery = function (selector) { if(arguments[LEXICON.l] === 0) return this; var base = new FakejQuery(); var elements = selector; var i = 0; var elms; var el; if(_type(selector) == TYPES.s) { elements = [ ]; if(selector.charAt(0) === '<') { el = document.createElement('div'); el.innerHTML = selector; elms = el.children; } else { elms = document.querySelectorAll(selector); } for(; i < elms[LEXICON.l]; i++) elements.push(elms[i]); } if(elements) { if(_type(elements) != TYPES.s && (!isArrayLike(elements) || elements === window || elements === elements.self)) elements = [ elements ]; for(i = 0; i < elements[LEXICON.l]; i++) base[i] = elements[i]; base[LEXICON.l] = elements[LEXICON.l]; } return base; }; function isArrayLike(obj) { var length = !!obj && [LEXICON.l] in obj && obj[LEXICON.l]; var t = _type(obj); return isFunction(t) ? false : (t == TYPES.a || length === 0 || _type(length) == TYPES.n && length > 0 && (length - 1) in obj); } function stripAndCollapse(value) { var tokens = value.match(_rnothtmlwhite) || []; return tokens.join(_strSpace); } function matches(elem, selector) { var nodeList = (elem.parentNode || document).querySelectorAll(selector) || []; var i = nodeList[LEXICON.l]; while (i--) if (nodeList[i] == elem) return true; return false; } function insertAdjacentElement(el, strategy, child) { if(_type(child) == TYPES.a) { for(var i = 0; i < child[LEXICON.l]; i++) insertAdjacentElement(el, strategy, child[i]); } else if(_type(child) == TYPES.s) el.insertAdjacentHTML(strategy, child); else el.insertAdjacentElement(strategy, child.nodeType ? child : child[0]); } function setCSSVal(el, prop, val) { try { if(el[LEXICON.s][prop] !== undefined) el[LEXICON.s][prop] = parseCSSVal(prop, val); } catch(e) { } } function parseCSSVal(prop, val) { if(!_cssNumber[prop.toLowerCase()] && _type(val) == TYPES.n) val += 'px'; return val; } function startNextAnimationInQ(animObj, removeFromQ) { var index; var nextAnim; if(removeFromQ !== false) animObj.q.splice(0, 1); if(animObj.q[LEXICON.l] > 0) { nextAnim = animObj.q[0]; animate(animObj.el, nextAnim.props, nextAnim.duration, nextAnim.easing, nextAnim.complete, true); } else { index = inArray(animObj, _animations); if(index > -1) _animations.splice(index, 1); } } function setAnimationValue(el, prop, value) { if(prop === _strScrollLeft || prop === _strScrollTop) el[prop] = value; else setCSSVal(el, prop, value); } function animate(el, props, options, easing, complete, guaranteedNext) { var hasOptions = isPlainObject(options); var from = { }; var to = { }; var i = 0; var key; var animObj; var start; var progress; var step; var specialEasing; var duration; if(hasOptions) { easing = options.easing; start = options.start; progress = options.progress; step = options.step; specialEasing = options.specialEasing; complete = options.complete; duration = options.duration; } else duration = options; specialEasing = specialEasing || { }; duration = duration || 400; easing = easing || 'swing'; guaranteedNext = guaranteedNext || false; for(; i < _animations[LEXICON.l]; i++) { if(_animations[i].el === el) { animObj = _animations[i]; break; } } if(!animObj) { animObj = { el : el, q : [] }; _animations.push(animObj); } for (key in props) { if(key === _strScrollLeft || key === _strScrollTop) from[key] = el[key]; else from[key] = FakejQuery(el).css(key); } for (key in from) { if(from[key] !== props[key] && props[key] !== undefined) to[key] = props[key]; } if(!isEmptyObject(to)) { var timeNow; var end; var percent; var fromVal; var toVal; var easedVal; var timeStart; var frame; var elapsed; var qPos = guaranteedNext ? 0 : inArray(qObj, animObj.q); var qObj = { props : to, duration : hasOptions ? options : duration, easing : easing, complete : complete }; if (qPos === -1) { qPos = animObj.q[LEXICON.l]; animObj.q.push(qObj); } if(qPos === 0) { if(duration > 0) { timeStart = COMPATIBILITY.now(); frame = function() { timeNow = COMPATIBILITY.now(); elapsed = (timeNow - timeStart); end = qObj.stop || elapsed >= duration; percent = 1 - ((MATH.max(0, timeStart + duration - timeNow) / duration) || 0); for(key in to) { fromVal = parseFloat(from[key]); toVal = parseFloat(to[key]); easedVal = (toVal - fromVal) * EASING[specialEasing[key] || easing](percent, percent * duration, 0, 1, duration) + fromVal; setAnimationValue(el, key, easedVal); if(isFunction(step)) { step(easedVal, { elem : el, prop : key, start : fromVal, now : easedVal, end : toVal, pos : percent, options : { easing : easing, speacialEasing : specialEasing, duration : duration, complete : complete, step : step }, startTime : timeStart }); } } if(isFunction(progress)) progress({ }, percent, MATH.max(0, duration - elapsed)); if (end) { startNextAnimationInQ(animObj); if(isFunction(complete)) complete(); } else qObj.frame = COMPATIBILITY.rAF()(frame); }; qObj.frame = COMPATIBILITY.rAF()(frame); } else { for(key in to) setAnimationValue(el, key, to[key]); startNextAnimationInQ(animObj); } } } else if(guaranteedNext) startNextAnimationInQ(animObj); } function stop(el, clearQ, jumpToEnd) { var animObj; var qObj; var key; var i = 0; for(; i < _animations[LEXICON.l]; i++) { animObj = _animations[i]; if(animObj.el === el) { if(animObj.q[LEXICON.l] > 0) { qObj = animObj.q[0]; qObj.stop = true; COMPATIBILITY.cAF()(qObj.frame); animObj.q.splice(0, 1); if(jumpToEnd) for(key in qObj.props) setAnimationValue(el, key, qObj.props[key]); if(clearQ) animObj.q = [ ]; else startNextAnimationInQ(animObj, false); } break; } } } FakejQuery[LEXICON.p] = { //EVENTS: on : function(eventName, handler) { eventName = (eventName || _strEmpty).match(_rnothtmlwhite) || [_strEmpty]; var eventNameLength = eventName[LEXICON.l]; var i = 0; var el; return this.each(function() { el = this; try { if (el.addEventListener) { for (; i < eventNameLength; i++) el.addEventListener(eventName[i], handler); } else if(el.detachEvent) { for (; i < eventNameLength; i++) el.attachEvent('on' + eventName[i], handler); } } catch (e) { } }); }, off : function(eventName, handler) { eventName = (eventName || _strEmpty).match(_rnothtmlwhite) || [_strEmpty]; var eventNameLength = eventName[LEXICON.l]; var i = 0; var el; return this.each(function() { el = this; try { if (el.removeEventListener) { for (; i < eventNameLength; i++) el.removeEventListener(eventName[i], handler); } else if(el.detachEvent) { for (; i < eventNameLength; i++) el.detachEvent('on' + eventName[i], handler); } } catch (e) { } }); }, one : function (eventName, handler) { eventName = (eventName || _strEmpty).match(_rnothtmlwhite) || [_strEmpty]; return this.each(function() { var el = FakejQuery(this); FakejQuery.each(eventName, function(i, oneEventName) { var oneHandler = function(e) { handler.call(this, e); el.off(oneEventName, oneHandler); }; el.on(oneEventName, oneHandler); }); }); }, trigger : function(eventName) { var el; var event; return this.each(function() { el = this; if (document.createEvent) { event = document.createEvent('HTMLEvents'); event.initEvent(eventName, true, false); el.dispatchEvent(event); } else { el.fireEvent("on" + eventName); } }); }, //DOM NODE INSERTING / REMOVING: append : function(child) { return this.each(function() { insertAdjacentElement(this, 'beforeend', child); }); }, prepend : function(child) { return this.each(function() { insertAdjacentElement(this, 'afterbegin', child); }); }, before : function(child) { return this.each(function() { insertAdjacentElement(this, 'beforebegin', child); }); }, after : function(child) { return this.each(function() { insertAdjacentElement(this, 'afterend', child); }); }, remove : function() { return this.each(function() { var el = this; var parentNode = el.parentNode; if(parentNode != null) parentNode.removeChild(el); }); }, unwrap : function() { var parents = [ ]; var i; var el; var parent; this.each(function() { parent = this.parentNode; if(inArray(parent, parents) === - 1) parents.push(parent); }); for(i = 0; i < parents[LEXICON.l]; i++) { el = parents[i]; parent = el.parentNode; while (el.firstChild) parent.insertBefore(el.firstChild, el); parent.removeChild(el); } return this; }, wrapAll : function(wrapperHTML) { var i; var nodes = this; var wrapper = FakejQuery(wrapperHTML)[0]; var deepest = wrapper; var parent = nodes[0].parentNode; var previousSibling = nodes[0].previousSibling; while(deepest.childNodes[LEXICON.l] > 0) deepest = deepest.childNodes[0]; for (i = 0; nodes[LEXICON.l] - i; deepest.firstChild === nodes[0] && i++) deepest.appendChild(nodes[i]); var nextSibling = previousSibling ? previousSibling.nextSibling : parent.firstChild; parent.insertBefore(wrapper, nextSibling); return this; }, wrapInner : function(wrapperHTML) { return this.each(function() { var el = FakejQuery(this); var contents = el.contents(); if (contents[LEXICON.l]) contents.wrapAll(wrapperHTML); else el.append(wrapperHTML); }); }, wrap : function(wrapperHTML) { return this.each(function() { FakejQuery(this).wrapAll(wrapperHTML); }); }, //DOM NODE MANIPULATION / INFORMATION: css : function(styles, val) { var el; var key; var cptStyle; var getCptStyle = window.getComputedStyle; if(_type(styles) == TYPES.s) { if(val === undefined) { el = this[0]; cptStyle = getCptStyle ? getCptStyle(el, null) : el.currentStyle[styles]; //https://bugzilla.mozilla.org/show_bug.cgi?id=548397 can be null sometimes if iframe with display: none (firefox only!) return getCptStyle ? cptStyle != null ? cptStyle.getPropertyValue(styles) : el[LEXICON.s][styles] : cptStyle; } else { return this.each(function() { setCSSVal(this, styles, val); }); } } else { return this.each(function() { for(key in styles) setCSSVal(this, key, styles[key]); }); } }, hasClass : function(className) { var elem, i = 0; var classNamePrepared = _strSpace + className + _strSpace; var classList; while ((elem = this[ i++ ])) { classList = elem.classList; if(classList && classList.contains(className)) return true; else if (elem.nodeType === 1 && (_strSpace + stripAndCollapse(elem.className + _strEmpty) + _strSpace).indexOf(classNamePrepared) > -1) return true; } return false; }, addClass : function(className) { var classes; var elem; var cur; var curValue; var clazz; var finalValue; var supportClassList; var elmClassList; var i = 0; var v = 0; if (className) { classes = className.match( _rnothtmlwhite ) || []; while ((elem = this[i++])) { elmClassList = elem.classList; if(supportClassList === undefined) supportClassList = elmClassList !== undefined; if(supportClassList) { while ((clazz = classes[v++])) elmClassList.add(clazz); } else { curValue = elem.className + _strEmpty; cur = elem.nodeType === 1 && (_strSpace + stripAndCollapse(curValue) + _strSpace); if (cur) { while ((clazz = classes[v++])) if (cur.indexOf(_strSpace + clazz + _strSpace) < 0) cur += clazz + _strSpace; finalValue = stripAndCollapse(cur); if (curValue !== finalValue) elem.className = finalValue; } } } } return this; }, removeClass : function(className) { var classes; var elem; var cur; var curValue; var clazz; var finalValue; var supportClassList; var elmClassList; var i = 0; var v = 0; if (className) { classes = className.match(_rnothtmlwhite) || []; while ((elem = this[i++])) { elmClassList = elem.classList; if(supportClassList === undefined) supportClassList = elmClassList !== undefined; if(supportClassList) { while ((clazz = classes[v++])) elmClassList.remove(clazz); } else { curValue = elem.className + _strEmpty; cur = elem.nodeType === 1 && (_strSpace + stripAndCollapse(curValue) + _strSpace); if (cur) { while ((clazz = classes[v++])) while (cur.indexOf(_strSpace + clazz + _strSpace) > -1) cur = cur.replace(_strSpace + clazz + _strSpace, _strSpace); finalValue = stripAndCollapse(cur); if (curValue !== finalValue) elem.className = finalValue; } } } } return this; }, hide : function() { return this.each(function() { this[LEXICON.s].display = 'none'; }); }, show : function() { return this.each(function() { this[LEXICON.s].display = 'block'; }); }, attr : function(attrName, value) { var i = 0; var el; while (el = this[i++]) { if(value === undefined) return el.getAttribute(attrName); el.setAttribute(attrName, value); } return this; }, removeAttr : function(attrName) { return this.each(function() { this.removeAttribute(attrName); }); }, offset : function() { var el = this[0]; var rect = el.getBoundingClientRect(); var scrollLeft = window.pageXOffset || document.documentElement[_strScrollLeft]; var scrollTop = window.pageYOffset || document.documentElement[_strScrollTop]; return { top: rect.top + scrollTop, left: rect.left + scrollLeft }; }, position : function() { var el = this[0]; return { top: el.offsetTop, left: el.offsetLeft }; }, scrollLeft : function(value) { var i = 0; var el; while (el = this[i++]) { if(value === undefined) return el[_strScrollLeft]; el[_strScrollLeft] = value; } return this; }, scrollTop : function(value) { var i = 0; var el; while (el = this[i++]) { if(value === undefined) return el[_strScrollTop]; el[_strScrollTop] = value; } return this; }, val : function(value) { var el = this[0]; if(!value) return el.value; el.value = value; return this; }, //DOM TRAVERSAL / FILTERING: first : function() { return this.eq(0); }, last : function() { return this.eq(-1); }, eq : function(index) { return FakejQuery(this[index >= 0 ? index : this[LEXICON.l] + index]); }, find : function(selector) { var children = [ ]; var i; this.each(function() { var el = this; var ch = el.querySelectorAll(selector); for(i = 0; i < ch[LEXICON.l]; i++) children.push(ch[i]); }); return FakejQuery(children); }, children : function(selector) { var children = [ ]; var el; var ch; var i; this.each(function() { ch = this.children; for(i = 0; i < ch[LEXICON.l]; i++) { el = ch[i]; if(selector) { if((el.matches && el.matches(selector)) || matches(el, selector)) children.push(el); } else children.push(el); } }); return FakejQuery(children); }, parent : function(selector) { var parents = [ ]; var parent; this.each(function() { parent = this.parentNode; if(selector ? FakejQuery(parent).is(selector) : true) parents.push(parent); }); return FakejQuery(parents); }, is : function(selector) { var el; var i; for(i = 0; i < this[LEXICON.l]; i++) { el = this[i]; if(selector === ":visible") return !!(el[LEXICON.oW] || el[LEXICON.oH] || el.getClientRects()[LEXICON.l]); if(selector === ":hidden") return !!!(el[LEXICON.oW] || el[LEXICON.oH] || el.getClientRects()[LEXICON.l]); if((el.matches && el.matches(selector)) || matches(el, selector)) return true; } return false; }, contents : function() { var contents = [ ]; var childs; var i; this.each(function() { childs = this.childNodes; for(i = 0; i < childs[LEXICON.l]; i++) contents.push(childs[i]); }); return FakejQuery(contents); }, each : function(callback) { return each(this, callback); }, //ANIMATION: animate : function(props, duration, easing, complete) { return this.each(function() { animate(this, props, duration, easing, complete); }); }, stop : function(clearQ, jump) { return this.each(function() { stop(this, clearQ, jump); }); } }; extend(FakejQuery, { extend : extend, inArray : inArray, isEmptyObject : isEmptyObject, isPlainObject : isPlainObject, each : each }); return FakejQuery; })(); var INSTANCES = (function() { var _targets = [ ]; var _instancePropertyString = '__overlayScrollbars__'; /** * Register, unregister or get a certain (or all) instances. * Register: Pass the target and the instance. * Unregister: Pass the target and null. * Get Instance: Pass the target from which the instance shall be got. * Get Targets: Pass no arguments. * @param target The target to which the instance shall be registered / from which the instance shall be unregistered / the instance shall be got * @param instance The instance. * @returns {*|void} Returns the instance from the given target. */ return function (target, instance) { var argLen = arguments[LEXICON.l]; if(argLen < 1) { //return all targets return _targets; } else { if(instance) { //register instance target[_instancePropertyString] = instance; _targets.push(target); } else { var index = COMPATIBILITY.inA(target, _targets); if (index > -1) { if(argLen > 1) { //unregister instance delete target[_instancePropertyString]; _targets.splice(index, 1); } else { //get instance from target return _targets[index][_instancePropertyString]; } } } } } })(); var PLUGIN = (function() { var _pluginsGlobals; var _pluginsAutoUpdateLoop; var _pluginsExtensions = [ ]; var _pluginsOptions = (function() { var possibleTemplateTypes = [ TYPES.b, //boolean TYPES.n, //number TYPES.s, //string TYPES.a, //array TYPES.o, //object TYPES.f, //function TYPES.z //null ]; var restrictedStringsSplit = ' '; var restrictedStringsPossibilitiesSplit = ':'; var classNameAllowedValues = [TYPES.z, TYPES.s]; var numberAllowedValues = TYPES.n; var booleanNullAllowedValues = [TYPES.z, TYPES.b]; var booleanTrueTemplate = [true, TYPES.b]; var booleanFalseTemplate = [false, TYPES.b]; var callbackTemplate = [null, [TYPES.z, TYPES.f]]; var inheritedAttrsTemplate = [['style', 'class'], [TYPES.s, TYPES.a, TYPES.z]]; var resizeAllowedValues = 'n:none b:both h:horizontal v:vertical'; var overflowBehaviorAllowedValues = 'v-h:visible-hidden v-s:visible-scroll s:scroll h:hidden'; var scrollbarsVisibilityAllowedValues = 'v:visible h:hidden a:auto'; var scrollbarsAutoHideAllowedValues = 'n:never s:scroll l:leave m:move'; var optionsDefaultsAndTemplate = { className: ['os-theme-dark', classNameAllowedValues], //null || string resize: ['none', resizeAllowedValues], //none || both || horizontal || vertical || n || b || h || v sizeAutoCapable: booleanTrueTemplate, //true || false clipAlways: booleanTrueTemplate, //true || false normalizeRTL: booleanTrueTemplate, //true || false paddingAbsolute: booleanFalseTemplate, //true || false autoUpdate: [null, booleanNullAllowedValues], //true || false || null autoUpdateInterval: [33, numberAllowedValues], //number nativeScrollbarsOverlaid: { showNativeScrollbars: booleanFalseTemplate, //true || false initialize: booleanTrueTemplate //true || false }, overflowBehavior: { x: ['scroll', overflowBehaviorAllowedValues], //visible-hidden || visible-scroll || hidden || scroll || v-h || v-s || h || s y: ['scroll', overflowBehaviorAllowedValues] //visible-hidden || visible-scroll || hidden || scroll || v-h || v-s || h || s }, scrollbars: { visibility: ['auto', scrollbarsVisibilityAllowedValues], //visible || hidden || auto || v || h || a autoHide: ['never', scrollbarsAutoHideAllowedValues], //never || scroll || leave || move || n || s || l || m autoHideDelay: [800, numberAllowedValues], //number dragScrolling: booleanTrueTemplate, //true || false clickScrolling: booleanFalseTemplate, //true || false touchSupport: booleanTrueTemplate, //true || false snapHandle: booleanFalseTemplate //true || false }, textarea: { dynWidth: booleanFalseTemplate, //true || false dynHeight: booleanFalseTemplate, //true || false inheritedAttrs : inheritedAttrsTemplate //string || array || null }, callbacks: { onInitialized: callbackTemplate, //null || function onInitializationWithdrawn: callbackTemplate, //null || function onDestroyed: callbackTemplate, //null || function onScrollStart: callbackTemplate, //null || function onScroll: callbackTemplate, //null || function onScrollStop: callbackTemplate, //null || function onOverflowChanged: callbackTemplate, //null || function onOverflowAmountChanged: callbackTemplate, //null || function onDirectionChanged: callbackTemplate, //null || function onContentSizeChanged: callbackTemplate, //null || function onHostSizeChanged: callbackTemplate, //null || function onUpdated: callbackTemplate //null || function } }; var convert = function(template) { var recursive = function(obj) { var key; var val; var valType; for(key in obj) { if(!obj.hasOwnProperty(key)) continue; val = obj[key]; valType = COMPATIBILITY.type(val); if(valType == TYPES.a) obj[key] = val[template ? 1 : 0]; else if(valType == TYPES.o) obj[key] = recursive(val); } return obj; }; return recursive(FRAMEWORK.extend(true, { }, optionsDefaultsAndTemplate)); }; return { _defaults : convert(), _template : convert(true), /** * Validates the passed object by the passed template. * @param obj The object which shall be validated. * @param template The template which defines the allowed values and types. * @param writeErrors True if errors shall be logged to the console. * @param usePreparedValues True if the validated main values shall be returned in the validated object, false otherwise. * @param keepForeignProps True if properties which aren't in the template shall be added to the validated object, false otherwise. * @returns {{}} A object which contains only the valid properties of the passed original object. */ _validate : function (obj, template, writeErrors, usePreparedValues, keepForeignProps) { var validatedOptions = { }; var objectCopy = FRAMEWORK.extend(true, { }, obj); var checkObjectProps = function(data, template, validatedOptions, prevPropName) { for (var prop in template) { if (template.hasOwnProperty(prop) && data.hasOwnProperty(prop)) { var isValid = false; var templateValue = template[prop]; var templateValueType = COMPATIBILITY.type(templateValue); var templateIsComplext = templateValueType == TYPES.o; var templateTypes = COMPATIBILITY.type(templateValue) != TYPES.a ? [ templateValue ] : templateValue; var dataValue = data[prop]; var dataValueType = COMPATIBILITY.type(dataValue); var propPrefix = prevPropName ? prevPropName + "." : ""; var error = "The option \"" + propPrefix + prop + "\" wasn't set, because"; var errorPossibleTypes = [ ]; var errorRestrictedStrings = [ ]; var restrictedStringValuesSplit; var restrictedStringValuesPossibilitiesSplit; var isRestrictedValue; var mainPossibility; var currType; var i; var v; var j; //if the template has a object as value, it means that the options are complex (verschachtelt) if(templateIsComplext && dataValueType == TYPES.o) { validatedOptions[prop] = { }; checkObjectProps(dataValue, templateValue, validatedOptions[prop], propPrefix + prop); if(FRAMEWORK.isEmptyObject(dataValue)) delete data[prop]; } else if(!templateIsComplext) { for(i = 0; i < templateTypes.length; i++) { currType = templateTypes[i]; templateValueType = COMPATIBILITY.type(currType); //if currtype is string and starts with restrictedStringPrefix and end with restrictedStringSuffix isRestrictedValue = templateValueType == TYPES.s && FRAMEWORK.inArray(currType, possibleTemplateTypes) === -1; if(isRestrictedValue) { errorPossibleTypes.push(TYPES.s); //split it into a array which contains all possible values for example: ["y:yes", "n:no", "m:maybe"] restrictedStringValuesSplit = currType.split(restrictedStringsSplit); errorRestrictedStrings = errorRestrictedStrings.concat(restrictedStringValuesSplit); for(v = 0; v < restrictedStringValuesSplit.length; v++) { //split the possible values into their possibiliteis for example: ["y", "yes"] -> the first is always the mainPossibility restrictedStringValuesPossibilitiesSplit = restrictedStringValuesSplit[v].split(restrictedStringsPossibilitiesSplit); mainPossibility = restrictedStringValuesPossibilitiesSplit[0]; for(j = 0; j < restrictedStringValuesPossibilitiesSplit.length; j++) { //if any possibility matches with the dataValue, its valid if(dataValue === restrictedStringValuesPossibilitiesSplit[j]) { isValid = true; break; } } if(isValid) break; } } else { errorPossibleTypes.push(currType); if(dataValueType === currType) { isValid = true; break; } } } if(isValid) { validatedOptions[prop] = isRestrictedValue && usePreparedValues ? mainPossibility : dataValue; } else if(writeErrors) { console.warn(error + " it doesn't accept the type [ " + dataValueType.toUpperCase() + " ] with the value of \"" + dataValue + "\".\r\n" + "Accepted types are: [ " + errorPossibleTypes.join(", ").toUpperCase() + " ]." + (errorRestrictedStrings.length > 0 ? "\r\nValid strings are: [ " + errorRestrictedStrings.join(", ").split(restrictedStringsPossibilitiesSplit).join(", ") + " ]." : "")); } delete data[prop]; } } } }; checkObjectProps(objectCopy, template, validatedOptions); //add values which aren't specified in the template to the finished validated object to prevent them from being discarded if(keepForeignProps) FRAMEWORK.extend(true, validatedOptions, objectCopy); else if(!FRAMEWORK.isEmptyObject(objectCopy) && writeErrors) console.warn("The following options are discarded due to invalidity:\r\n" + window.JSON.stringify(objectCopy, null, 2)); return validatedOptions; } } }()); /** * Initializes the object which contains global information about the plugin and each instance of it. */ function initOverlayScrollbarsStatics() { if(!_pluginsGlobals) _pluginsGlobals = new OverlayScrollbarsGlobals(_pluginsOptions._defaults); if(!_pluginsAutoUpdateLoop) _pluginsAutoUpdateLoop = new OverlayScrollbarsAutoUpdateLoop(_pluginsGlobals); } /** * The global object for the OverlayScrollbars objects. It contains resources which every OverlayScrollbars object needs. This object is initialized only once: if the first OverlayScrollbars object gets initialized. * @param defaultOptions * @constructor */ function OverlayScrollbarsGlobals(defaultOptions) { var _base = this; var strOverflow = 'overflow'; var strHidden = 'hidden'; var strScroll = 'scroll'; var bodyElement = FRAMEWORK('body'); var scrollbarDummyElement = FRAMEWORK('<div id="os-dummy-scrollbar-size"><div></div></div>'); var scrollbarDummyElement0 = scrollbarDummyElement[0]; var dummyContainerChild = FRAMEWORK(scrollbarDummyElement.children('div').eq(0)); var getCptStyle = window.getComputedStyle; bodyElement.append(scrollbarDummyElement); scrollbarDummyElement.hide().show(); //fix IE8 bug (incorrect measuring) var nativeScrollbarSize = calcNativeScrollbarSize(scrollbarDummyElement0); var nativeScrollbarIsOverlaid = { x: nativeScrollbarSize.x === 0, y: nativeScrollbarSize.y === 0 }; FRAMEWORK.extend(_base, { defaultOptions : defaultOptions, autoUpdateLoop : false, autoUpdateRecommended : !COMPATIBILITY.mO(), nativeScrollbarSize : nativeScrollbarSize, nativeScrollbarIsOverlaid : nativeScrollbarIsOverlaid, nativeScrollbarStyling : (function() { scrollbarDummyElement.addClass('os-viewport-native-scrollbars-invisible'); //fix opera bug: scrollbar styles will only appear if overflow value is scroll or auto during the activation of the style. //and set overflow to scroll //scrollbarDummyElement.css(strOverflow, strHidden).hide().css(strOverflow, strScroll).show(); //return (scrollbarDummyElement0[LEXICON.oH] - scrollbarDummyElement0[LEXICON.cH]) === 0 && (scrollbarDummyElement0[LEXICON.oW] - scrollbarDummyElement0[LEXICON.cW]) === 0; return scrollbarDummyElement.css('scrollbar-width') === 'none' || (getCptStyle ? getCptStyle(scrollbarDummyElement0, '::-webkit-scrollbar').getPropertyValue('display') === 'none' : false); })(), overlayScrollbarDummySize : { x: 30, y: 30 }, msie : (function() { var ua = window.navigator.userAgent; var strIndexOf = 'indexOf'; var strSubString = 'substring'; var msie = ua[strIndexOf]('MSIE '); var trident = ua[strIndexOf]('Trident/'); var edge = ua[strIndexOf]('Edge/'); var rv = ua[strIndexOf]('rv:'); var result; var parseIntFunc = parseInt; // IE 10 or older => return version number if (msie > 0) result = parseIntFunc(ua[strSubString](msie + 5, ua[strIndexOf]('.', msie)), 10); // IE 11 => return version number else if (trident > 0) result = parseIntFunc(ua[strSubString](rv + 3, ua[strIndexOf]('.', rv)), 10); // Edge (IE 12+) => return version number else if (edge > 0) result = parseIntFunc(ua[strSubString](edge + 5, ua[strIndexOf]('.', edge)), 10); // other browser return result; })(), cssCalc : (function() { var dummyStyle = document.createElement('div')[LEXICON.s]; var strCalc = 'calc'; var i = -1; var prop; for(; i < VENDORS._cssPrefixes[LEXICON.l]; i++) { prop = i < 0 ? strCalc : VENDORS._cssPrefixes[i] + strCalc; dummyStyle.cssText = 'width:' + prop + '(1px);'; if (dummyStyle[LEXICON.l]) return prop; } return null; })(), restrictedMeasuring : (function() { //https://bugzilla.mozilla.org/show_bug.cgi?id=1439305 scrollbarDummyElement.css(strOverflow, strHidden); var scrollSize = { w : scrollbarDummyElement0[LEXICON.sW], h : scrollbarDummyElement0[LEXICON.sH] }; scrollbarDummyElement.css(strOverflow, 'visible'); var scrollSize2 = { w : scrollbarDummyElement0[LEXICON.sW], h : scrollbarDummyElement0[LEXICON.sH] }; return (scrollSize.w - scrollSize2.w) !== 0 || (scrollSize.h - scrollSize2.h) !== 0; })(), rtlScrollBehavior : (function() { scrollbarDummyElement.css({ 'overflow-y' : strHidden, 'overflow-x' : strScroll, 'direction' : 'rtl' }).scrollLeft(0); var dummyContainerOffset = scrollbarDummyElement.offset(); var dummyContainerChildOffset = dummyContainerChild.offset(); scrollbarDummyElement.scrollLeft(999); var dummyContainerScrollOffsetAfterScroll = dummyContainerChild.offset(); return { //origin direction = determines if the zero scroll position is on the left or right side //'i' means 'invert' (i === true means that the axis must be inverted to be correct) //true = on the left side //false = on the right side i : dummyContainerOffset.left === dummyContainerChildOffset.left, //negative = determines if the maximum scroll is positive or negative //'n' means 'negate' (n === true means that the axis must be negated to be correct) //true = negative //false = positive n : dummyContainerChildOffset.left - dummyContainerScrollOffsetAfterScroll.left === 0 }; })(), supportTransform : VENDORS._cssProperty('transform') !== null, supportTransition : VENDORS._cssProperty('transition') !== null, supportPassiveEvents : (function() { var supportsPassive = false; try { window.addEventListener('test', null, Object.defineProperty({ }, 'passive', { get: function() { supportsPassive = true; } })); } catch (e) { } return supportsPassive; })(), supportResizeObserver : !!COMPATIBILITY.rO(), supportMutationObserver : !!COMPATIBILITY.mO() }); scrollbarDummyElement.removeAttr(LEXICON.s).remove(); //Catch zoom event: (function () { if(nativeScrollbarIsOverlaid.x && nativeScrollbarIsOverlaid.y) return; var abs = MATH.abs; var windowWidth = COMPATIBILITY.wW(); var windowHeight = COMPATIBILITY.wH(); var windowDpr = getWindowDPR(); var onResize = function() { if(INSTANCES().length > 0) { var newW = COMPATIBILITY.wW(); var newH = COMPATIBILITY.wH(); var deltaW = newW - windowWidth; var deltaH = newH - windowHeight; if (deltaW === 0 && deltaH === 0) return; var deltaWRatio = MATH.round(newW / (windowWidth / 100.0)); var deltaHRatio = MATH.round(newH / (windowHeight / 100.0)); var absDeltaW = abs(deltaW); var absDeltaH = abs(deltaH); var absDeltaWRatio = abs(deltaWRatio); var absDeltaHRatio = abs(deltaHRatio); var newDPR = getWindowDPR(); var deltaIsBigger = absDeltaW > 2 && absDeltaH > 2; var difference = !differenceIsBiggerThanOne(absDeltaWRatio, absDeltaHRatio); var dprChanged = newDPR !== windowDpr && windowDpr > 0; var isZoom = deltaIsBigger && difference && dprChanged; var oldScrollbarSize = _base.nativeScrollbarSize; var newScrollbarSize; if (isZoom) { bodyElement.append(scrollbarDummyElement); newScrollbarSize = _base.nativeScrollbarSize = calcNativeScrollbarSize(scrollbarDummyElement[0]); scrollbarDummyElement.remove(); if(oldScrollbarSize.x !== newScrollbarSize.x || oldScrollbarSize.y !== newScrollbarSize.y) { FRAMEWORK.each(INSTANCES(), function () { if(INSTANCES(this)) INSTANCES(this).update('zoom'); }); } } windowWidth = newW; windowHeight = newH; windowDpr = newDPR; } }; function differenceIsBiggerThanOne(valOne, valTwo) { var absValOne = abs(valOne); var absValTwo = abs(valTwo); return !(absValOne === absValTwo || absValOne + 1 === absValTwo || absValOne - 1 === absValTwo); } function getWindowDPR() { var dDPI = window.screen.deviceXDPI || 0; var sDPI = window.screen.logicalXDPI || 1; return window.devicePixelRatio || (dDPI / sDPI); } FRAMEWORK(window).on('resize', onResize); })(); function calcNativeScrollbarSize(measureElement) { return { x: measureElement[LEXICON.oH] - measureElement[LEXICON.cH], y: measureElement[LEXICON.oW] - measureElement[LEXICON.cW] }; } } /** * The object which manages the auto update loop for all OverlayScrollbars objects. This object is initialized only once: if the first OverlayScrollbars object gets initialized. * @constructor */ function OverlayScrollbarsAutoUpdateLoop(globals) { var _base = this; var _strAutoUpdate = 'autoUpdate'; var _strAutoUpdateInterval = _strAutoUpdate + 'Interval'; var _strLength = LEXICON.l; var _loopingInstances = [ ]; var _loopingInstancesIntervalCache = [ ]; var _loopIsActive = false; var _loopIntervalDefault = 33; var _loopInterval = _loopIntervalDefault; var _loopTimeOld = COMPATIBILITY.now(); var _loopID; /** * The auto update loop which will run every 50 milliseconds or less if the update interval of a instance is lower than 50 milliseconds. */ var loop = function() { if(_loopingInstances[_strLength] > 0 && _loopIsActive) { _loopID = COMPATIBILITY.rAF()(function () { loop(); }); var timeNew = COMPATIBILITY.now(); var timeDelta = timeNew - _loopTimeOld; var lowestInterval; var instance; var instanceOptions; var instanceAutoUpdateAllowed; var instanceAutoUpdateInterval; var now; if (timeDelta > _loopInterval) { _loopTimeOld = timeNew - (timeDelta % _loopInterval); lowestInterval = _loopIntervalDefault; for(var i = 0; i < _loopingInstances[_strLength]; i++) { instance = _loopingInstances[i]; if (instance !== undefined) { instanceOptions = instance.options(); instanceAutoUpdateAllowed = instanceOptions[_strAutoUpdate]; instanceAutoUpdateInterval = MATH.max(1, instanceOptions[_strAutoUpdateInterval]); now = COMPATIBILITY.now(); if ((instanceAutoUpdateAllowed === true || instanceAutoUpdateAllowed === null) && (now - _loopingInstancesIntervalCache[i]) > instanceAutoUpdateInterval) { instance.update('auto'); _loopingInstancesIntervalCache[i] = new Date(now += instanceAutoUpdateInterval); } lowestInterval = MATH.max(1, MATH.min(lowestInterval, instanceAutoUpdateInterval)); } } _loopInterval = lowestInterval; } } else { _loopInterval = _loopIntervalDefault; } }; /** * Add OverlayScrollbars instance to the auto update loop. Only successful if the instance isn't already added. * @param instance The instance which shall be updated in a loop automatically. */ _base.add = function(instance) { if(FRAMEWORK.inArray(instance, _loopingInstances) === -1) { _loopingInstances.push(instance); _loopingInstancesIntervalCache.push(COMPATIBILITY.now()); if (_loopingInstances[_strLength] > 0 && !_loopIsActive) { _loopIsActive = true; globals.autoUpdateLoop = _loopIsActive; loop(); } } }; /** * Remove OverlayScrollbars instance from the auto update loop. Only successful if the instance was added before. * @param instance The instance which shall be updated in a loop automatically. */ _base.remove = function(instance) { var index = FRAMEWORK.inArray(instance, _loopingInstances); if(index > -1) { //remove from loopingInstances list _loopingInstancesIntervalCache.splice(index, 1); _loopingInstances.splice(index, 1); //correct update loop behavior if (_loopingInstances[_strLength] === 0 && _loopIsActive) { _loopIsActive = false; globals.autoUpdateLoop = _loopIsActive; if(_loopID !== undefined) { COMPATIBILITY.cAF()(_loopID); _loopID = -1; } } } }; } /** * A object which manages the scrollbars visibility of the target element. * @param pluginTargetElement The element from which the scrollbars shall be hidden. * @param options The custom options. * @param extensions The custom extensions. * @param globals * @param autoUpdateLoop * @returns {*} * @constructor */ function OverlayScrollbarsInstance(pluginTargetElement, options, extensions, globals, autoUpdateLoop) { //if passed element is no HTML element: skip and return if(!isHTMLElement(pluginTargetElement)) return; //if passed element is already initialized: set passed options if there are any and return its instance if(INSTANCES(pluginTargetElement)) { var inst = INSTANCES(pluginTargetElement); inst.options(options); return inst; } //make correct instanceof var _base = new window[PLUGINNAME](); var _frameworkProto = FRAMEWORK[LEXICON.p]; //globals: var _nativeScrollbarIsOverlaid; var _overlayScrollbarDummySize; var _rtlScrollBehavior; var _autoUpdateRecommended; var _msieVersion; var _nativeScrollbarStyling; var _cssCalc; var _nativeScrollbarSize; var _supportTransition; var _supportTransform; var _supportPassiveEvents; var _supportResizeObserver; var _supportMutationObserver; var _restrictedMeasuring; //general readonly: var _initialized; var _destroyed; var _isTextarea; var _isBody; var _documentMixed; var _isTextareaHostGenerated; //general: var _isBorderBox; var _sizeAutoObserverAdded; var _paddingX; var _paddingY; var _borderX; var _borderY; var _marginX; var _marginY; var _isRTL; var _isSleeping; var _contentBorderSize = { }; var _scrollHorizontalInfo = { }; var _scrollVerticalInfo = { }; var _viewportSize = { }; var _nativeScrollbarMinSize = { }; //naming: var _strMinusHidden = '-hidden'; var _strMarginMinus = 'margin-'; var _strPaddingMinus = 'padding-'; var _strBorderMinus = 'border-'; var _strTop = 'top'; var _strRight = 'right'; var _strBottom = 'bottom'; var _strLeft = 'left'; var _strMinMinus = 'min-'; var _strMaxMinus = 'max-'; var _strWidth = 'width'; var _strHeight = 'height'; var _strFloat = 'float'; var _strEmpty = ''; var _strAuto = 'auto'; var _strScroll = 'scroll'; var _strHundredPercent = '100%'; var _strX = 'x'; var _strY = 'y'; var _strDot = '.'; var _strSpace = ' '; var _strScrollbar = 'scrollbar'; var _strMinusHorizontal = '-horizontal'; var _strMinusVertical = '-vertical'; var _strScrollLeft = _strScroll + 'Left'; var _strScrollTop = _strScroll + 'Top'; var _strMouseTouchDownEvent = 'mousedown touchstart'; var _strMouseTouchUpEvent = 'mouseup touchend touchcancel'; var _strMouseTouchMoveEvent = 'mousemove touchmove'; var _strMouseTouchEnter = 'mouseenter'; var _strMouseTouchLeave = 'mouseleave'; var _strKeyDownEvent = 'keydown'; var _strKeyUpEvent = 'keyup'; var _strSelectStartEvent = 'selectstart'; var _strTransitionEndEvent = 'transitionend webkitTransitionEnd oTransitionEnd'; var _strResizeObserverProperty = '__overlayScrollbarsRO__'; //class names: var _cassNamesPrefix = 'os-'; var _classNameHTMLElement = _cassNamesPrefix + 'html'; var _classNameHostElement = _cassNamesPrefix + 'host'; var _classNameHostTextareaElement = _classNameHostElement + '-textarea'; var _classNameHostScrollbarHorizontalHidden = _classNameHostElement + '-' + _strScrollbar + _strMinusHorizontal + _strMinusHidden; var _classNameHostScrollbarVerticalHidden = _classNameHostElement + '-' + _strScrollbar + _strMinusVertical + _strMinusHidden; var _classNameHostTransition = _classNameHostElement + '-transition'; var _classNameHostRTL = _classNameHostElement + '-rtl'; var _classNameHostResizeDisabled = _classNameHostElement + '-resize-disabled'; var _classNameHostScrolling = _classNameHostElement + '-scrolling'; var _classNameHostOverflow = _classNameHostElement + '-overflow'; var _classNameHostOverflowX = _classNameHostOverflow + '-x'; var _classNameHostOverflowY = _classNameHostOverflow + '-y'; var _classNameTextareaElement = _cassNamesPrefix + 'textarea'; var _classNameTextareaCoverElement = _classNameTextareaElement + '-cover'; var _classNamePaddingElement = _cassNamesPrefix + 'padding'; var _classNameViewportElement = _cassNamesPrefix + 'viewport'; var _classNameViewportNativeScrollbarsInvisible = _classNameViewportElement + '-native-scrollbars-invisible'; var _classNameViewportNativeScrollbarsOverlaid = _classNameViewportElement + '-native-scrollbars-overlaid'; var _classNameContentElement = _cassNamesPrefix + 'content'; var _classNameContentArrangeElement = _cassNamesPrefix + 'content-arrange'; var _classNameContentGlueElement = _cassNamesPrefix + 'content-glue'; var _classNameSizeAutoObserverElement = _cassNamesPrefix + 'size-auto-observer'; var _classNameResizeObserverElement = _cassNamesPrefix + 'resize-observer'; var _classNameResizeObserverItemElement = _cassNamesPrefix + 'resize-observer-item'; var _classNameResizeObserverItemFinalElement = _classNameResizeObserverItemElement + '-final'; var _classNameTextInherit = _cassNamesPrefix + 'text-inherit'; var _classNameScrollbar = _cassNamesPrefix + _strScrollbar; var _classNameScrollbarTrack = _classNameScrollbar + '-track'; var _classNameScrollbarTrackOff = _classNameScrollbarTrack + '-off'; var _classNameScrollbarHandle = _classNameScrollbar + '-handle'; var _classNameScrollbarHandleOff = _classNameScrollbarHandle + '-off'; var _classNameScrollbarUnusable = _classNameScrollbar + '-unusable'; var _classNameScrollbarAutoHidden = _classNameScrollbar + '-' + _strAuto + _strMinusHidden; var _classNameScrollbarCorner = _classNameScrollbar + '-corner'; var _classNameScrollbarCornerResize = _classNameScrollbarCorner + '-resize'; var _classNameScrollbarCornerResizeB = _classNameScrollbarCornerResize + '-both'; var _classNameScrollbarCornerResizeH = _classNameScrollbarCornerResize + _strMinusHorizontal; var _classNameScrollbarCornerResizeV = _classNameScrollbarCornerResize + _strMinusVertical; var _classNameScrollbarHorizontal = _classNameScrollbar + _strMinusHorizontal; var _classNameScrollbarVertical = _classNameScrollbar + _strMinusVertical; var _classNameDragging = _cassNamesPrefix + 'dragging'; var _classNameThemeNone = _cassNamesPrefix + 'theme-none'; //callbacks: var _callbacksInitQeueue = [ ]; //options: var _defaultOptions; var _currentOptions; var _currentPreparedOptions; //extensions: var _extensions = { }; var _extensionsPrivateMethods = "added removed on contract"; //update var _lastUpdateTime; var _swallowedUpdateParams = { }; var _swallowedUpdateTimeout; var _swallowUpdateLag = 42; var _imgs = [ ]; //DOM elements: var _windowElement; var _documentElement; var _htmlElement; var _bodyElement; var _targetElement; //the target element of this OverlayScrollbars object var _hostElement; //the host element of this OverlayScrollbars object -> may be the same as targetElement var _sizeAutoObserverElement; //observes size auto changes var _sizeObserverElement; //observes size and padding changes var _paddingElement; //manages the padding var _viewportElement; //is the viewport of our scrollbar model var _contentElement; //the element which holds the content var _contentArrangeElement; //is needed for correct sizing of the content element (only if native scrollbars are overlays) var _contentGlueElement; //has always the size of the content element var _textareaCoverElement; //only applied if target is a textarea element. Used for correct size calculation and for prevention of uncontrolled scrolling var _scrollbarCornerElement; var _scrollbarHorizontalElement; var _scrollbarHorizontalTrackElement; var _scrollbarHorizontalHandleElement; var _scrollbarVerticalElement; var _scrollbarVerticalTrackElement; var _scrollbarVerticalHandleElement; var _windowElementNative; var _documentElementNative; var _targetElementNative; var _hostElementNative; var _sizeAutoObserverElementNative; var _sizeObserverElementNative; var _paddingElementNative; var _viewportElementNative; var _contentElementNative; //Cache: var _hostSizeCache; var _contentScrollSizeCache; var _arrangeContentSizeCache; var _hasOverflowCache; var _hideOverflowCache; var _widthAutoCache; var _heightAutoCache; var _cssMaxValueCache; var _cssBoxSizingCache; var _cssPaddingCache; var _cssBorderCache; var _cssMarginCache; var _cssDirectionCache; var _cssDirectionDetectedCache; var _paddingAbsoluteCache; var _clipAlwaysCache; var _contentGlueSizeCache; var _overflowBehaviorCache; var _overflowAmountCache; var _ignoreOverlayScrollbarHidingCache; var _autoUpdateCache; var _sizeAutoCapableCache; var _textareaAutoWrappingCache; var _textareaInfoCache; var _updateAutoHostElementIdCache; var _updateAutoHostElementClassCache; var _updateAutoHostElementStyleCache; var _updateAutoHostElementVisibleCache; var _updateAutoTargetElementRowsCache; var _updateAutoTargetElementColsCache; var _updateAutoTargetElementWrapCache; var _contentElementScrollSizeChangeDetectedCache; var _hostElementSizeChangeDetectedCache; var _scrollbarsVisibilityCache; var _scrollbarsAutoHideCache; var _scrollbarsClickScrollingCache; var _scrollbarsDragScrollingCache; var _resizeCache; var _normalizeRTLCache; var _classNameCache; var _oldClassName; var _textareaDynHeightCache; var _textareaDynWidthCache; var _bodyMinSizeCache; var _viewportScrollSizeCache; var _displayIsHiddenCache; //MutationObserver: var _mutationObserverHost; var _mutationObserverContent; var _mutationObserverHostCallback; var _mutationObserverContentCallback; var _mutationObserversConnected; //textarea: var _textareaEvents; var _textareaHasFocus; //scrollbars: var _scrollbarsAutoHideTimeoutId; var _scrollbarsAutoHideMoveTimeoutId; var _scrollbarsAutoHideDelay; var _scrollbarsAutoHideNever; var _scrollbarsAutoHideScroll; var _scrollbarsAutoHideMove; var _scrollbarsAutoHideLeave; var _scrollbarsHandleHovered; var _scrollbarsHandleAsync; //resize var _resizeReconnectMutationObserver; var _resizeNone; var _resizeBoth; var _resizeHorizontal; var _resizeVertical; var _resizeOnMouseTouchDown; //==== Passive Event Listener ====// /** * Adds a passive event listener to the given element. * @param element The element to which the event listener shall be applied. * @param eventNames The name(s) of the event listener. * @param listener The listener method which shall be called. */ function addPassiveEventListener(element, eventNames, listener) { var events = eventNames.split(_strSpace); for (var i = 0; i < events.length; i++) element[0].addEventListener(events[i], listener, {passive: true}); } /** * Removes a passive event listener to the given element. * @param element The element from which the event listener shall be removed. * @param eventNames The name(s) of the event listener. * @param listener The listener method which shall be removed. */ function removePassiveEventListener(element, eventNames, listener) { var events = eventNames.split(_strSpace); for (var i = 0; i < events.length; i++) element[0].removeEventListener(events[i], listener, {passive: true}); } //==== Resize Observer ====// /** * Adds a resize observer to the given element. * @param targetElement The element to which the resize observer shall be applied. * @param onElementResizedCallback The callback which is fired every time the resize observer registers a size change. */ function addResizeObserver(targetElement, onElementResizedCallback) { var constMaximum = 3333333; var resizeObserver = COMPATIBILITY.rO(); var strAnimationStartEvent = 'animationstart mozAnimationStart webkitAnimationStart MSAnimationStart'; var strChildNodes = 'childNodes'; var callback = function () { targetElement[_strScrollTop](constMaximum)[_strScrollLeft](_isRTL ? _rtlScrollBehavior.n ? -constMaximum : _rtlScrollBehavior.i ? 0 : constMaximum : constMaximum); onElementResizedCallback(); }; if (_supportResizeObserver) { var element = targetElement.append(generateDiv(_classNameResizeObserverElement + ' observed')).contents()[0]; var observer = element[_strResizeObserverProperty] = new resizeObserver(callback); observer.observe(element); } else { if (_msieVersion > 9 || !_autoUpdateRecommended) { targetElement.prepend( generateDiv(_classNameResizeObserverElement, generateDiv({ className : _classNameResizeObserverItemElement, dir : "ltr" }, generateDiv(_classNameResizeObserverItemElement, generateDiv(_classNameResizeObserverItemFinalElement) ) + generateDiv(_classNameResizeObserverItemElement, generateDiv({ className : _classNameResizeObserverItemFinalElement, style : 'width: 200%; height: 200%' }) ) ) ) ); var observerElement = targetElement[0][strChildNodes][0][strChildNodes][0]; var shrinkElement = FRAMEWORK(observerElement[strChildNodes][1]); var expandElement = FRAMEWORK(observerElement[strChildNodes][0]); var expandElementChild = FRAMEWORK(expandElement[0][strChildNodes][0]); var widthCache = observerElement[LEXICON.oW]; var heightCache = observerElement[LEXICON.oH]; var isDirty; var rAFId; var currWidth; var currHeight; var factor = 2; var nativeScrollbarSize = globals.nativeScrollbarSize; //care don't make changes to this object!!! var reset = function () { /* var sizeResetWidth = observerElement[LEXICON.oW] + nativeScrollbarSize.x * factor + nativeScrollbarSize.y * factor + _overlayScrollbarDummySize.x + _overlayScrollbarDummySize.y; var sizeResetHeight = observerElement[LEXICON.oH] + nativeScrollbarSize.x * factor + nativeScrollbarSize.y * factor + _overlayScrollbarDummySize.x + _overlayScrollbarDummySize.y; var expandChildCSS = {}; expandChildCSS[_strWidth] = sizeResetWidth; expandChildCSS[_strHeight] = sizeResetHeight; expandElementChild.css(expandChildCSS); expandElement[_strScrollLeft](sizeResetWidth)[_strScrollTop](sizeResetHeight); shrinkElement[_strScrollLeft](sizeResetWidth)[_strScrollTop](sizeResetHeight); */ expandElement[_strScrollLeft](constMaximum)[_strScrollTop](constMaximum); shrinkElement[_strScrollLeft](constMaximum)[_strScrollTop](constMaximum); }; var onResized = function () { rAFId = 0; if (!isDirty) return; widthCache = currWidth; heightCache = currHeight; callback(); }; var onScroll = function (event) { currWidth = observerElement[LEXICON.oW]; currHeight = observerElement[LEXICON.oH]; isDirty = currWidth != widthCache || currHeight != heightCache; if (event && isDirty && !rAFId) { COMPATIBILITY.cAF()(rAFId); rAFId = COMPATIBILITY.rAF()(onResized); } else if(!event) onResized(); reset(); if (event) { COMPATIBILITY.prvD(event); COMPATIBILITY.stpP(event); } return false; }; var expandChildCSS = {}; var observerElementCSS = {}; setTopRightBottomLeft(observerElementCSS, _strEmpty, [ -((nativeScrollbarSize.y + 1) * factor), nativeScrollbarSize.x * -factor, nativeScrollbarSize.y * -factor, -((nativeScrollbarSize.x + 1) * factor) ]); FRAMEWORK(observerElement).css(observerElementCSS); expandElement.on(_strScroll, onScroll); shrinkElement.on(_strScroll, onScroll); targetElement.on(strAnimationStartEvent, function () { onScroll(false); }); //lets assume that the divs will never be that large and a constant value is enough expandChildCSS[_strWidth] = constMaximum; expandChildCSS[_strHeight] = constMaximum; expandElementChild.css(expandChildCSS); reset(); } else { var attachEvent = _documentElementNative.attachEvent; var isIE = _msieVersion !== undefined; if (attachEvent) { targetElement.prepend(generateDiv(_classNameResizeObserverElement)); findFirst(targetElement, _strDot + _classNameResizeObserverElement)[0].attachEvent('onresize', callback); } else { var obj = _documentElementNative.createElement(TYPES.o); obj.setAttribute('tabindex', '-1'); obj.setAttribute(LEXICON.c, _classNameResizeObserverElement); obj.onload = function () { var wnd = this.contentDocument.defaultView; wnd.addEventListener('resize', callback); wnd.document.documentElement.style.display = 'none'; }; obj.type = 'text/html'; if (isIE) targetElement.prepend(obj); obj.data = 'about:blank'; if (!isIE) targetElement.prepend(obj); targetElement.on(strAnimationStartEvent, callback); } } } //direction change detection: if (targetElement[0] === _sizeObserverElementNative) { var directionChanged = function () { var dir = _hostElement.css('direction'); var css = {}; var scrollLeftValue = 0; var result = false; if (dir !== _cssDirectionDetectedCache) { if (dir === 'ltr') { css[_strLeft] = 0; css[_strRight] = _strAuto; scrollLeftValue = constMaximum; } else { css[_strLeft] = _strAuto; css[_strRight] = 0; scrollLeftValue = _rtlScrollBehavior.n ? -constMaximum : _rtlScrollBehavior.i ? 0 : constMaximum; } _sizeObserverElement.children().eq(0).css(css); targetElement[_strScrollLeft](scrollLeftValue)[_strScrollTop](constMaximum); _cssDirectionDetectedCache = dir; result = true; } return result; }; directionChanged(); targetElement.on(_strScroll, function (event) { if (directionChanged()) update(); COMPATIBILITY.prvD(event); COMPATIBILITY.stpP(event); return false; }); } } /** * Removes a resize observer from the given element. * @param targetElement The element to which the target resize observer is applied. */ function removeResizeObserver(targetElement) { if (_supportResizeObserver) { var element = targetElement.contents()[0]; element[_strResizeObserverProperty].disconnect(); delete element[_strResizeObserverProperty]; } else { remove(targetElement.children(_strDot + _classNameResizeObserverElement).eq(0)); } } /** * Freezes the given resize observer. * @param targetElement The element to which the target resize observer is applied. */ function freezeResizeObserver(targetElement) { if (targetElement !== undefined) { /* if (_supportResizeObserver) { var element = targetElement.contents()[0]; element[_strResizeObserverProperty].unobserve(element); } else { targetElement = targetElement.children(_strDot + _classNameResizeObserverElement).eq(0); var w = targetElement.css(_strWidth); var h = targetElement.css(_strHeight); var css = {}; css[_strWidth] = w; css[_strHeight] = h; targetElement.css(css); } */ } } /** * Unfreezes the given resize observer. * @param targetElement The element to which the target resize observer is applied. */ function unfreezeResizeObserver(targetElement) { if (targetElement !== undefined) { /* if (_supportResizeObserver) { var element = targetElement.contents()[0]; element[_strResizeObserverProperty].observe(element); } else { var css = { }; css[_strHeight] = _strEmpty; css[_strWidth] = _strEmpty; targetElement.children(_strDot + _classNameResizeObserverElement).eq(0).css(css); } */ } } //==== Mutation Observers ====// /** * Creates MutationObservers for the host and content Element if they are supported. */ function createMutationObservers() { if (_supportMutationObserver) { var mutationObserverContentLag = 11; var mutationObserver = COMPATIBILITY.mO(); var contentLastUpdate = COMPATIBILITY.now(); var mutationTarget; var mutationAttrName; var contentTimeout; var now; var sizeAuto; var action; _mutationObserverHostCallback = function(mutations) { var doUpdate = false; var mutation; if (_initialized && !_isSleeping) { FRAMEWORK.each(mutations, function () { mutation = this; mutationTarget = mutation.target; mutationAttrName = mutation.attributeName; if (mutationAttrName === LEXICON.c) doUpdate = hostClassNamesChanged(mutation.oldValue, mutationTarget.className); else if (mutationAttrName === LEXICON.s) doUpdate = mutation.oldValue !== mutationTarget[LEXICON.s].cssText; else doUpdate = true; if (doUpdate) return false; }); if (doUpdate) _base.update(_strAuto); } return doUpdate; }; _mutationObserverContentCallback = function (mutations) { var doUpdate = false; var mutation; if (_initialized && !_isSleeping) { FRAMEWORK.each(mutations, function () { mutation = this; doUpdate = isUnknownMutation(mutation); return !doUpdate; }); if (doUpdate) { now = COMPATIBILITY.now(); sizeAuto = (_heightAutoCache || _widthAutoCache); action = function () { if(!_destroyed) { contentLastUpdate = now; //if cols, rows or wrap attr was changed if (_isTextarea) textareaUpdate(); if (sizeAuto) update(); else _base.update(_strAuto); } }; clearTimeout(contentTimeout); if (mutationObserverContentLag <= 0 || now - contentLastUpdate > mutationObserverContentLag || !sizeAuto) action(); else contentTimeout = setTimeout(action, mutationObserverContentLag); } } return doUpdate; } _mutationObserverHost = new mutationObserver(_mutationObserverHostCallback); _mutationObserverContent = new mutationObserver(_mutationObserverContentCallback); } } /** * Connects the MutationObservers if they are supported. */ function connectMutationObservers() { if (_supportMutationObserver && !_mutationObserversConnected) { _mutationObserverHost.observe(_hostElementNative, { attributes: true, attributeOldValue: true, attributeFilter: [LEXICON.i, LEXICON.c, LEXICON.s] }); _mutationObserverContent.observe(_isTextarea ? _targetElementNative : _contentElementNative, { attributes: true, attributeOldValue: true, subtree: !_isTextarea, childList: !_isTextarea, characterData: !_isTextarea, attributeFilter: _isTextarea ? ['wrap', 'cols', 'rows'] : [LEXICON.i, LEXICON.c, LEXICON.s, 'open'] }); _mutationObserversConnected = true; } } /** * Disconnects the MutationObservers if they are supported. */ function disconnectMutationObservers() { if (_supportMutationObserver && _mutationObserversConnected) { _mutationObserverHost.disconnect(); _mutationObserverContent.disconnect(); _mutationObserversConnected = false; } } /** * Disconnects the MutationObservers if they are supported. * @returns {boolean|undefined} True if the MutationObservers needed to be synchronized, false or undefined otherwise. */ function synchronizeMutationObservers() { if(_mutationObserversConnected) { var mutHost = _mutationObserverHostCallback(_mutationObserverHost.takeRecords()); var mutContent = _mutationObserverContentCallback(_mutationObserverContent.takeRecords()); return mutHost || mutContent; } } //==== Events of elements ====// /** * This method gets called every time the host element gets resized. IMPORTANT: Padding changes are detected too!! * It refreshes the hostResizedEventArgs and the hostSizeResizeCache. * If there are any size changes, the update method gets called. */ function hostOnResized() { if (_isSleeping) return; var changed; var hostSize = { w: _sizeObserverElementNative[LEXICON.sW], h: _sizeObserverElementNative[LEXICON.sH] }; if (_initialized) { changed = checkCacheDouble(hostSize, _hostElementSizeChangeDetectedCache); _hostElementSizeChangeDetectedCache = hostSize; if (changed) update(true, false); } else { _hostElementSizeChangeDetectedCache = hostSize; } } /** * The mouse enter event of the host element. This event is only needed for the autoHide feature. */ function hostOnMouseEnter() { if (_scrollbarsAutoHideLeave) refreshScrollbarsAutoHide(true); } /** * The mouse leave event of the host element. This event is only needed for the autoHide feature. */ function hostOnMouseLeave() { if (_scrollbarsAutoHideLeave && !_bodyElement.hasClass(_classNameDragging)) refreshScrollbarsAutoHide(false); } /** * The mouse move event of the host element. This event is only needed for the autoHide "move" feature. */ function hostOnMouseMove() { if (_scrollbarsAutoHideMove) { refreshScrollbarsAutoHide(true); clearTimeout(_scrollbarsAutoHideMoveTimeoutId); _scrollbarsAutoHideMoveTimeoutId = setTimeout(function () { if (_scrollbarsAutoHideMove && !_destroyed) refreshScrollbarsAutoHide(false); }, 100); } } /** * Adds or removes mouse & touch events of the host element. (for handling auto-hiding of the scrollbars) * @param destroy Indicates whether the events shall be added or removed. */ function setupHostMouseTouchEvents(destroy) { var passiveEvent = destroy ? removePassiveEventListener : addPassiveEventListener; var strOnOff = destroy ? 'off' : 'on'; var setupEvent = function(target, name, listener) { if(_supportPassiveEvents) passiveEvent(target, name, listener); else target[strOnOff](name, listener); }; if(_scrollbarsAutoHideMove && !destroy) setupEvent(_hostElement, _strMouseTouchMoveEvent, hostOnMouseMove); else { if(destroy) setupEvent(_hostElement, _strMouseTouchMoveEvent, hostOnMouseMove); setupEvent(_hostElement, _strMouseTouchEnter, hostOnMouseEnter); setupEvent(_hostElement, _strMouseTouchLeave, hostOnMouseLeave); } //if the plugin is initialized and the mouse is over the host element, make the scrollbars visible if(!_initialized && !destroy) _hostElement.one("mouseover", hostOnMouseEnter); } /** * Prevents text from deselection if attached to the document element on the mousedown event of a DOM element. * @param event The select start event. */ function documentOnSelectStart(event) { COMPATIBILITY.prvD(event); return false; } /** * A callback which will be called after a img element has downloaded its src asynchronous. */ function imgOnLoad() { update(false, true); } //==== Update Detection ====// /** * Measures the min width and min height of the body element and refreshes the related cache. * @returns {boolean} True if the min width or min height has changed, false otherwise. */ function bodyMinSizeChanged() { var bodyMinSize = {}; if (_isBody && _contentArrangeElement) { bodyMinSize.w = parseToZeroOrNumber(_contentArrangeElement.css(_strMinMinus + _strWidth)); bodyMinSize.h = parseToZeroOrNumber(_contentArrangeElement.css(_strMinMinus + _strHeight)); bodyMinSize.c = checkCacheDouble(bodyMinSize, _bodyMinSizeCache); bodyMinSize.f = true; //flag for "measured at least once" } _bodyMinSizeCache = bodyMinSize; return bodyMinSize.c || false; } /** * Returns true if the class names really changed (new class without plugin host prefix) * @param oldCassNames The old ClassName string. * @param newClassNames The new ClassName string. * @returns {boolean} True if the class names has really changed, false otherwise. */ function hostClassNamesChanged(oldCassNames, newClassNames) { var currClasses = (newClassNames !== undefined && newClassNames !== null) ? newClassNames.split(_strSpace) : _strEmpty; var oldClasses = (oldCassNames !== undefined && oldCassNames !== null) ? oldCassNames.split(_strSpace) : _strEmpty; if (currClasses === _strEmpty && oldClasses === _strEmpty) return false; var diff = getArrayDifferences(oldClasses, currClasses); var changed = false; var oldClassNames = _oldClassName !== undefined && _oldClassName !== null ? _oldClassName.split(_strSpace) : [_strEmpty]; var currClassNames = _classNameCache !== undefined && _classNameCache !== null ? _classNameCache.split(_strSpace) : [_strEmpty]; //remove none theme from diff list to prevent update var idx = FRAMEWORK.inArray(_classNameThemeNone, diff); var curr; var i; var v; var o; var c; if (idx > -1) diff.splice(idx, 1); for (i = 0; i < diff.length; i++) { curr = diff[i]; if (curr.indexOf(_classNameHostElement) !== 0) { o = true; c = true; for (v = 0; v < oldClassNames.length; v++) { if (curr === oldClassNames[v]) { o = false; break; } } for (v = 0; v < currClassNames.length; v++) { if (curr === currClassNames[v]) { c = false; break; } } if (o && c) { changed = true; break; } } } return changed; } /** * Returns true if the given mutation is not from a from the plugin generated element. If the target element is a textarea the mutation is always unknown. * @param mutation The mutation which shall be checked. * @returns {boolean} True if the mutation is from a unknown element, false otherwise. */ function isUnknownMutation(mutation) { var attributeName = mutation.attributeName; var mutationTarget = mutation.target; var mutationType = mutation.type; var strClosest = 'closest'; if (mutationTarget === _contentElementNative) return attributeName === null; if (mutationType === 'attributes' && (attributeName === LEXICON.c || attributeName === LEXICON.s) && !_isTextarea) { //ignore className changes by the plugin if (attributeName === LEXICON.c && FRAMEWORK(mutationTarget).hasClass(_classNameHostElement)) return hostClassNamesChanged(mutation.oldValue, mutationTarget.getAttribute(LEXICON.c)); //only do it of browser support it natively if (typeof mutationTarget[strClosest] != TYPES.f) return true; if (mutationTarget[strClosest](_strDot + _classNameResizeObserverElement) !== null || mutationTarget[strClosest](_strDot + _classNameScrollbar) !== null || mutationTarget[strClosest](_strDot + _classNameScrollbarCorner) !== null) return false; } return true; } /** * Returns true if the content size was changed since the last time this method was called. * @returns {boolean} True if the content size was changed, false otherwise. */ function updateAutoContentSizeChanged() { if (_isSleeping) return false; var float; var textareaValueLength = _isTextarea && _widthAutoCache && !_textareaAutoWrappingCache ? _targetElement.val().length : 0; var setCSS = !_mutationObserversConnected && _widthAutoCache && !_isTextarea; var viewportScrollSize = { }; var css = { }; var bodyMinSizeC; var changed; var viewportScrollSizeChanged; //fix for https://bugzilla.mozilla.org/show_bug.cgi?id=1439305, it only works with "clipAlways : true" //it can work with "clipAlways : false" too, but we had to set the overflow of the viewportElement to hidden every time before measuring if(_restrictedMeasuring) { viewportScrollSize = { x : _viewportElementNative[LEXICON.sW], y : _viewportElementNative[LEXICON.sH] } } if (setCSS) { float = _contentElement.css(_strFloat); css[_strFloat] = _isRTL ? _strRight : _strLeft; css[_strWidth] = _strAuto; _contentElement.css(css); } var contentElementScrollSize = { w: getContentMeasureElement()[LEXICON.sW] + textareaValueLength, h: getContentMeasureElement()[LEXICON.sH] + textareaValueLength }; if (setCSS) { css[_strFloat] = float; css[_strWidth] = _strHundredPercent; _contentElement.css(css); } bodyMinSizeC = bodyMinSizeChanged(); changed = checkCacheDouble(contentElementScrollSize, _contentElementScrollSizeChangeDetectedCache); viewportScrollSizeChanged = checkCacheDouble(viewportScrollSize, _viewportScrollSizeCache, _strX, _strY); _contentElementScrollSizeChangeDetectedCache = contentElementScrollSize; _viewportScrollSizeCache = viewportScrollSize; return changed || bodyMinSizeC || viewportScrollSizeChanged; } /** * Returns true if the host element attributes (id, class, style) was changed since the last time this method was called. * @returns {boolean} */ function meaningfulAttrsChanged() { if (_isSleeping || _mutationObserversConnected) return false; var hostElementId = _hostElement.attr(LEXICON.i) || _strEmpty; var hostElementIdChanged = checkCacheSingle(hostElementId, _updateAutoHostElementIdCache); var hostElementClass = _hostElement.attr(LEXICON.c) || _strEmpty; var hostElementClassChanged = checkCacheSingle(hostElementClass, _updateAutoHostElementClassCache); var hostElementStyle = _hostElement.attr(LEXICON.s) || _strEmpty; var hostElementStyleChanged = checkCacheSingle(hostElementStyle, _updateAutoHostElementStyleCache); var hostElementVisible = _hostElement.is(':visible') || _strEmpty; var hostElementVisibleChanged = checkCacheSingle(hostElementVisible, _updateAutoHostElementVisibleCache); var targetElementRows = _isTextarea ? (_targetElement.attr('rows') || _strEmpty) : _strEmpty; var targetElementRowsChanged = checkCacheSingle(targetElementRows, _updateAutoTargetElementRowsCache); var targetElementCols = _isTextarea ? (_targetElement.attr('cols') || _strEmpty) : _strEmpty; var targetElementColsChanged = checkCacheSingle(targetElementCols, _updateAutoTargetElementColsCache); var targetElementWrap = _isTextarea ? (_targetElement.attr('wrap') || _strEmpty) : _strEmpty; var targetElementWrapChanged = checkCacheSingle(targetElementWrap, _updateAutoTargetElementWrapCache); _updateAutoHostElementIdCache = hostElementId; if (hostElementClassChanged) hostElementClassChanged = hostClassNamesChanged(_updateAutoHostElementClassCache, hostElementClass); _updateAutoHostElementClassCache = hostElementClass; _updateAutoHostElementStyleCache = hostElementStyle; _updateAutoHostElementVisibleCache = hostElementVisible; _updateAutoTargetElementRowsCache = targetElementRows; _updateAutoTargetElementColsCache = targetElementCols; _updateAutoTargetElementWrapCache = targetElementWrap; return hostElementIdChanged || hostElementClassChanged || hostElementStyleChanged || hostElementVisibleChanged || targetElementRowsChanged || targetElementColsChanged || targetElementWrapChanged; } /** * Checks is a CSS Property of a child element is affecting the scroll size of the content. * @param propertyName The CSS property name. * @returns {boolean} True if the property is affecting the content scroll size, false otherwise. */ function isSizeAffectingCSSProperty(propertyName) { if (!_initialized) return true; var flexGrow = 'flex-grow'; var flexShrink = 'flex-shrink'; var flexBasis = 'flex-basis'; var affectingPropsX = [ _strWidth, _strMinMinus + _strWidth, _strMaxMinus + _strWidth, _strMarginMinus + _strLeft, _strMarginMinus + _strRight, _strLeft, _strRight, 'font-weight', 'word-spacing', flexGrow, flexShrink, flexBasis ]; var affectingPropsXContentBox = [ _strPaddingMinus + _strLeft, _strPaddingMinus + _strRight, _strBorderMinus + _strLeft + _strWidth, _strBorderMinus + _strRight + _strWidth ]; var affectingPropsY = [ _strHeight, _strMinMinus + _strHeight, _strMaxMinus + _strHeight, _strMarginMinus + _strTop, _strMarginMinus + _strBottom, _strTop, _strBottom, 'line-height', flexGrow, flexShrink, flexBasis ]; var affectingPropsYContentBox = [ _strPaddingMinus + _strTop, _strPaddingMinus + _strBottom, _strBorderMinus + _strTop + _strWidth, _strBorderMinus + _strBottom + _strWidth ]; var _strS = 's'; var _strVS = 'v-s'; var checkX = _overflowBehaviorCache.x === _strS || _overflowBehaviorCache.x === _strVS; var checkY = _overflowBehaviorCache.y === _strS || _overflowBehaviorCache.y === _strVS; var sizeIsAffected = false; var checkPropertyName = function (arr, name) { for (var i = 0; i < arr[LEXICON.l]; i++) { if (arr[i] === name) return true; } return false; }; if (checkY) { sizeIsAffected = checkPropertyName(affectingPropsY, propertyName); if (!sizeIsAffected && !_isBorderBox) sizeIsAffected = checkPropertyName(affectingPropsYContentBox, propertyName); } if (checkX && !sizeIsAffected) { sizeIsAffected = checkPropertyName(affectingPropsX, propertyName); if (!sizeIsAffected && !_isBorderBox) sizeIsAffected = checkPropertyName(affectingPropsXContentBox, propertyName); } return sizeIsAffected; } //==== Update ====// /** * Updates the variables and size of the textarea element, and manages the scroll on new line or new character. */ function textareaUpdate() { if (_isSleeping) return; var wrapAttrOff = !_textareaAutoWrappingCache; var minWidth = _viewportSize.w /* - (!_isBorderBox && !_paddingAbsoluteCache && _widthAutoCache ? _paddingY + _borderY : 0) */; var minHeight = _viewportSize.h /* - (!_isBorderBox && !_paddingAbsoluteCache && _heightAutoCache ? _paddingY + _borderY : 0) */; var css = { }; var doMeasure = _widthAutoCache || wrapAttrOff; var origWidth; var width; var origHeight; var height; //reset min size css[_strMinMinus + _strWidth] = _strEmpty; css[_strMinMinus + _strHeight] = _strEmpty; //set width auto css[_strWidth] = _strAuto; _targetElement.css(css); //measure width origWidth = _targetElementNative[LEXICON.oW]; width = doMeasure ? MATH.max(origWidth, _targetElementNative[LEXICON.sW] - 1) : 1; /*width += (_widthAutoCache ? _marginX + (!_isBorderBox ? wrapAttrOff ? 0 : _paddingX + _borderX : 0) : 0);*/ //set measured width css[_strWidth] = _widthAutoCache ? _strAuto /*width*/ : _strHundredPercent; css[_strMinMinus + _strWidth] = _strHundredPercent; //set height auto css[_strHeight] = _strAuto; _targetElement.css(css); //measure height origHeight = _targetElementNative[LEXICON.oH]; height = MATH.max(origHeight, _targetElementNative[LEXICON.sH] - 1); //append correct size values css[_strWidth] = width; css[_strHeight] = height; _textareaCoverElement.css(css); //apply min width / min height to prevent textarea collapsing css[_strMinMinus + _strWidth] = minWidth /*+ (!_isBorderBox && _widthAutoCache ? _paddingX + _borderX : 0)*/; css[_strMinMinus + _strHeight] = minHeight /*+ (!_isBorderBox && _heightAutoCache ? _paddingY + _borderY : 0)*/; _targetElement.css(css); return { _originalWidth: origWidth, _originalHeight: origHeight, _dynamicWidth: width, _dynamicHeight: height }; } /** * Updates the plugin and DOM to the current options. * This method should only be called if a update is 100% required. * @param hostSizeChanged True if this method was called due to a host size change. * @param contentSizeChanged True if this method was called due to a content size change. * @param force True if every property shall be updated and the cache shall be ignored. * @param preventSwallowing True if this method shall be executed even if it could be swallowed. */ function update(hostSizeChanged, contentSizeChanged, force, preventSwallowing) { var now = COMPATIBILITY.now(); var swallow = _swallowUpdateLag > 0 && _initialized && (now - _lastUpdateTime) < _swallowUpdateLag && (!_heightAutoCache && !_widthAutoCache) && !preventSwallowing; var displayIsHidden = _hostElement.is(':hidden'); var displayIsHiddenChanged = checkCacheSingle(displayIsHidden, _displayIsHiddenCache, force); _displayIsHiddenCache = displayIsHidden; clearTimeout(_swallowedUpdateTimeout); if (swallow) { _swallowedUpdateParams.h = _swallowedUpdateParams.h || hostSizeChanged; _swallowedUpdateParams.c = _swallowedUpdateParams.c || contentSizeChanged; _swallowedUpdateParams.f = _swallowedUpdateParams.f || force; _swallowedUpdateTimeout = setTimeout(update, _swallowUpdateLag); } //abort update due to: //destroyed //swallowing //sleeping //host is hidden or has false display if (_destroyed || swallow || _isSleeping || (_initialized && !force && displayIsHidden) || _hostElement.css('display') === 'inline') return; _lastUpdateTime = now; hostSizeChanged = hostSizeChanged || _swallowedUpdateParams.h; contentSizeChanged = contentSizeChanged || _swallowedUpdateParams.c; force = force || _swallowedUpdateParams.f; _swallowedUpdateParams = {}; hostSizeChanged = hostSizeChanged === undefined ? false : hostSizeChanged; contentSizeChanged = contentSizeChanged === undefined ? false : contentSizeChanged; force = force === undefined ? false : force; //if scrollbar styling is possible and native scrollbars aren't overlaid the scrollbar styling will be applied which hides the native scrollbars completely. if (_nativeScrollbarStyling && !(_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y)) { //native scrollbars are hidden, so change the values to zero _nativeScrollbarSize.x = 0; _nativeScrollbarSize.y = 0; } else { //refresh native scrollbar size (in case of zoom) _nativeScrollbarSize = extendDeep({}, globals.nativeScrollbarSize); } // Scrollbar padding is needed for firefox, because firefox hides scrollbar automatically if the size of the div is too small. // The calculation: [scrollbar size +3 *3] // (+3 because of possible decoration e.g. borders, margins etc., but only if native scrollbar is NOT a overlaid scrollbar) // (*3 because (1)increase / (2)decrease -button and (3)resize handle) _nativeScrollbarMinSize = { x: (_nativeScrollbarSize.x + (_nativeScrollbarIsOverlaid.x ? 0 : 3)) * 3, y: (_nativeScrollbarSize.y + (_nativeScrollbarIsOverlaid.y ? 0 : 3)) * 3 }; freezeResizeObserver(_sizeObserverElement); freezeResizeObserver(_sizeAutoObserverElement); //save current scroll offset var currScroll = { x: _viewportElement[_strScrollLeft](), y: _viewportElement[_strScrollTop]() }; var currentPreparedOptionsScrollbars = _currentPreparedOptions.scrollbars; var currentPreparedOptionsTextarea = _currentPreparedOptions.textarea; //scrollbars visibility: var scrollbarsVisibility = currentPreparedOptionsScrollbars.visibility; var scrollbarsVisibilityChanged = checkCacheSingle(scrollbarsVisibility, _scrollbarsVisibilityCache, force); //scrollbars autoHide: var scrollbarsAutoHide = currentPreparedOptionsScrollbars.autoHide; var scrollbarsAutoHideChanged = checkCacheSingle(scrollbarsAutoHide, _scrollbarsAutoHideCache, force); //scrollbars click scrolling var scrollbarsClickScrolling = currentPreparedOptionsScrollbars.clickScrolling; var scrollbarsClickScrollingChanged = checkCacheSingle(scrollbarsClickScrolling, _scrollbarsClickScrollingCache, force); //scrollbars drag scrolling var scrollbarsDragScrolling = currentPreparedOptionsScrollbars.dragScrolling; var scrollbarsDragScrollingChanged = checkCacheSingle(scrollbarsDragScrolling, _scrollbarsDragScrollingCache, force); //className var className = _currentPreparedOptions.className; var classNameChanged = checkCacheSingle(className, _classNameCache, force); //resize var resize = _currentPreparedOptions.resize; var resizeChanged = checkCacheSingle(resize, _resizeCache, force) && !_isBody; //body can't be resized since the window itself acts as resize possibility. //textarea AutoWrapping var textareaAutoWrapping = _isTextarea ? _targetElement.attr('wrap') !== 'off' : false; var textareaAutoWrappingChanged = checkCacheSingle(textareaAutoWrapping, _textareaAutoWrappingCache, force); //paddingAbsolute var paddingAbsolute = _currentPreparedOptions.paddingAbsolute; var paddingAbsoluteChanged = checkCacheSingle(paddingAbsolute, _paddingAbsoluteCache, force); //clipAlways var clipAlways = _currentPreparedOptions.clipAlways; var clipAlwaysChanged = checkCacheSingle(clipAlways, _clipAlwaysCache, force); //sizeAutoCapable var sizeAutoCapable = _currentPreparedOptions.sizeAutoCapable && !_isBody; //body can never be size auto, because it shall be always as big as the viewport. var sizeAutoCapableChanged = checkCacheSingle(sizeAutoCapable, _sizeAutoCapableCache, force); //showNativeScrollbars var ignoreOverlayScrollbarHiding = _currentPreparedOptions.nativeScrollbarsOverlaid.showNativeScrollbars; var ignoreOverlayScrollbarHidingChanged = checkCacheSingle(ignoreOverlayScrollbarHiding, _ignoreOverlayScrollbarHidingCache); //autoUpdate var autoUpdate = _currentPreparedOptions.autoUpdate; var autoUpdateChanged = checkCacheSingle(autoUpdate, _autoUpdateCache); //overflowBehavior var overflowBehavior = _currentPreparedOptions.overflowBehavior; var overflowBehaviorChanged = checkCacheDouble(overflowBehavior, _overflowBehaviorCache, _strX, _strY, force); //dynWidth: var textareaDynWidth = currentPreparedOptionsTextarea.dynWidth; var textareaDynWidthChanged = checkCacheSingle(_textareaDynWidthCache, textareaDynWidth); //dynHeight: var textareaDynHeight = currentPreparedOptionsTextarea.dynHeight; var textareaDynHeightChanged = checkCacheSingle(_textareaDynHeightCache, textareaDynHeight); //scrollbars visibility _scrollbarsAutoHideNever = scrollbarsAutoHide === 'n'; _scrollbarsAutoHideScroll = scrollbarsAutoHide === 's'; _scrollbarsAutoHideMove = scrollbarsAutoHide === 'm'; _scrollbarsAutoHideLeave = scrollbarsAutoHide === 'l'; //scrollbars autoHideDelay _scrollbarsAutoHideDelay = currentPreparedOptionsScrollbars.autoHideDelay; //old className _oldClassName = _classNameCache; //resize _resizeNone = resize === 'n'; _resizeBoth = resize === 'b'; _resizeHorizontal = resize === 'h'; _resizeVertical = resize === 'v'; //normalizeRTL _normalizeRTLCache = _currentPreparedOptions.normalizeRTL; //ignore overlay scrollbar hiding ignoreOverlayScrollbarHiding = ignoreOverlayScrollbarHiding && (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y); //refresh options cache _scrollbarsVisibilityCache = scrollbarsVisibility; _scrollbarsAutoHideCache = scrollbarsAutoHide; _scrollbarsClickScrollingCache = scrollbarsClickScrolling; _scrollbarsDragScrollingCache = scrollbarsDragScrolling; _classNameCache = className; _resizeCache = resize; _textareaAutoWrappingCache = textareaAutoWrapping; _paddingAbsoluteCache = paddingAbsolute; _clipAlwaysCache = clipAlways; _sizeAutoCapableCache = sizeAutoCapable; _ignoreOverlayScrollbarHidingCache = ignoreOverlayScrollbarHiding; _autoUpdateCache = autoUpdate; _overflowBehaviorCache = extendDeep({}, overflowBehavior); _textareaDynWidthCache = textareaDynWidth; _textareaDynHeightCache = textareaDynHeight; _hasOverflowCache = _hasOverflowCache || { x: false, y: false }; //set correct class name to the host element if (classNameChanged) { removeClass(_hostElement, _oldClassName + _strSpace + _classNameThemeNone); addClass(_hostElement, className !== undefined && className !== null && className.length > 0 ? className : _classNameThemeNone); } //set correct auto Update if (autoUpdateChanged) { if (autoUpdate === true) { disconnectMutationObservers(); autoUpdateLoop.add(_base); } else if (autoUpdate === null) { if (_autoUpdateRecommended) { disconnectMutationObservers(); autoUpdateLoop.add(_base); } else { autoUpdateLoop.remove(_base); connectMutationObservers(); } } else { autoUpdateLoop.remove(_base); connectMutationObservers(); } } //activate or deactivate size auto capability if (sizeAutoCapableChanged) { if (sizeAutoCapable) { if (!_contentGlueElement) { _contentGlueElement = FRAMEWORK(generateDiv(_classNameContentGlueElement)); _paddingElement.before(_contentGlueElement); } else { _contentGlueElement.show(); } if (_sizeAutoObserverAdded) { _sizeAutoObserverElement.show(); } else { _sizeAutoObserverElement = FRAMEWORK(generateDiv(_classNameSizeAutoObserverElement)); _sizeAutoObserverElementNative = _sizeAutoObserverElement[0]; _contentGlueElement.before(_sizeAutoObserverElement); var oldSize = {w: -1, h: -1}; addResizeObserver(_sizeAutoObserverElement, function () { var newSize = { w: _sizeAutoObserverElementNative[LEXICON.oW], h: _sizeAutoObserverElementNative[LEXICON.oH] }; if (checkCacheDouble(newSize, oldSize)) { if (_initialized && (_heightAutoCache && newSize.h > 0) || (_widthAutoCache && newSize.w > 0)) { update(); } else if (_initialized && (!_heightAutoCache && newSize.h === 0) || (!_widthAutoCache && newSize.w === 0)) { update(); } } oldSize = newSize; }); _sizeAutoObserverAdded = true; //fix heightAuto detector bug if height is fixed but contentHeight is 0. //the probability this bug will ever happen is very very low, thats why its ok if we use calc which isn't supported in IE8. if (_cssCalc !== null) _sizeAutoObserverElement.css(_strHeight, _cssCalc + '(100% + 1px)'); } } else { if (_sizeAutoObserverAdded) _sizeAutoObserverElement.hide(); if (_contentGlueElement) _contentGlueElement.hide(); } } //if force, update all resizeObservers too if (force) { _sizeObserverElement.find('*').trigger(_strScroll); if (_sizeAutoObserverAdded) _sizeAutoObserverElement.find('*').trigger(_strScroll); } //detect direction: var cssDirection = _hostElement.css('direction'); var cssDirectionChanged = checkCacheSingle(cssDirection, _cssDirectionCache, force); //detect box-sizing: var boxSizing = _hostElement.css('box-sizing'); var boxSizingChanged = checkCacheSingle(boxSizing, _cssBoxSizingCache, force); //detect padding: var padding = { c: force, t: parseToZeroOrNumber(_hostElement.css(_strPaddingMinus + _strTop)), r: parseToZeroOrNumber(_hostElement.css(_strPaddingMinus + _strRight)), b: parseToZeroOrNumber(_hostElement.css(_strPaddingMinus + _strBottom)), l: parseToZeroOrNumber(_hostElement.css(_strPaddingMinus + _strLeft)) }; //width + height auto detecting var: var sizeAutoObserverElementBCRect; //exception occurs in IE8 sometimes (unknown exception) try { sizeAutoObserverElementBCRect = _sizeAutoObserverAdded ? _sizeAutoObserverElementNative.getBoundingClientRect() : null; } catch (ex) { return; } _isRTL = cssDirection === 'rtl'; _isBorderBox = (boxSizing === 'border-box'); var isRTLLeft = _isRTL ? _strLeft : _strRight; var isRTLRight = _isRTL ? _strRight : _strLeft; //detect width auto: var widthAutoResizeDetection = false; var widthAutoObserverDetection = (_sizeAutoObserverAdded && (_hostElement.css(_strFloat) !== 'none' /*|| _isTextarea */)) ? (MATH.round(sizeAutoObserverElementBCRect.right - sizeAutoObserverElementBCRect.left) === 0) && (!paddingAbsolute ? (_hostElementNative[LEXICON.cW] - _paddingX) > 0 : true) : false; if (sizeAutoCapable && !widthAutoObserverDetection) { var tmpCurrHostWidth = _hostElementNative[LEXICON.oW]; var tmpCurrContentGlueWidth = _contentGlueElement.css(_strWidth); _contentGlueElement.css(_strWidth, _strAuto); var tmpNewHostWidth = _hostElementNative[LEXICON.oW]; _contentGlueElement.css(_strWidth, tmpCurrContentGlueWidth); widthAutoResizeDetection = tmpCurrHostWidth !== tmpNewHostWidth; if (!widthAutoResizeDetection) { _contentGlueElement.css(_strWidth, tmpCurrHostWidth + 1); tmpNewHostWidth = _hostElementNative[LEXICON.oW]; _contentGlueElement.css(_strWidth, tmpCurrContentGlueWidth); widthAutoResizeDetection = tmpCurrHostWidth !== tmpNewHostWidth; } } var widthAuto = (widthAutoObserverDetection || widthAutoResizeDetection) && sizeAutoCapable && !displayIsHidden; var widthAutoChanged = checkCacheSingle(widthAuto, _widthAutoCache, force); var wasWidthAuto = !widthAuto && _widthAutoCache; //detect height auto: var heightAuto = _sizeAutoObserverAdded && sizeAutoCapable && !displayIsHidden ? (MATH.round(sizeAutoObserverElementBCRect.bottom - sizeAutoObserverElementBCRect.top) === 0) /* && (!paddingAbsolute && (_msieVersion > 9 || !_msieVersion) ? true : true) */ : false; var heightAutoChanged = checkCacheSingle(heightAuto, _heightAutoCache, force); var wasHeightAuto = !heightAuto && _heightAutoCache; //detect border: //we need the border only if border box and auto size var strMinusWidth = '-' + _strWidth; var updateBorderX = (widthAuto && _isBorderBox) || !_isBorderBox; var updateBorderY = (heightAuto && _isBorderBox) || !_isBorderBox; var border = { c: force, t: updateBorderY ? parseToZeroOrNumber(_hostElement.css(_strBorderMinus + _strTop + strMinusWidth), true) : 0, r: updateBorderX ? parseToZeroOrNumber(_hostElement.css(_strBorderMinus + _strRight + strMinusWidth), true) : 0, b: updateBorderY ? parseToZeroOrNumber(_hostElement.css(_strBorderMinus + _strBottom + strMinusWidth), true) : 0, l: updateBorderX ? parseToZeroOrNumber(_hostElement.css(_strBorderMinus + _strLeft + strMinusWidth), true) : 0 }; //detect margin: var margin = { c: force, t: parseToZeroOrNumber(_hostElement.css(_strMarginMinus + _strTop)), r: parseToZeroOrNumber(_hostElement.css(_strMarginMinus + _strRight)), b: parseToZeroOrNumber(_hostElement.css(_strMarginMinus + _strBottom)), l: parseToZeroOrNumber(_hostElement.css(_strMarginMinus + _strLeft)) }; //detect css max width & height: var cssMaxValue = { h: String(_hostElement.css(_strMaxMinus + _strHeight)), w: String(_hostElement.css(_strMaxMinus + _strWidth)) }; //vars to apply correct css var contentElementCSS = { }; var contentGlueElementCSS = { }; //funcs var getHostSize = function() { //has to be clientSize because offsetSize respect borders return { w: _hostElementNative[LEXICON.cW], h: _hostElementNative[LEXICON.cH] }; }; var getViewportSize = function() { //viewport size is padding container because it never has padding, margin and a border //determine zoom rounding error -> sometimes scrollWidth/Height is smaller than clientWidth/Height //if this happens add the difference to the viewportSize to compensate the rounding error return { w: _paddingElementNative[LEXICON.oW] + MATH.max(0, _contentElementNative[LEXICON.cW] - _contentElementNative[LEXICON.sW]), h: _paddingElementNative[LEXICON.oH] + MATH.max(0, _contentElementNative[LEXICON.cH] - _contentElementNative[LEXICON.sH]) }; }; //set info for padding var paddingAbsoluteX = _paddingX = padding.l + padding.r; var paddingAbsoluteY = _paddingY = padding.t + padding.b; paddingAbsoluteX *= paddingAbsolute ? 1 : 0; paddingAbsoluteY *= paddingAbsolute ? 1 : 0; padding.c = checkCacheTRBL(padding, _cssPaddingCache); //set info for border _borderX = border.l + border.r; _borderY = border.t + border.b; border.c = checkCacheTRBL(border, _cssBorderCache); //set info for margin _marginX = margin.l + margin.r; _marginY = margin.t + margin.b; margin.c = checkCacheTRBL(margin, _cssMarginCache); //set info for css max value cssMaxValue.ih = parseToZeroOrNumber(cssMaxValue.h); //ih = integer height cssMaxValue.iw = parseToZeroOrNumber(cssMaxValue.w); //iw = integer width cssMaxValue.ch = cssMaxValue.h.indexOf('px') > -1; //ch = correct height cssMaxValue.cw = cssMaxValue.w.indexOf('px') > -1; //cw = correct width cssMaxValue.c = checkCacheDouble(cssMaxValue, _cssMaxValueCache, force); //refresh cache _cssDirectionCache = cssDirection; _cssBoxSizingCache = boxSizing; _widthAutoCache = widthAuto; _heightAutoCache = heightAuto; _cssPaddingCache = padding; _cssBorderCache = border; _cssMarginCache = margin; _cssMaxValueCache = cssMaxValue; //IEFix direction changed if (cssDirectionChanged && _sizeAutoObserverAdded) _sizeAutoObserverElement.css(_strFloat, isRTLRight); //apply padding: if (padding.c || cssDirectionChanged || paddingAbsoluteChanged || widthAutoChanged || heightAutoChanged || boxSizingChanged || sizeAutoCapableChanged) { var paddingElementCSS = {}; var textareaCSS = {}; setTopRightBottomLeft(contentGlueElementCSS, _strMarginMinus, [-padding.t, -padding.r, -padding.b, -padding.l]); if (paddingAbsolute) { setTopRightBottomLeft(paddingElementCSS, _strEmpty, [padding.t, padding.r, padding.b, padding.l]); if (_isTextarea) setTopRightBottomLeft(textareaCSS, _strPaddingMinus); else setTopRightBottomLeft(contentElementCSS, _strPaddingMinus); } else { setTopRightBottomLeft(paddingElementCSS, _strEmpty); if (_isTextarea) setTopRightBottomLeft(textareaCSS, _strPaddingMinus, [padding.t, padding.r, padding.b, padding.l]); else setTopRightBottomLeft(contentElementCSS, _strPaddingMinus, [padding.t, padding.r, padding.b, padding.l]); } _paddingElement.css(paddingElementCSS); _targetElement.css(textareaCSS); } //viewport size is padding container because it never has padding, margin and a border. _viewportSize = getViewportSize(); //update Textarea var textareaSize = _isTextarea ? textareaUpdate() : false; var textareaDynOrigSize = _isTextarea && textareaSize ? { w : textareaDynWidth ? textareaSize._dynamicWidth : textareaSize._originalWidth, h : textareaDynHeight ? textareaSize._dynamicHeight : textareaSize._originalHeight } : { }; //fix height auto / width auto in cooperation with current padding & boxSizing behavior: if (heightAuto && (heightAutoChanged || paddingAbsoluteChanged || boxSizingChanged || cssMaxValue.c || padding.c || border.c)) { //if (cssMaxValue.ch) contentElementCSS[_strMaxMinus + _strHeight] = (cssMaxValue.ch ? (cssMaxValue.ih - paddingAbsoluteY + (_isBorderBox ? -_borderY : _paddingY)) : _strEmpty); contentElementCSS[_strHeight] = _strAuto; } else if (heightAutoChanged || paddingAbsoluteChanged) { contentElementCSS[_strMaxMinus + _strHeight] = _strEmpty; contentElementCSS[_strHeight] = _strHundredPercent; } if (widthAuto && (widthAutoChanged || paddingAbsoluteChanged || boxSizingChanged || cssMaxValue.c || padding.c || border.c || cssDirectionChanged)) { //if (cssMaxValue.cw) contentElementCSS[_strMaxMinus + _strWidth] = (cssMaxValue.cw ? (cssMaxValue.iw - paddingAbsoluteX + (_isBorderBox ? -_borderX : _paddingX)) + (_nativeScrollbarIsOverlaid.y /*&& _hasOverflowCache.y && widthAuto */ ? _overlayScrollbarDummySize.y : 0) : _strEmpty); contentElementCSS[_strWidth] = _strAuto; contentGlueElementCSS[_strMaxMinus + _strWidth] = _strHundredPercent; //IE Fix } else if (widthAutoChanged || paddingAbsoluteChanged) { contentElementCSS[_strMaxMinus + _strWidth] = _strEmpty; contentElementCSS[_strWidth] = _strHundredPercent; contentElementCSS[_strFloat] = _strEmpty; contentGlueElementCSS[_strMaxMinus + _strWidth] = _strEmpty; //IE Fix } if (widthAuto) { if (!cssMaxValue.cw) contentElementCSS[_strMaxMinus + _strWidth] = _strEmpty; //textareaDynOrigSize.w || _strAuto :: doesnt works because applied margin will shift width contentGlueElementCSS[_strWidth] = _strAuto; contentElementCSS[_strWidth] = _strAuto; contentElementCSS[_strFloat] = isRTLRight; } else { contentGlueElementCSS[_strWidth] = _strEmpty; } if (heightAuto) { if (!cssMaxValue.ch) contentElementCSS[_strMaxMinus + _strHeight] = _strEmpty; //textareaDynOrigSize.h || _contentElementNative[LEXICON.cH] :: use for anti scroll jumping contentGlueElementCSS[_strHeight] = textareaDynOrigSize.h || _contentElementNative[LEXICON.cH]; } else { contentGlueElementCSS[_strHeight] = _strEmpty; } if (sizeAutoCapable) _contentGlueElement.css(contentGlueElementCSS); _contentElement.css(contentElementCSS); //CHECKPOINT HERE ~ contentElementCSS = {}; contentGlueElementCSS = {}; //if [content(host) client / scroll size, or target element direction, or content(host) max-sizes] changed, or force is true if (hostSizeChanged || contentSizeChanged || cssDirectionChanged || boxSizingChanged || paddingAbsoluteChanged || widthAutoChanged || widthAuto || heightAutoChanged || heightAuto || cssMaxValue.c || ignoreOverlayScrollbarHidingChanged || overflowBehaviorChanged || clipAlwaysChanged || resizeChanged || scrollbarsVisibilityChanged || scrollbarsAutoHideChanged || scrollbarsDragScrollingChanged || scrollbarsClickScrollingChanged || textareaDynWidthChanged || textareaDynHeightChanged || textareaAutoWrappingChanged || force) { var strOverflow = 'overflow'; var strOverflowX = strOverflow + '-x'; var strOverflowY = strOverflow + '-y'; var strHidden = 'hidden'; var strVisible = 'visible'; //decide whether the content overflow must get hidden for correct overflow measuring, it !MUST! be always hidden if the height is auto var hideOverflow4CorrectMeasuring = _restrictedMeasuring ? (_nativeScrollbarIsOverlaid.x || _nativeScrollbarIsOverlaid.y) || //it must be hidden if native scrollbars are overlaid (_viewportSize.w < _nativeScrollbarMinSize.y || _viewportSize.h < _nativeScrollbarMinSize.x) || //it must be hidden if host-element is too small heightAuto || displayIsHiddenChanged //it must be hidden if height is auto or display was change : heightAuto; //if there is not the restricted Measuring bug, it must be hidden if the height is auto //Reset the viewport (very important for natively overlaid scrollbars and zoom change //don't change the overflow prop as it is very expensive and affects performance !A LOT! var viewportElementResetCSS = { }; var resetXTmp = _hasOverflowCache.y && _hideOverflowCache.ys && !ignoreOverlayScrollbarHiding ? (_nativeScrollbarIsOverlaid.y ? _viewportElement.css(isRTLLeft) : -_nativeScrollbarSize.y) : 0; var resetBottomTmp = _hasOverflowCache.x && _hideOverflowCache.xs && !ignoreOverlayScrollbarHiding ? (_nativeScrollbarIsOverlaid.x ? _viewportElement.css(_strBottom) : -_nativeScrollbarSize.x) : 0; setTopRightBottomLeft(viewportElementResetCSS, _strEmpty); _viewportElement.css(viewportElementResetCSS); if(hideOverflow4CorrectMeasuring) _contentElement.css(strOverflow, strHidden); //measure several sizes: var contentMeasureElement = getContentMeasureElement(); //in Firefox content element has to have overflow hidden, else element margins aren't calculated properly, this element prevents this bug, but only if scrollbars aren't overlaid var contentMeasureElementGuaranty = _restrictedMeasuring && !hideOverflow4CorrectMeasuring ? _viewportElementNative : contentMeasureElement; var contentSize = { //use clientSize because natively overlaidScrollbars add borders w: textareaDynOrigSize.w || contentMeasureElement[LEXICON.cW], h: textareaDynOrigSize.h || contentMeasureElement[LEXICON.cH] }; var scrollSize = { w: MATH.max(contentMeasureElement[LEXICON.sW], contentMeasureElementGuaranty[LEXICON.sW]), h: MATH.max(contentMeasureElement[LEXICON.sH], contentMeasureElementGuaranty[LEXICON.sH]) }; //apply the correct viewport style and measure viewport size viewportElementResetCSS[_strBottom] = wasHeightAuto ? _strEmpty : resetBottomTmp; viewportElementResetCSS[isRTLLeft] = wasWidthAuto ? _strEmpty : resetXTmp; _viewportElement.css(viewportElementResetCSS); _viewportSize = getViewportSize(); //measure and correct several sizes var hostSize = getHostSize(); var contentGlueSize = { //client/scrollSize + AbsolutePadding -> because padding is only applied to the paddingElement if its absolute, so you have to add it manually //hostSize is clientSize -> so padding should be added manually, right? FALSE! Because content glue is inside hostElement, so we don't have to worry about padding w: MATH.max((widthAuto ? contentSize.w : scrollSize.w) + paddingAbsoluteX, hostSize.w), h: MATH.max((heightAuto ? contentSize.h : scrollSize.h) + paddingAbsoluteY, hostSize.h) }; contentGlueSize.c = checkCacheDouble(contentGlueSize, _contentGlueSizeCache, force); _contentGlueSizeCache = contentGlueSize; //apply correct contentGlue size if (sizeAutoCapable) { //size contentGlue correctly to make sure the element has correct size if the sizing switches to auto if (contentGlueSize.c || (heightAuto || widthAuto)) { contentGlueElementCSS[_strWidth] = contentGlueSize.w; contentGlueElementCSS[_strHeight] = contentGlueSize.h; //textarea-sizes are already calculated correctly at this point if(!_isTextarea) { contentSize = { //use clientSize because natively overlaidScrollbars add borders w: contentMeasureElement[LEXICON.cW], h: contentMeasureElement[LEXICON.cH] }; } } var textareaCoverCSS = {}; var setContentGlueElementCSSfunction = function(horizontal) { var scrollbarVars = getScrollbarVars(horizontal); var wh = scrollbarVars._w_h; var strWH = scrollbarVars._width_height; var autoSize = horizontal ? widthAuto : heightAuto; var borderSize = horizontal ? _borderX : _borderY; var paddingSize = horizontal ? _paddingX : _paddingY; var marginSize = horizontal ? _marginX : _marginY; var maxSize = contentGlueElementCSS[strWH] + (_isBorderBox ? borderSize : -paddingSize); //make contentGlue size -1 if element is not auto sized, to make sure that a resize event happens when the element shrinks if (!autoSize || (!autoSize && border.c)) contentGlueElementCSS[strWH] = hostSize[wh] - (_isBorderBox ? 0 : paddingSize + borderSize) - 1 - marginSize; //if size is auto and host is same size as max size, make content glue size +1 to make sure size changes will be detected if (autoSize && cssMaxValue['c' + wh] && cssMaxValue['i' + wh] === maxSize) contentGlueElementCSS[strWH] = maxSize + (_isBorderBox ? 0 : paddingSize) + 1; //if size is auto and host is smaller than size as min size, make content glue size -1 to make sure size changes will be detected (this is only needed if padding is 0) if (autoSize && (contentSize[wh] < _viewportSize[wh]) && (horizontal ? (_isTextarea ? !textareaAutoWrapping : false) : true)) { if (_isTextarea) textareaCoverCSS[strWH] = parseToZeroOrNumber(_textareaCoverElement.css(strWH)) - 1; contentGlueElementCSS[strWH] -= 1; } //make sure content glue size is at least 1 if (contentSize[wh] > 0) contentGlueElementCSS[strWH] = MATH.max(1, contentGlueElementCSS[strWH]); }; setContentGlueElementCSSfunction(true); setContentGlueElementCSSfunction(false); if (_isTextarea) _textareaCoverElement.css(textareaCoverCSS); _contentGlueElement.css(contentGlueElementCSS); } if (widthAuto) contentElementCSS[_strWidth] = _strHundredPercent; if (widthAuto && !_isBorderBox && !_mutationObserversConnected) contentElementCSS[_strFloat] = 'none'; //apply and reset content style _contentElement.css(contentElementCSS); contentElementCSS = {}; //measure again, but this time all correct sizes: var contentScrollSize = { w: MATH.max(contentMeasureElement[LEXICON.sW], contentMeasureElementGuaranty[LEXICON.sW]), h: MATH.max(contentMeasureElement[LEXICON.sH], contentMeasureElementGuaranty[LEXICON.sH]) }; contentScrollSize.c = contentSizeChanged = checkCacheDouble(contentScrollSize, _contentScrollSizeCache, force); _contentScrollSizeCache = contentScrollSize; //remove overflow hidden to restore overflow if(hideOverflow4CorrectMeasuring) _contentElement.css(strOverflow, _strEmpty); //refresh viewport size after correct measuring _viewportSize = getViewportSize(); hostSize = getHostSize(); hostSizeChanged = checkCacheDouble(hostSize, _hostSizeCache); _hostSizeCache = hostSize; var hideOverflowForceTextarea = _isTextarea && (_viewportSize.w === 0 || _viewportSize.h === 0); var previousOverflow = _overflowAmountCache; var overflowBehaviorIsVS = { }; var overflowBehaviorIsVH = { }; var overflowBehaviorIsS = { }; var overflowAmount = { }; var hasOverflow = { }; var hideOverflow = { }; var canScroll = { }; var viewportRect = _paddingElementNative.getBoundingClientRect(); var setOverflowVariables = function(horizontal) { var scrollbarVars = getScrollbarVars(horizontal); var scrollbarVarsInverted = getScrollbarVars(!horizontal); var xyI = scrollbarVarsInverted._x_y; var xy = scrollbarVars._x_y; var wh = scrollbarVars._w_h; var widthHeight = scrollbarVars._width_height; var scrollMax = _strScroll + scrollbarVars._Left_Top + 'Max'; var fractionalOverflowAmount = viewportRect[widthHeight] ? MATH.abs(viewportRect[widthHeight] - _viewportSize[wh]) : 0; overflowBehaviorIsVS[xy] = overflowBehavior[xy] === 'v-s'; overflowBehaviorIsVH[xy] = overflowBehavior[xy] === 'v-h'; overflowBehaviorIsS[xy] = overflowBehavior[xy] === 's'; overflowAmount[xy] = MATH.max(0, MATH.round((contentScrollSize[wh] - _viewportSize[wh]) * 100) / 100); overflowAmount[xy] *= (hideOverflowForceTextarea || (_viewportElementNative[scrollMax] === 0 && fractionalOverflowAmount > 0 && fractionalOverflowAmount < 1)) ? 0 : 1; hasOverflow[xy] = overflowAmount[xy] > 0; //hideOverflow: //x || y : true === overflow is hidden by "overflow: scroll" OR "overflow: hidden" //xs || ys : true === overflow is hidden by "overflow: scroll" hideOverflow[xy] = overflowBehaviorIsVS[xy] || overflowBehaviorIsVH[xy] ? (hasOverflow[xyI] && !overflowBehaviorIsVS[xyI] && !overflowBehaviorIsVH[xyI]) : hasOverflow[xy]; hideOverflow[xy + 's'] = hideOverflow[xy] ? (overflowBehaviorIsS[xy] || overflowBehaviorIsVS[xy]) : false; canScroll[xy] = hasOverflow[xy] && hideOverflow[xy + 's']; }; setOverflowVariables(true); setOverflowVariables(false); overflowAmount.c = checkCacheDouble(overflowAmount, _overflowAmountCache, _strX, _strY, force); _overflowAmountCache = overflowAmount; hasOverflow.c = checkCacheDouble(hasOverflow, _hasOverflowCache, _strX, _strY, force); _hasOverflowCache = hasOverflow; hideOverflow.c = checkCacheDouble(hideOverflow, _hideOverflowCache, _strX, _strY, force); _hideOverflowCache = hideOverflow; //if native scrollbar is overlay at x OR y axis, prepare DOM if (_nativeScrollbarIsOverlaid.x || _nativeScrollbarIsOverlaid.y) { var borderDesign = 'px solid transparent'; var contentArrangeElementCSS = { }; var arrangeContent = { }; var arrangeChanged = force; var setContentElementCSS; if (hasOverflow.x || hasOverflow.y) { arrangeContent.w = _nativeScrollbarIsOverlaid.y && hasOverflow.y ? contentScrollSize.w + _overlayScrollbarDummySize.y : _strEmpty; arrangeContent.h = _nativeScrollbarIsOverlaid.x && hasOverflow.x ? contentScrollSize.h + _overlayScrollbarDummySize.x : _strEmpty; arrangeChanged = checkCacheSingle(arrangeContent, _arrangeContentSizeCache, force); _arrangeContentSizeCache = arrangeContent; } if (hasOverflow.c || hideOverflow.c || contentScrollSize.c || cssDirectionChanged || widthAutoChanged || heightAutoChanged || widthAuto || heightAuto || ignoreOverlayScrollbarHidingChanged) { contentElementCSS[_strMarginMinus + isRTLRight] = contentElementCSS[_strBorderMinus + isRTLRight] = _strEmpty; setContentElementCSS = function(horizontal) { var scrollbarVars = getScrollbarVars(horizontal); var scrollbarVarsInverted = getScrollbarVars(!horizontal); var xy = scrollbarVars._x_y; var strDirection = horizontal ? _strBottom : isRTLLeft; var invertedAutoSize = horizontal ? heightAuto : widthAuto; if (_nativeScrollbarIsOverlaid[xy] && hasOverflow[xy] && hideOverflow[xy + 's']) { contentElementCSS[_strMarginMinus + strDirection] = invertedAutoSize ? (ignoreOverlayScrollbarHiding ? _strEmpty : _overlayScrollbarDummySize[xy]) : _strEmpty; contentElementCSS[_strBorderMinus + strDirection] = ((horizontal ? !invertedAutoSize : true) && !ignoreOverlayScrollbarHiding) ? (_overlayScrollbarDummySize[xy] + borderDesign) : _strEmpty; } else { arrangeContent[scrollbarVarsInverted._w_h] = contentElementCSS[_strMarginMinus + strDirection] = contentElementCSS[_strBorderMinus + strDirection] = _strEmpty; arrangeChanged = true; } }; if (_nativeScrollbarStyling) { if (ignoreOverlayScrollbarHiding) removeClass(_viewportElement, _classNameViewportNativeScrollbarsInvisible); else addClass(_viewportElement, _classNameViewportNativeScrollbarsInvisible); } else { setContentElementCSS(true); setContentElementCSS(false); } } if (ignoreOverlayScrollbarHiding) { arrangeContent.w = arrangeContent.h = _strEmpty; arrangeChanged = true; } if (arrangeChanged && !_nativeScrollbarStyling) { contentArrangeElementCSS[_strWidth] = hideOverflow.y ? arrangeContent.w : _strEmpty; contentArrangeElementCSS[_strHeight] = hideOverflow.x ? arrangeContent.h : _strEmpty; if (!_contentArrangeElement) { _contentArrangeElement = FRAMEWORK(generateDiv(_classNameContentArrangeElement)); _viewportElement.prepend(_contentArrangeElement); } _contentArrangeElement.css(contentArrangeElementCSS); } _contentElement.css(contentElementCSS); } var viewportElementCSS = {}; var paddingElementCSS = {}; var setViewportCSS; if (hostSizeChanged || hasOverflow.c || hideOverflow.c || contentScrollSize.c || overflowBehaviorChanged || boxSizingChanged || ignoreOverlayScrollbarHidingChanged || cssDirectionChanged || clipAlwaysChanged || heightAutoChanged) { viewportElementCSS[isRTLRight] = _strEmpty; setViewportCSS = function(horizontal) { var scrollbarVars = getScrollbarVars(horizontal); var scrollbarVarsInverted = getScrollbarVars(!horizontal); var xy = scrollbarVars._x_y; var XY = scrollbarVars._X_Y; var strDirection = horizontal ? _strBottom : isRTLLeft; var reset = function () { viewportElementCSS[strDirection] = _strEmpty; _contentBorderSize[scrollbarVarsInverted._w_h] = 0; }; if (hasOverflow[xy] && hideOverflow[xy + 's']) { viewportElementCSS[strOverflow + XY] = _strScroll; if (ignoreOverlayScrollbarHiding || _nativeScrollbarStyling) { reset(); } else { viewportElementCSS[strDirection] = -(_nativeScrollbarIsOverlaid[xy] ? _overlayScrollbarDummySize[xy] : _nativeScrollbarSize[xy]); _contentBorderSize[scrollbarVarsInverted._w_h] = _nativeScrollbarIsOverlaid[xy] ? _overlayScrollbarDummySize[scrollbarVarsInverted._x_y] : 0; } } else { viewportElementCSS[strOverflow + XY] = _strEmpty; reset(); } }; setViewportCSS(true); setViewportCSS(false); // if the scroll container is too small and if there is any overflow with no overlay scrollbar (and scrollbar styling isn't possible), // make viewport element greater in size (Firefox hide Scrollbars fix) // because firefox starts hiding scrollbars on too small elements // with this behavior the overflow calculation may be incorrect or the scrollbars would appear suddenly // https://bugzilla.mozilla.org/show_bug.cgi?id=292284 if (!_nativeScrollbarStyling && (_viewportSize.h < _nativeScrollbarMinSize.x || _viewportSize.w < _nativeScrollbarMinSize.y) && ((hasOverflow.x && hideOverflow.x && !_nativeScrollbarIsOverlaid.x) || (hasOverflow.y && hideOverflow.y && !_nativeScrollbarIsOverlaid.y))) { viewportElementCSS[_strPaddingMinus + _strTop] = _nativeScrollbarMinSize.x; viewportElementCSS[_strMarginMinus + _strTop] = -_nativeScrollbarMinSize.x; viewportElementCSS[_strPaddingMinus + isRTLRight] = _nativeScrollbarMinSize.y; viewportElementCSS[_strMarginMinus + isRTLRight] = -_nativeScrollbarMinSize.y; } else { viewportElementCSS[_strPaddingMinus + _strTop] = viewportElementCSS[_strMarginMinus + _strTop] = viewportElementCSS[_strPaddingMinus + isRTLRight] = viewportElementCSS[_strMarginMinus + isRTLRight] = _strEmpty; } viewportElementCSS[_strPaddingMinus + isRTLLeft] = viewportElementCSS[_strMarginMinus + isRTLLeft] = _strEmpty; //if there is any overflow (x OR y axis) and this overflow shall be hidden, make overflow hidden, else overflow visible if ((hasOverflow.x && hideOverflow.x) || (hasOverflow.y && hideOverflow.y) || hideOverflowForceTextarea) { //only hide if is Textarea if (_isTextarea && hideOverflowForceTextarea) { paddingElementCSS[strOverflowX] = paddingElementCSS[strOverflowY] = strHidden; } } else { if (!clipAlways || (overflowBehaviorIsVH.x || overflowBehaviorIsVS.x || overflowBehaviorIsVH.y || overflowBehaviorIsVS.y)) { //only un-hide if Textarea if (_isTextarea) { paddingElementCSS[strOverflowX] = paddingElementCSS[strOverflowY] = _strEmpty; } viewportElementCSS[strOverflowX] = viewportElementCSS[strOverflowY] = strVisible; } } _paddingElement.css(paddingElementCSS); _viewportElement.css(viewportElementCSS); viewportElementCSS = { }; //force soft redraw in webkit because without the scrollbars will may appear because DOM wont be redrawn under special conditions if ((hasOverflow.c || boxSizingChanged || widthAutoChanged || heightAutoChanged) && !(_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y)) { var elementStyle = _contentElementNative[LEXICON.s]; var dump; elementStyle.webkitTransform = 'scale(1)'; elementStyle.display = 'run-in'; dump = _contentElementNative[LEXICON.oH]; elementStyle.display = _strEmpty; //|| dump; //use dump to prevent it from deletion if minify elementStyle.webkitTransform = _strEmpty; } /* //force hard redraw in webkit if native overlaid scrollbars shall appear if (ignoreOverlayScrollbarHidingChanged && ignoreOverlayScrollbarHiding) { _hostElement.hide(); var dump = _hostElementNative[LEXICON.oH]; _hostElement.show(); } */ } //change to direction RTL and width auto Bugfix in Webkit //without this fix, the DOM still thinks the scrollbar is LTR and thus the content is shifted to the left contentElementCSS = {}; if (cssDirectionChanged || widthAutoChanged || heightAutoChanged) { if (_isRTL && widthAuto) { var floatTmp = _contentElement.css(_strFloat); var posLeftWithoutFloat = MATH.round(_contentElement.css(_strFloat, _strEmpty).css(_strLeft, _strEmpty).position().left); _contentElement.css(_strFloat, floatTmp); var posLeftWithFloat = MATH.round(_contentElement.position().left); if (posLeftWithoutFloat !== posLeftWithFloat) contentElementCSS[_strLeft] = posLeftWithoutFloat; } else { contentElementCSS[_strLeft] = _strEmpty; } } _contentElement.css(contentElementCSS); //handle scroll position if (_isTextarea && contentSizeChanged) { var textareaInfo = getTextareaInfo(); if (textareaInfo) { var textareaRowsChanged = _textareaInfoCache === undefined ? true : textareaInfo._rows !== _textareaInfoCache._rows; var cursorRow = textareaInfo._cursorRow; var cursorCol = textareaInfo._cursorColumn; var widestRow = textareaInfo._widestRow; var lastRow = textareaInfo._rows; var lastCol = textareaInfo._columns; var cursorPos = textareaInfo._cursorPosition; var cursorMax = textareaInfo._cursorMax; var cursorIsLastPosition = (cursorPos >= cursorMax && _textareaHasFocus); var textareaScrollAmount = { x: (!textareaAutoWrapping && (cursorCol === lastCol && cursorRow === widestRow)) ? _overflowAmountCache.x : -1, y: (textareaAutoWrapping ? cursorIsLastPosition || textareaRowsChanged && (previousOverflow !== undefined ? (currScroll.y === previousOverflow.y) : false) : (cursorIsLastPosition || textareaRowsChanged) && cursorRow === lastRow) ? _overflowAmountCache.y : -1 }; currScroll.x = textareaScrollAmount.x > -1 ? (_isRTL && _normalizeRTLCache && _rtlScrollBehavior.i ? 0 : textareaScrollAmount.x) : currScroll.x; //if inverted, scroll to 0 -> normalized this means to max scroll offset. currScroll.y = textareaScrollAmount.y > -1 ? textareaScrollAmount.y : currScroll.y; } _textareaInfoCache = textareaInfo; } if (_isRTL && _rtlScrollBehavior.i && _nativeScrollbarIsOverlaid.y && hasOverflow.x && _normalizeRTLCache) currScroll.x += _contentBorderSize.w || 0; if(widthAuto) _hostElement[_strScrollLeft](0); if(heightAuto) _hostElement[_strScrollTop](0); _viewportElement[_strScrollLeft](currScroll.x)[_strScrollTop](currScroll.y); //scrollbars management: var scrollbarsVisibilityVisible = scrollbarsVisibility === 'v'; var scrollbarsVisibilityHidden = scrollbarsVisibility === 'h'; var scrollbarsVisibilityAuto = scrollbarsVisibility === 'a'; var showScrollbarH = COMPATIBILITY.bind(refreshScrollbarAppearance, 0, true, true, canScroll.x); var showScrollbarV = COMPATIBILITY.bind(refreshScrollbarAppearance, 0, false, true, canScroll.y); var hideScrollbarH = COMPATIBILITY.bind(refreshScrollbarAppearance, 0, true, false, canScroll.x); var hideScrollbarV = COMPATIBILITY.bind(refreshScrollbarAppearance, 0, false, false, canScroll.y); //manage class name which indicates scrollable overflow if (hideOverflow.x || hideOverflow.y) addClass(_hostElement, _classNameHostOverflow); else removeClass(_hostElement, _classNameHostOverflow); if (hideOverflow.x) addClass(_hostElement, _classNameHostOverflowX); else removeClass(_hostElement, _classNameHostOverflowX); if (hideOverflow.y) addClass(_hostElement, _classNameHostOverflowY); else removeClass(_hostElement, _classNameHostOverflowY); //add or remove rtl class name for styling purposes if (cssDirectionChanged) { if (_isRTL) addClass(_hostElement, _classNameHostRTL); else removeClass(_hostElement, _classNameHostRTL); } //manage the resize feature (CSS3 resize "polyfill" for this plugin) if (_isBody) addClass(_hostElement, _classNameHostResizeDisabled); if (resizeChanged) { var addCornerEvents = function () { _scrollbarCornerElement.on(_strMouseTouchDownEvent, _resizeOnMouseTouchDown); }; var removeCornerEvents = function () { _scrollbarCornerElement.off(_strMouseTouchDownEvent, _resizeOnMouseTouchDown); }; removeClass(_scrollbarCornerElement, [ _classNameHostResizeDisabled, _classNameScrollbarCornerResize, _classNameScrollbarCornerResizeB, _classNameScrollbarCornerResizeH, _classNameScrollbarCornerResizeV].join(_strSpace)); if (_resizeNone) { addClass(_hostElement, _classNameHostResizeDisabled); removeCornerEvents(); } else { addClass(_scrollbarCornerElement, _classNameScrollbarCornerResize); if (_resizeBoth) addClass(_scrollbarCornerElement, _classNameScrollbarCornerResizeB); else if (_resizeHorizontal) addClass(_scrollbarCornerElement, _classNameScrollbarCornerResizeH); else if (_resizeVertical) addClass(_scrollbarCornerElement, _classNameScrollbarCornerResizeV); removeCornerEvents(); addCornerEvents(); } } //manage the scrollbars general visibility + the scrollbar interactivity (unusable class name) if (scrollbarsVisibilityChanged || overflowBehaviorChanged || hideOverflow.c || hasOverflow.c || ignoreOverlayScrollbarHidingChanged) { if (ignoreOverlayScrollbarHiding) { if (ignoreOverlayScrollbarHidingChanged) { removeClass(_hostElement, _classNameHostScrolling); if (ignoreOverlayScrollbarHiding) { hideScrollbarH(); hideScrollbarV(); } } } else if (scrollbarsVisibilityAuto) { if (canScroll.x) showScrollbarH(); else hideScrollbarH(); if (canScroll.y) showScrollbarV(); else hideScrollbarV(); } else if (scrollbarsVisibilityVisible) { showScrollbarH(); showScrollbarV(); } else if (scrollbarsVisibilityHidden) { hideScrollbarH(); hideScrollbarV(); } } //manage the scrollbars auto hide feature (auto hide them after specific actions) if (scrollbarsAutoHideChanged || ignoreOverlayScrollbarHidingChanged) { if (_scrollbarsAutoHideLeave || _scrollbarsAutoHideMove) { setupHostMouseTouchEvents(true); setupHostMouseTouchEvents(); } else { setupHostMouseTouchEvents(true); } if (_scrollbarsAutoHideNever) refreshScrollbarsAutoHide(true); else refreshScrollbarsAutoHide(false, true); } //manage scrollbars handle length & offset - don't remove! if (hostSizeChanged || overflowAmount.c || heightAutoChanged || widthAutoChanged || resizeChanged || boxSizingChanged || paddingAbsoluteChanged || ignoreOverlayScrollbarHidingChanged || cssDirectionChanged) { refreshScrollbarHandleLength(true); refreshScrollbarHandleOffset(true); refreshScrollbarHandleLength(false); refreshScrollbarHandleOffset(false); } //manage interactivity if (scrollbarsClickScrollingChanged) refreshScrollbarsInteractive(true, scrollbarsClickScrolling); if (scrollbarsDragScrollingChanged) refreshScrollbarsInteractive(false, scrollbarsDragScrolling); //callbacks: if (cssDirectionChanged) { dispatchCallback("onDirectionChanged", { isRTL: _isRTL, dir: cssDirection }); } if (hostSizeChanged) { dispatchCallback("onHostSizeChanged", { width: _hostSizeCache.w, height: _hostSizeCache.h }); } if (contentSizeChanged) { dispatchCallback("onContentSizeChanged", { width: _contentScrollSizeCache.w, height: _contentScrollSizeCache.h }); } if (hasOverflow.c || hideOverflow.c) { dispatchCallback("onOverflowChanged", { x: hasOverflow.x, y: hasOverflow.y, xScrollable: hideOverflow.xs, yScrollable: hideOverflow.ys, clipped: hideOverflow.x || hideOverflow.y }); } if (overflowAmount.c) { dispatchCallback("onOverflowAmountChanged", { x: overflowAmount.x, y: overflowAmount.y }); } } //fix body min size if (_isBody && (_hasOverflowCache.c || _bodyMinSizeCache.c)) { //its possible that no min size was measured until now, because the content arrange element was just added now, in this case, measure now the min size. if (!_bodyMinSizeCache.f) bodyMinSizeChanged(); if (_nativeScrollbarIsOverlaid.y && _hasOverflowCache.x) _contentElement.css(_strMinMinus + _strWidth, _bodyMinSizeCache.w + _overlayScrollbarDummySize.y); if (_nativeScrollbarIsOverlaid.x && _hasOverflowCache.y) _contentElement.css(_strMinMinus + _strHeight, _bodyMinSizeCache.h + _overlayScrollbarDummySize.x); _bodyMinSizeCache.c = false; } unfreezeResizeObserver(_sizeObserverElement); unfreezeResizeObserver(_sizeAutoObserverElement); dispatchCallback("onUpdated", { forced: force }); } //==== Options ====// /** * Sets new options but doesn't call the update method. * @param newOptions The object which contains the new options. */ function setOptions(newOptions) { _currentOptions = extendDeep({}, _currentOptions, _pluginsOptions._validate(newOptions, _pluginsOptions._template, true)); _currentPreparedOptions = extendDeep({}, _currentPreparedOptions, _pluginsOptions._validate(newOptions, _pluginsOptions._template, false, true)); } //==== Structure ====// /** * Builds or destroys the wrapper and helper DOM elements. * @param destroy Indicates whether the DOM shall be build or destroyed. */ function setupStructureDOM(destroy) { var adoptAttrs = _currentPreparedOptions.textarea.inheritedAttrs; var adoptAttrsMap = { }; var applyAdoptedAttrs = function() { var applyAdoptedAttrsElm = destroy ? _targetElement : _hostElement; FRAMEWORK.each(adoptAttrsMap, function(k, v) { if(type(v) == TYPES.s) { if(k == LEXICON.c) applyAdoptedAttrsElm.addClass(v); else applyAdoptedAttrsElm.attr(k, v); } }); }; var hostElementClassNames = [ _classNameHostElement, _classNameHostTextareaElement, _classNameHostResizeDisabled, _classNameHostRTL, _classNameHostScrollbarHorizontalHidden, _classNameHostScrollbarVerticalHidden, _classNameHostTransition, _classNameHostScrolling, _classNameHostOverflow, _classNameHostOverflowX, _classNameHostOverflowY, _classNameThemeNone, _classNameTextareaElement, _classNameTextInherit, _classNameCache].join(_strSpace); adoptAttrs = type(adoptAttrs) == TYPES.s ? adoptAttrs.split(' ') : adoptAttrs; if(type(adoptAttrs) == TYPES.a) { FRAMEWORK.each(adoptAttrs, function(i, v) { if(type(v) == TYPES.s) adoptAttrsMap[v] = destroy ? _hostElement.attr(v) : _targetElement.attr(v); }); } if(!destroy) { if (_isTextarea) { var hostElementCSS = {}; var parent = _targetElement.parent(); _isTextareaHostGenerated = !(parent.hasClass(_classNameHostTextareaElement) && parent.children()[LEXICON.l] === 1); if (!_currentPreparedOptions.sizeAutoCapable) { hostElementCSS[_strWidth] = _targetElement.css(_strWidth); hostElementCSS[_strHeight] = _targetElement.css(_strHeight); } if(_isTextareaHostGenerated) _targetElement.wrap(generateDiv(_classNameHostTextareaElement)); _hostElement = _targetElement.parent(); _hostElement.css(hostElementCSS) .wrapInner(generateDiv(_classNameContentElement + _strSpace + _classNameTextInherit)) .wrapInner(generateDiv(_classNameViewportElement + _strSpace + _classNameTextInherit)) .wrapInner(generateDiv(_classNamePaddingElement + _strSpace + _classNameTextInherit)); _contentElement = findFirst(_hostElement, _strDot + _classNameContentElement); _viewportElement = findFirst(_hostElement, _strDot + _classNameViewportElement); _paddingElement = findFirst(_hostElement, _strDot + _classNamePaddingElement); _textareaCoverElement = FRAMEWORK(generateDiv(_classNameTextareaCoverElement)); _contentElement.prepend(_textareaCoverElement); addClass(_targetElement, _classNameTextareaElement + _strSpace + _classNameTextInherit); if(_isTextareaHostGenerated) applyAdoptedAttrs(); } else { _hostElement = _targetElement; _hostElement.wrapInner(generateDiv(_classNameContentElement)) .wrapInner(generateDiv(_classNameViewportElement)) .wrapInner(generateDiv(_classNamePaddingElement)); _contentElement = findFirst(_hostElement, _strDot + _classNameContentElement); _viewportElement = findFirst(_hostElement, _strDot + _classNameViewportElement); _paddingElement = findFirst(_hostElement, _strDot + _classNamePaddingElement); addClass(_targetElement, _classNameHostElement); } if (_nativeScrollbarStyling) addClass(_viewportElement, _classNameViewportNativeScrollbarsInvisible); if(_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y) addClass(_viewportElement, _classNameViewportNativeScrollbarsOverlaid); if (_isBody) addClass(_htmlElement, _classNameHTMLElement); _sizeObserverElement = FRAMEWORK(generateDiv('os-resize-observer-host')); _hostElement.prepend(_sizeObserverElement); _sizeObserverElementNative = _sizeObserverElement[0]; _hostElementNative = _hostElement[0]; _paddingElementNative = _paddingElement[0]; _viewportElementNative = _viewportElement[0]; _contentElementNative = _contentElement[0]; } else { _contentElement.contents() .unwrap() .unwrap() .unwrap(); removeClass(_hostElement, hostElementClassNames); if (_isTextarea) { _targetElement.removeAttr(LEXICON.s); if(_isTextareaHostGenerated) applyAdoptedAttrs(); removeClass(_targetElement, hostElementClassNames); remove(_textareaCoverElement); if(_isTextareaHostGenerated) { _targetElement.unwrap(); remove(_hostElement); } else { addClass(_hostElement, _classNameHostTextareaElement); } } else { removeClass(_targetElement, _classNameHostElement); } if (_isBody) removeClass(_htmlElement, _classNameHTMLElement); remove(_sizeObserverElement); } } /** * Adds or removes all wrapper elements interactivity events. * @param destroy Indicates whether the Events shall be added or removed. */ function setupStructureEvents(destroy) { var textareaKeyDownRestrictedKeyCodes = [ 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 123, //F1 to F12 33, 34, //page up, page down 37, 38, 39, 40, //left, up, right, down arrows 16, 17, 18, 19, 20, 144 //Shift, Ctrl, Alt, Pause, CapsLock, NumLock ]; var textareaKeyDownKeyCodesList = [ ]; var textareaUpdateIntervalID; var scrollStopDelay = 175; var scrollStopTimeoutId; var strOnOff = destroy ? 'off' : 'on'; var updateTextarea; var viewportOnScroll; if(!destroy && _isTextarea) { _textareaEvents = { }; updateTextarea = function(doClearInterval) { textareaUpdate(); _base.update(_strAuto); if(doClearInterval) clearInterval(textareaUpdateIntervalID); }; _textareaEvents[_strScroll] = function(event) { _targetElement[_strScrollLeft](_rtlScrollBehavior.i && _normalizeRTLCache ? 9999999 : 0); _targetElement[_strScrollTop](0); COMPATIBILITY.prvD(event); COMPATIBILITY.stpP(event); return false; }; _textareaEvents['drop'] = function() { setTimeout(function () { if(!_destroyed) updateTextarea(); }, 50); }; _textareaEvents['focus'] = function() { _textareaHasFocus = true; }; _textareaEvents['focusout'] = function() { _textareaHasFocus = false; textareaKeyDownKeyCodesList = [ ]; updateTextarea(true); }; if (_msieVersion > 9 || !_autoUpdateRecommended) { _textareaEvents['input'] = function textareaOnInput() { updateTextarea(); } } else { _textareaEvents[_strKeyDownEvent] = function textareaOnKeyDown(event) { var keyCode = event.keyCode; if (FRAMEWORK.inArray(keyCode, textareaKeyDownRestrictedKeyCodes) > -1) return; if (!textareaKeyDownKeyCodesList.length) { updateTextarea(); textareaUpdateIntervalID = setInterval(updateTextarea, 1000 / 60); } if (FRAMEWORK.inArray(keyCode, textareaKeyDownKeyCodesList) === -1) textareaKeyDownKeyCodesList.push(keyCode); }; _textareaEvents[_strKeyUpEvent] = function(event) { var keyCode = event.keyCode; var index = FRAMEWORK.inArray(keyCode, textareaKeyDownKeyCodesList); if (FRAMEWORK.inArray(keyCode, textareaKeyDownRestrictedKeyCodes) > -1) return; if (index > -1) textareaKeyDownKeyCodesList.splice(index, 1); if (!textareaKeyDownKeyCodesList.length) updateTextarea(true); }; } } if (_isTextarea) { FRAMEWORK.each(_textareaEvents, function(key, value) { _targetElement[strOnOff](key, value); }); } else { _contentElement[strOnOff](_strTransitionEndEvent, function (event) { if (_autoUpdateCache === true) return; event = event.originalEvent || event; if (isSizeAffectingCSSProperty(event.propertyName)) update(_strAuto); }); } if(!destroy) { viewportOnScroll = function(event) { if (_isSleeping) return; if (scrollStopTimeoutId !== undefined) clearTimeout(scrollStopTimeoutId); else { if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(true); if (!nativeOverlayScrollbarsAreActive()) addClass(_hostElement, _classNameHostScrolling); dispatchCallback("onScrollStart", event); } //if a scrollbars handle gets dragged, the mousemove event is responsible for refreshing the handle offset //because if CSS scroll-snap is used, the handle offset gets only refreshed on every snap point //this looks laggy & clunky, it looks much better if the offset refreshes with the mousemove if(!_scrollbarsHandleAsync) { refreshScrollbarHandleOffset(true); refreshScrollbarHandleOffset(false); } dispatchCallback("onScroll", event); scrollStopTimeoutId = setTimeout(function () { if(!_destroyed) { //OnScrollStop: clearTimeout(scrollStopTimeoutId); scrollStopTimeoutId = undefined; if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(false); if (!nativeOverlayScrollbarsAreActive()) removeClass(_hostElement, _classNameHostScrolling); dispatchCallback("onScrollStop", event); } }, scrollStopDelay); }; if (_supportPassiveEvents) addPassiveEventListener(_viewportElement, _strScroll, viewportOnScroll); else _viewportElement.on(_strScroll, viewportOnScroll); } } //==== Scrollbars ====// /** * Builds or destroys all scrollbar DOM elements (scrollbar, track, handle) * @param destroy Indicates whether the DOM shall be build or destroyed. */ function setupScrollbarsDOM(destroy) { if(!destroy) { _scrollbarHorizontalElement = FRAMEWORK(generateDiv(_classNameScrollbar + _strSpace + _classNameScrollbarHorizontal)); _scrollbarHorizontalTrackElement = FRAMEWORK(generateDiv(_classNameScrollbarTrack)); _scrollbarHorizontalHandleElement = FRAMEWORK(generateDiv(_classNameScrollbarHandle)); _scrollbarVerticalElement = FRAMEWORK(generateDiv(_classNameScrollbar + _strSpace + _classNameScrollbarVertical)); _scrollbarVerticalTrackElement = FRAMEWORK(generateDiv(_classNameScrollbarTrack)); _scrollbarVerticalHandleElement = FRAMEWORK(generateDiv(_classNameScrollbarHandle)); _scrollbarHorizontalElement.append(_scrollbarHorizontalTrackElement); _scrollbarHorizontalTrackElement.append(_scrollbarHorizontalHandleElement); _scrollbarVerticalElement.append(_scrollbarVerticalTrackElement); _scrollbarVerticalTrackElement.append(_scrollbarVerticalHandleElement); _paddingElement.after(_scrollbarVerticalElement); _paddingElement.after(_scrollbarHorizontalElement); } else { remove(_scrollbarHorizontalElement); remove(_scrollbarVerticalElement); } } /** * Initializes all scrollbar interactivity events. (track and handle dragging, clicking, scrolling) * @param isHorizontal True if the target scrollbar is the horizontal scrollbar, false if the target scrollbar is the vertical scrollbar. */ function setupScrollbarEvents(isHorizontal) { var scrollbarVars = getScrollbarVars(isHorizontal); var scrollbarVarsInfo = scrollbarVars._info; var insideIFrame = _windowElementNative.top !== _windowElementNative; var xy = scrollbarVars._x_y; var XY = scrollbarVars._X_Y; var scroll = _strScroll + scrollbarVars._Left_Top; var strActive = 'active'; var strSnapHandle = 'snapHandle'; var scrollDurationFactor = 1; var increaseDecreaseScrollAmountKeyCodes = [ 16, 17 ]; //shift, ctrl var trackTimeout; var mouseDownScroll; var mouseDownOffset; var mouseDownInvertedScale; function getPointerPosition(event) { return _msieVersion && insideIFrame ? event['screen' + XY] : COMPATIBILITY.page(event)[xy]; //use screen coordinates in EDGE & IE because the page values are incorrect in frames. } function getPreparedScrollbarsOption(name) { return _currentPreparedOptions.scrollbars[name]; } function increaseTrackScrollAmount() { scrollDurationFactor = 0.5; } function decreaseTrackScrollAmount() { scrollDurationFactor = 1; } function documentKeyDown(event) { if (FRAMEWORK.inArray(event.keyCode, increaseDecreaseScrollAmountKeyCodes) > -1) increaseTrackScrollAmount(); } function documentKeyUp(event) { if (FRAMEWORK.inArray(event.keyCode, increaseDecreaseScrollAmountKeyCodes) > -1) decreaseTrackScrollAmount(); } function onMouseTouchDownContinue(event) { var originalEvent = event.originalEvent || event; var isTouchEvent = originalEvent.touches !== undefined; return _isSleeping || _destroyed || nativeOverlayScrollbarsAreActive() || !_scrollbarsDragScrollingCache || (isTouchEvent && !getPreparedScrollbarsOption('touchSupport')) ? false : COMPATIBILITY.mBtn(event) === 1 || isTouchEvent; } function documentDragMove(event) { if(onMouseTouchDownContinue(event)) { var trackLength = scrollbarVarsInfo._trackLength; var handleLength = scrollbarVarsInfo._handleLength; var scrollRange = scrollbarVarsInfo._maxScroll; var scrollRaw = (getPointerPosition(event) - mouseDownOffset) * mouseDownInvertedScale; var scrollDeltaPercent = scrollRaw / (trackLength - handleLength); var scrollDelta = (scrollRange * scrollDeltaPercent); scrollDelta = isFinite(scrollDelta) ? scrollDelta : 0; if (_isRTL && isHorizontal && !_rtlScrollBehavior.i) scrollDelta *= -1; _viewportElement[scroll](MATH.round(mouseDownScroll + scrollDelta)); if(_scrollbarsHandleAsync) refreshScrollbarHandleOffset(isHorizontal, mouseDownScroll + scrollDelta); if (!_supportPassiveEvents) COMPATIBILITY.prvD(event); } else documentMouseTouchUp(event); } function documentMouseTouchUp(event) { event = event || event.originalEvent; _documentElement.off(_strMouseTouchMoveEvent, documentDragMove) .off(_strMouseTouchUpEvent, documentMouseTouchUp) .off(_strKeyDownEvent, documentKeyDown) .off(_strKeyUpEvent, documentKeyUp) .off(_strSelectStartEvent, documentOnSelectStart); if(_scrollbarsHandleAsync) refreshScrollbarHandleOffset(isHorizontal, true); _scrollbarsHandleAsync = false; removeClass(_bodyElement, _classNameDragging); removeClass(scrollbarVars._handle, strActive); removeClass(scrollbarVars._track, strActive); removeClass(scrollbarVars._scrollbar, strActive); mouseDownScroll = undefined; mouseDownOffset = undefined; mouseDownInvertedScale = 1; decreaseTrackScrollAmount(); if (trackTimeout !== undefined) { _base.scrollStop(); clearTimeout(trackTimeout); trackTimeout = undefined; } if(event) { var rect = _hostElementNative.getBoundingClientRect(); var mouseInsideHost = event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom; //if mouse is outside host element if (!mouseInsideHost) hostOnMouseLeave(); if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(false); } } function onHandleMouseTouchDown(event) { mouseDownScroll = _viewportElement[scroll](); mouseDownScroll = isNaN(mouseDownScroll) ? 0 : mouseDownScroll; if (_isRTL && isHorizontal && !_rtlScrollBehavior.n || !_isRTL) mouseDownScroll = mouseDownScroll < 0 ? 0 : mouseDownScroll; mouseDownInvertedScale = getHostElementInvertedScale()[xy]; mouseDownOffset = getPointerPosition(event); _scrollbarsHandleAsync = !getPreparedScrollbarsOption(strSnapHandle); addClass(_bodyElement, _classNameDragging); addClass(scrollbarVars._handle, strActive); addClass(scrollbarVars._scrollbar, strActive); _documentElement.on(_strMouseTouchMoveEvent, documentDragMove) .on(_strMouseTouchUpEvent, documentMouseTouchUp) .on(_strSelectStartEvent, documentOnSelectStart); if(_msieVersion || !_documentMixed) COMPATIBILITY.prvD(event); COMPATIBILITY.stpP(event); } scrollbarVars._handle.on(_strMouseTouchDownEvent, function(event) { if (onMouseTouchDownContinue(event)) onHandleMouseTouchDown(event); }); scrollbarVars._track.on(_strMouseTouchDownEvent, function(event) { if (onMouseTouchDownContinue(event)) { var scrollDistance = MATH.round(_viewportSize[scrollbarVars._w_h]); var trackOffset = scrollbarVars._track.offset()[scrollbarVars._left_top]; var ctrlKey = event.ctrlKey; var instantScroll = event.shiftKey; var instantScrollTransition = instantScroll && ctrlKey; var isFirstIteration = true; var easing = 'linear'; var decreaseScroll; var finishedCondition; var scrollActionFinsished = function(transition) { if(_scrollbarsHandleAsync) refreshScrollbarHandleOffset(isHorizontal, transition); }; var scrollActionInstantFinished = function() { scrollActionFinsished(); onHandleMouseTouchDown(event); }; var scrollAction = function () { if(!_destroyed) { var mouseOffset = (mouseDownOffset - trackOffset) * mouseDownInvertedScale; var handleOffset = scrollbarVarsInfo._handleOffset; var trackLength = scrollbarVarsInfo._trackLength; var handleLength = scrollbarVarsInfo._handleLength; var scrollRange = scrollbarVarsInfo._maxScroll; var currScroll = scrollbarVarsInfo._currentScroll; var scrollDuration = 270 * scrollDurationFactor; var timeoutDelay = isFirstIteration ? MATH.max(400, scrollDuration) : scrollDuration; var instantScrollPosition = scrollRange * ((mouseOffset - (handleLength / 2)) / (trackLength - handleLength)); // 100% * positionPercent var rtlIsNormal = _isRTL && isHorizontal && ((!_rtlScrollBehavior.i && !_rtlScrollBehavior.n) || _normalizeRTLCache); var decreaseScrollCondition = rtlIsNormal ? handleOffset < mouseOffset : handleOffset > mouseOffset; var scrollObj = { }; var animationObj = { easing : easing, step : function(now) { if(_scrollbarsHandleAsync) { _viewportElement[scroll](now); //https://github.com/jquery/jquery/issues/4340 refreshScrollbarHandleOffset(isHorizontal, now); } } }; instantScrollPosition = isFinite(instantScrollPosition) ? instantScrollPosition : 0; instantScrollPosition = _isRTL && isHorizontal && !_rtlScrollBehavior.i ? (scrollRange - instantScrollPosition) : instantScrollPosition; //_base.scrollStop(); if(instantScroll) { _viewportElement[scroll](instantScrollPosition); //scroll instantly to new position if(instantScrollTransition) { //get the scroll position after instant scroll (in case CSS Snap Points are used) to get the correct snapped scroll position //and the animation stops at the correct point instantScrollPosition = _viewportElement[scroll](); //scroll back to the position before instant scrolling so animation can be performed _viewportElement[scroll](currScroll); instantScrollPosition = rtlIsNormal && _rtlScrollBehavior.i ? (scrollRange - instantScrollPosition) : instantScrollPosition; instantScrollPosition = rtlIsNormal && _rtlScrollBehavior.n ? -instantScrollPosition : instantScrollPosition; scrollObj[xy] = instantScrollPosition; _base.scroll(scrollObj, extendDeep(animationObj, { duration : 130, complete : scrollActionInstantFinished })); } else scrollActionInstantFinished(); } else { decreaseScroll = isFirstIteration ? decreaseScrollCondition : decreaseScroll; finishedCondition = rtlIsNormal ? (decreaseScroll ? handleOffset + handleLength >= mouseOffset : handleOffset <= mouseOffset) : (decreaseScroll ? handleOffset <= mouseOffset : handleOffset + handleLength >= mouseOffset); if (finishedCondition) { clearTimeout(trackTimeout); _base.scrollStop(); trackTimeout = undefined; scrollActionFinsished(true); } else { trackTimeout = setTimeout(scrollAction, timeoutDelay); scrollObj[xy] = (decreaseScroll ? '-=' : '+=') + scrollDistance; _base.scroll(scrollObj, extendDeep(animationObj, { duration: scrollDuration })); } isFirstIteration = false; } } }; if (ctrlKey) increaseTrackScrollAmount(); mouseDownInvertedScale = getHostElementInvertedScale()[xy]; mouseDownOffset = COMPATIBILITY.page(event)[xy]; _scrollbarsHandleAsync = !getPreparedScrollbarsOption(strSnapHandle); addClass(_bodyElement, _classNameDragging); addClass(scrollbarVars._track, strActive); addClass(scrollbarVars._scrollbar, strActive); _documentElement.on(_strMouseTouchUpEvent, documentMouseTouchUp) .on(_strKeyDownEvent, documentKeyDown) .on(_strKeyUpEvent, documentKeyUp) .on(_strSelectStartEvent, documentOnSelectStart); scrollAction(); COMPATIBILITY.prvD(event); COMPATIBILITY.stpP(event); } }).on(_strMouseTouchEnter, function() { //make sure both scrollbars will stay visible if one scrollbar is hovered if autoHide is "scroll" or "move". _scrollbarsHandleHovered = true; if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(true); }).on(_strMouseTouchLeave, function() { _scrollbarsHandleHovered = false; if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(false); }); scrollbarVars._scrollbar.on(_strMouseTouchDownEvent, function(event) { COMPATIBILITY.stpP(event); }); if (_supportTransition) { scrollbarVars._scrollbar.on(_strTransitionEndEvent, function(event) { if (event.target !== scrollbarVars._scrollbar[0]) return; refreshScrollbarHandleLength(isHorizontal); refreshScrollbarHandleOffset(isHorizontal); }); } } /** * Shows or hides the given scrollbar and applied a class name which indicates if the scrollbar is scrollable or not. * @param isHorizontal True if the horizontal scrollbar is the target, false if the vertical scrollbar is the target. * @param shallBeVisible True if the scrollbar shall be shown, false if hidden. * @param canScroll True if the scrollbar is scrollable, false otherwise. */ function refreshScrollbarAppearance(isHorizontal, shallBeVisible, canScroll) { var scrollbarClassName = isHorizontal ? _classNameHostScrollbarHorizontalHidden : _classNameHostScrollbarVerticalHidden; var scrollbarElement = isHorizontal ? _scrollbarHorizontalElement : _scrollbarVerticalElement; if (shallBeVisible) removeClass(_hostElement, scrollbarClassName); else addClass(_hostElement, scrollbarClassName); if (canScroll) removeClass(scrollbarElement, _classNameScrollbarUnusable); else addClass(scrollbarElement, _classNameScrollbarUnusable); } /** * Autoshows / autohides both scrollbars with. * @param shallBeVisible True if the scrollbars shall be autoshown (only the case if they are hidden by a autohide), false if the shall be auto hidden. * @param delayfree True if the scrollbars shall be hidden without a delay, false or undefined otherwise. */ function refreshScrollbarsAutoHide(shallBeVisible, delayfree) { clearTimeout(_scrollbarsAutoHideTimeoutId); if (shallBeVisible) { //if(_hasOverflowCache.x && _hideOverflowCache.xs) removeClass(_scrollbarHorizontalElement, _classNameScrollbarAutoHidden); //if(_hasOverflowCache.y && _hideOverflowCache.ys) removeClass(_scrollbarVerticalElement, _classNameScrollbarAutoHidden); } else { var anyActive; var strActive = 'active'; var hide = function () { if (!_scrollbarsHandleHovered && !_destroyed) { anyActive = _scrollbarHorizontalHandleElement.hasClass(strActive) || _scrollbarVerticalHandleElement.hasClass(strActive); if (!anyActive && (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove || _scrollbarsAutoHideLeave)) addClass(_scrollbarHorizontalElement, _classNameScrollbarAutoHidden); if (!anyActive && (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove || _scrollbarsAutoHideLeave)) addClass(_scrollbarVerticalElement, _classNameScrollbarAutoHidden); } }; if (_scrollbarsAutoHideDelay > 0 && delayfree !== true) _scrollbarsAutoHideTimeoutId = setTimeout(hide, _scrollbarsAutoHideDelay); else hide(); } } /** * Refreshes the handle length of the given scrollbar. * @param isHorizontal True if the horizontal scrollbar handle shall be refreshed, false if the vertical one shall be refreshed. */ function refreshScrollbarHandleLength(isHorizontal) { var handleCSS = {}; var scrollbarVars = getScrollbarVars(isHorizontal); var scrollbarVarsInfo = scrollbarVars._info; var digit = 1000000; //get and apply intended handle length var handleRatio = MATH.min(1, (_hostSizeCache[scrollbarVars._w_h] - (_paddingAbsoluteCache ? (isHorizontal ? _paddingX : _paddingY) : 0)) / _contentScrollSizeCache[scrollbarVars._w_h]); handleCSS[scrollbarVars._width_height] = (MATH.floor(handleRatio * 100 * digit) / digit) + "%"; //the last * digit / digit is for flooring to the 4th digit if (!nativeOverlayScrollbarsAreActive()) scrollbarVars._handle.css(handleCSS); //measure the handle length to respect min & max length scrollbarVarsInfo._handleLength = scrollbarVars._handle[0]['offset' + scrollbarVars._Width_Height]; scrollbarVarsInfo._handleLengthRatio = handleRatio; } /** * Refreshes the handle offset of the given scrollbar. * @param isHorizontal True if the horizontal scrollbar handle shall be refreshed, false if the vertical one shall be refreshed. * @param scrollOrTransition The scroll position of the given scrollbar axis to which the handle shall be moved or a boolean which indicates whether a transition shall be applied. If undefined or boolean if the current scroll-offset is taken. (if isHorizontal ? scrollLeft : scrollTop) */ function refreshScrollbarHandleOffset(isHorizontal, scrollOrTransition) { var transition = type(scrollOrTransition) == TYPES.b; var transitionDuration = 250; var isRTLisHorizontal = _isRTL && isHorizontal; var scrollbarVars = getScrollbarVars(isHorizontal); var scrollbarVarsInfo = scrollbarVars._info; var strTranslateBrace = 'translate('; var strTransform = VENDORS._cssProperty('transform'); var strTransition = VENDORS._cssProperty('transition'); var nativeScroll = isHorizontal ? _viewportElement[_strScrollLeft]() : _viewportElement[_strScrollTop](); var currentScroll = scrollOrTransition === undefined || transition ? nativeScroll : scrollOrTransition; //measure the handle length to respect min & max length var handleLength = scrollbarVarsInfo._handleLength; var trackLength = scrollbarVars._track[0]['offset' + scrollbarVars._Width_Height]; var handleTrackDiff = trackLength - handleLength; var handleCSS = {}; var transformOffset; var translateValue; //DONT use the variable '_contentScrollSizeCache[scrollbarVars._w_h]' instead of '_viewportElement[0]['scroll' + scrollbarVars._Width_Height]' // because its a bit behind during the small delay when content size updates //(delay = mutationObserverContentLag, if its 0 then this var could be used) var maxScroll = (_viewportElementNative[_strScroll + scrollbarVars._Width_Height] - _viewportElementNative['client' + scrollbarVars._Width_Height]) * (_rtlScrollBehavior.n && isRTLisHorizontal ? -1 : 1); //* -1 if rtl scroll max is negative var getScrollRatio = function(base) { return isNaN(base / maxScroll) ? 0 : MATH.max(0, MATH.min(1, base / maxScroll)); }; var getHandleOffset = function(scrollRatio) { var offset = handleTrackDiff * scrollRatio; offset = isNaN(offset) ? 0 : offset; offset = (isRTLisHorizontal && !_rtlScrollBehavior.i) ? (trackLength - handleLength - offset) : offset; offset = MATH.max(0, offset); return offset; }; var scrollRatio = getScrollRatio(nativeScroll); var unsnappedScrollRatio = getScrollRatio(currentScroll); var handleOffset = getHandleOffset(unsnappedScrollRatio); var snappedHandleOffset = getHandleOffset(scrollRatio); scrollbarVarsInfo._maxScroll = maxScroll; scrollbarVarsInfo._currentScroll = nativeScroll; scrollbarVarsInfo._currentScrollRatio = scrollRatio; if (_supportTransform) { transformOffset = isRTLisHorizontal ? -(trackLength - handleLength - handleOffset) : handleOffset; //in px //transformOffset = (transformOffset / trackLength * 100) * (trackLength / handleLength); //in % translateValue = isHorizontal ? strTranslateBrace + transformOffset + 'px, 0)' : strTranslateBrace + '0, ' + transformOffset + 'px)'; handleCSS[strTransform] = translateValue; //apply or clear up transition if(_supportTransition) handleCSS[strTransition] = transition && MATH.abs(handleOffset - scrollbarVarsInfo._handleOffset) > 1 ? getCSSTransitionString(scrollbarVars._handle) + ', ' + (strTransform + _strSpace + transitionDuration + 'ms') : _strEmpty; } else handleCSS[scrollbarVars._left_top] = handleOffset; //only apply css if offset has changed and overflow exists. if (!nativeOverlayScrollbarsAreActive()) { scrollbarVars._handle.css(handleCSS); //clear up transition if(_supportTransform && _supportTransition && transition) { scrollbarVars._handle.one(_strTransitionEndEvent, function() { if(!_destroyed) scrollbarVars._handle.css(strTransition, _strEmpty); }); } } scrollbarVarsInfo._handleOffset = handleOffset; scrollbarVarsInfo._snappedHandleOffset = snappedHandleOffset; scrollbarVarsInfo._trackLength = trackLength; } /** * Refreshes the interactivity of the given scrollbar element. * @param isTrack True if the track element is the target, false if the handle element is the target. * @param value True for interactivity false for no interactivity. */ function refreshScrollbarsInteractive(isTrack, value) { var action = value ? 'removeClass' : 'addClass'; var element1 = isTrack ? _scrollbarHorizontalTrackElement : _scrollbarHorizontalHandleElement; var element2 = isTrack ? _scrollbarVerticalTrackElement : _scrollbarVerticalHandleElement; var className = isTrack ? _classNameScrollbarTrackOff : _classNameScrollbarHandleOff; element1[action](className); element2[action](className); } /** * Returns a object which is used for fast access for specific variables. * @param isHorizontal True if the horizontal scrollbar vars shall be accessed, false if the vertical scrollbar vars shall be accessed. * @returns {{wh: string, WH: string, lt: string, _wh: string, _lt: string, t: *, h: *, c: {}, s: *}} */ function getScrollbarVars(isHorizontal) { return { _width_height: isHorizontal ? _strWidth : _strHeight, _Width_Height: isHorizontal ? 'Width' : 'Height', _left_top: isHorizontal ? _strLeft : _strTop, _Left_Top: isHorizontal ? 'Left' : 'Top', _x_y: isHorizontal ? _strX : _strY, _X_Y: isHorizontal ? 'X' : 'Y', _w_h: isHorizontal ? 'w' : 'h', _l_t: isHorizontal ? 'l' : 't', _track: isHorizontal ? _scrollbarHorizontalTrackElement : _scrollbarVerticalTrackElement, _handle: isHorizontal ? _scrollbarHorizontalHandleElement : _scrollbarVerticalHandleElement, _scrollbar: isHorizontal ? _scrollbarHorizontalElement : _scrollbarVerticalElement, _info: isHorizontal ? _scrollHorizontalInfo : _scrollVerticalInfo }; } //==== Scrollbar Corner ====// /** * Builds or destroys the scrollbar corner DOM element. * @param destroy Indicates whether the DOM shall be build or destroyed. */ function setupScrollbarCornerDOM(destroy) { if(!destroy) { _scrollbarCornerElement = FRAMEWORK(generateDiv(_classNameScrollbarCorner)); _hostElement.append(_scrollbarCornerElement); } else { remove(_scrollbarCornerElement); } } /** * Initializes all scrollbar corner interactivity events. */ function setupScrollbarCornerEvents() { var insideIFrame = _windowElementNative.top !== _windowElementNative; var mouseDownPosition = { }; var mouseDownSize = { }; var mouseDownInvertedScale = { }; _resizeOnMouseTouchDown = function(event) { if (onMouseTouchDownContinue(event)) { if (_mutationObserversConnected) { _resizeReconnectMutationObserver = true; disconnectMutationObservers(); } mouseDownPosition = getCoordinates(event); mouseDownSize.w = _hostElementNative[LEXICON.oW] - (!_isBorderBox ? _paddingX : 0); mouseDownSize.h = _hostElementNative[LEXICON.oH] - (!_isBorderBox ? _paddingY : 0); mouseDownInvertedScale = getHostElementInvertedScale(); _documentElement.on(_strSelectStartEvent, documentOnSelectStart) .on(_strMouseTouchMoveEvent, documentDragMove) .on(_strMouseTouchUpEvent, documentMouseTouchUp); addClass(_bodyElement, _classNameDragging); if (_scrollbarCornerElement.setCapture) _scrollbarCornerElement.setCapture(); COMPATIBILITY.prvD(event); COMPATIBILITY.stpP(event); } }; function documentDragMove(event) { if (onMouseTouchDownContinue(event)) { var pageOffset = getCoordinates(event); var hostElementCSS = { }; if (_resizeHorizontal || _resizeBoth) hostElementCSS[_strWidth] = (mouseDownSize.w + (pageOffset.x - mouseDownPosition.x) * mouseDownInvertedScale.x); if (_resizeVertical || _resizeBoth) hostElementCSS[_strHeight] = (mouseDownSize.h + (pageOffset.y - mouseDownPosition.y) * mouseDownInvertedScale.y); _hostElement.css(hostElementCSS); COMPATIBILITY.stpP(event); } else { documentMouseTouchUp(event); } } function documentMouseTouchUp(event) { var eventIsTrusted = event !== undefined; _documentElement.off(_strSelectStartEvent, documentOnSelectStart) .off(_strMouseTouchMoveEvent, documentDragMove) .off(_strMouseTouchUpEvent, documentMouseTouchUp); removeClass(_bodyElement, _classNameDragging); if (_scrollbarCornerElement.releaseCapture) _scrollbarCornerElement.releaseCapture(); if (eventIsTrusted) { if (_resizeReconnectMutationObserver) connectMutationObservers(); _base.update(_strAuto); } _resizeReconnectMutationObserver = false; } function onMouseTouchDownContinue(event) { var originalEvent = event.originalEvent || event; var isTouchEvent = originalEvent.touches !== undefined; return _isSleeping || _destroyed ? false : COMPATIBILITY.mBtn(event) === 1 || isTouchEvent; } function getCoordinates(event) { return _msieVersion && insideIFrame ? { x : event.screenX , y : event.screenY } : COMPATIBILITY.page(event); } } //==== Utils ====// /** * Calls the callback with the given name. The Context of this callback is always _base (this). * @param name The name of the target which shall be called. * @param args The args with which the callback shall be called. */ function dispatchCallback(name, args) { if(_initialized) { var callback = _currentPreparedOptions.callbacks[name]; var extensionOnName = name; var ext; if(extensionOnName.substr(0, 2) === "on") extensionOnName = extensionOnName.substr(2, 1).toLowerCase() + extensionOnName.substr(3); if(type(callback) == TYPES.f) callback.call(_base, args); FRAMEWORK.each(_extensions, function() { ext = this; if(type(ext.on) == TYPES.f) ext.on(extensionOnName, args); }); } else if(!_destroyed) _callbacksInitQeueue.push({ n : name, a : args }); } /** * Sets the "top, right, bottom, left" properties, with a given prefix, of the given css object. * @param targetCSSObject The css object to which the values shall be applied. * @param prefix The prefix of the "top, right, bottom, left" css properties. (example: 'padding-' is a valid prefix) * @param values A array of values which shall be applied to the "top, right, bottom, left" -properties. The array order is [top, right, bottom, left]. * If this argument is undefined the value '' (empty string) will be applied to all properties. */ function setTopRightBottomLeft(targetCSSObject, prefix, values) { if (values === undefined) values = [_strEmpty, _strEmpty, _strEmpty, _strEmpty]; targetCSSObject[prefix + _strTop] = values[0]; targetCSSObject[prefix + _strRight] = values[1]; targetCSSObject[prefix + _strBottom] = values[2]; targetCSSObject[prefix + _strLeft] = values[3]; } /** * Returns the computed CSS transition string from the given element. * @param element The element from which the transition string shall be returned. * @returns {string} The CSS transition string from the given element. */ function getCSSTransitionString(element) { var transitionStr = VENDORS._cssProperty('transition'); var assembledValue = element.css(transitionStr); if(assembledValue) return assembledValue; var regExpString = '\\s*(' + '([^,(]+(\\(.+?\\))?)+' + ')[\\s,]*'; var regExpMain = new RegExp(regExpString); var regExpValidate = new RegExp('^(' + regExpString + ')+$'); var properties = 'property duration timing-function delay'.split(' '); var result = [ ]; var strResult; var valueArray; var i = 0; var j; var splitCssStyleByComma = function(str) { strResult = [ ]; if (!str.match(regExpValidate)) return str; while (str.match(regExpMain)) { strResult.push(RegExp.$1); str = str.replace(regExpMain, _strEmpty); } return strResult; }; for (; i < properties[LEXICON.l]; i++) { valueArray = splitCssStyleByComma(element.css(transitionStr + '-' + properties[i])); for (j = 0; j < valueArray[LEXICON.l]; j++) result[j] = (result[j] ? result[j] + _strSpace : _strEmpty) + valueArray[j]; } return result.join(', '); } /** * Calculates the host-elements inverted scale. (invertedScale = 1 / scale) * @returns {{x: number, y: number}} The scale of the host-element. */ function getHostElementInvertedScale() { var rect = _paddingElementNative.getBoundingClientRect(); return { x : _supportTransform ? 1 / (MATH.round(rect.width) / _paddingElementNative[LEXICON.oW]) || 1 : 1, y : _supportTransform ? 1 / (MATH.round(rect.height) / _paddingElementNative[LEXICON.oH]) || 1 : 1 }; } /** * Checks whether the given object is a HTMLElement. * @param o The object which shall be checked. * @returns {boolean} True the given object is a HTMLElement, false otherwise. */ function isHTMLElement(o) { var strOwnerDocument = 'ownerDocument'; var strHTMLElement = 'HTMLElement'; var wnd = o && o[strOwnerDocument] ? (o[strOwnerDocument].parentWindow || window) : window; return ( typeof wnd[strHTMLElement] == TYPES.o ? o instanceof wnd[strHTMLElement] : //DOM2 o && typeof o == TYPES.o && o !== null && o.nodeType === 1 && typeof o.nodeName == TYPES.s ); } /** * Compares 2 arrays and returns the differences between them as a array. * @param a1 The first array which shall be compared. * @param a2 The second array which shall be compared. * @returns {Array} The differences between the two arrays. */ function getArrayDifferences(a1, a2) { var a = [ ]; var diff = [ ]; var i; var k; for (i = 0; i < a1.length; i++) a[a1[i]] = true; for (i = 0; i < a2.length; i++) { if (a[a2[i]]) delete a[a2[i]]; else a[a2[i]] = true; } for (k in a) diff.push(k); return diff; } /** * Returns Zero or the number to which the value can be parsed. * @param value The value which shall be parsed. * @param toFloat Indicates whether the number shall be parsed to a float. */ function parseToZeroOrNumber(value, toFloat) { var num = toFloat ? parseFloat(value) : parseInt(value, 10); return isNaN(num) ? 0 : num; } /** * Gets several information of the textarea and returns them as a object or undefined if the browser doesn't support it. * @returns {{cursorRow: Number, cursorCol, rows: Number, cols: number, wRow: number, pos: number, max : number}} or undefined if not supported. */ function getTextareaInfo() { //read needed values var textareaCursorPosition = _targetElementNative.selectionStart; if (textareaCursorPosition === undefined) return; var strLength = 'length'; var textareaValue = _targetElement.val(); var textareaLength = textareaValue[strLength]; var textareaRowSplit = textareaValue.split("\n"); var textareaLastRow = textareaRowSplit[strLength]; var textareaCurrentCursorRowSplit = textareaValue.substr(0, textareaCursorPosition).split("\n"); var widestRow = 0; var textareaLastCol = 0; var cursorRow = textareaCurrentCursorRowSplit[strLength]; var cursorCol = textareaCurrentCursorRowSplit[textareaCurrentCursorRowSplit[strLength] - 1][strLength]; var rowCols; var i; //get widest Row and the last column of the textarea for (i = 0; i < textareaRowSplit[strLength]; i++) { rowCols = textareaRowSplit[i][strLength]; if (rowCols > textareaLastCol) { widestRow = i + 1; textareaLastCol = rowCols; } } return { _cursorRow: cursorRow, //cursorRow _cursorColumn: cursorCol, //cursorCol _rows: textareaLastRow, //rows _columns: textareaLastCol, //cols _widestRow: widestRow, //wRow _cursorPosition: textareaCursorPosition, //pos _cursorMax: textareaLength //max }; } /** * Determines whether native overlay scrollbars are active. * @returns {boolean} True if native overlay scrollbars are active, false otherwise. */ function nativeOverlayScrollbarsAreActive() { return (_ignoreOverlayScrollbarHidingCache && (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y)); } /** * Gets the element which is used to measure the content size. * @returns {*} TextareaCover if target element is textarea else the ContentElement. */ function getContentMeasureElement() { return _isTextarea ? _textareaCoverElement[0] : _contentElementNative; } /** * Generates a string which represents a HTML div with the given classes or attributes. * @param classesOrAttrs The class of the div as string or a object which represents the attributes of the div. (The class attribute can also be written as "className".) * @param content The content of the div as string. * @returns {string} The concated string which represents a HTML div and its content. */ function generateDiv(classesOrAttrs, content) { return '<div ' + (classesOrAttrs ? type(classesOrAttrs) == TYPES.s ? 'class="' + classesOrAttrs + '"' : (function() { var key; var attrs = ''; if(FRAMEWORK.isPlainObject(classesOrAttrs)) { for (key in classesOrAttrs) attrs += (key === 'className' ? 'class' : key) + '="' + classesOrAttrs[key] + '" '; } return attrs; })() : _strEmpty) + '>' + (content ? content : _strEmpty) + '</div>'; } /** * Gets the value of the given property from the given object. * @param obj The object from which the property value shall be got. * @param path The property of which the value shall be got. * @returns {*} Returns the value of the searched property or undefined of the property wasn't found. */ function getObjectPropVal(obj, path) { var splits = path.split(_strDot); var i = 0; var val; for(; i < splits.length; i++) { if(!obj.hasOwnProperty(splits[i])) return; val = obj[splits[i]]; if(i < splits.length && type(val) == TYPES.o) obj = val; } return val; } /** * Sets the value of the given property from the given object. * @param obj The object from which the property value shall be set. * @param path The property of which the value shall be set. * @param val The value of the property which shall be set. */ function setObjectPropVal(obj, path, val) { var splits = path.split(_strDot); var splitsLength = splits.length; var i = 0; var extendObj = { }; var extendObjRoot = extendObj; for(; i < splitsLength; i++) extendObj = extendObj[splits[i]] = i + 1 < splitsLength ? { } : val; FRAMEWORK.extend(obj, extendObjRoot, true); } //==== Utils Cache ====// /** * Compares two values and returns the result of the comparison as a boolean. * @param current The first value which shall be compared. * @param cache The second value which shall be compared. * @param force If true the returned value is always true. * @returns {boolean} True if both variables aren't equal or some of them is undefined or when the force parameter is true, false otherwise. */ function checkCacheSingle(current, cache, force) { if (force === true) return force; if (cache === undefined) return true; else if (current !== cache) return true; return false; } /** * Compares two objects with two properties and returns the result of the comparison as a boolean. * @param current The first object which shall be compared. * @param cache The second object which shall be compared. * @param prop1 The name of the first property of the objects which shall be compared. * @param prop2 The name of the second property of the objects which shall be compared. * @param force If true the returned value is always true. * @returns {boolean} True if both variables aren't equal or some of them is undefined or when the force parameter is true, false otherwise. */ function checkCacheDouble(current, cache, prop1, prop2, force) { if (force === true) return force; if (prop2 === undefined && force === undefined) { if (prop1 === true) return prop1; else prop1 = undefined; } prop1 = prop1 === undefined ? 'w' : prop1; prop2 = prop2 === undefined ? 'h' : prop2; if (cache === undefined) return true; else if (current[prop1] !== cache[prop1] || current[prop2] !== cache[prop2]) return true; return false; } /** * Compares two objects which have four properties and returns the result of the comparison as a boolean. * @param current The first object with four properties. * @param cache The second object with four properties. * @returns {boolean} True if both objects aren't equal or some of them is undefined, false otherwise. */ function checkCacheTRBL(current, cache) { if (cache === undefined) return true; else if (current.t !== cache.t || current.r !== cache.r || current.b !== cache.b || current.l !== cache.l) return true; return false; } //==== Shortcuts ====// /** * jQuery type method shortcut. */ function type(obj) { return COMPATIBILITY.type(obj); } /** * jQuery extend method shortcut with a appended "true" as first argument. */ function extendDeep() { return FRAMEWORK.extend.apply(this, [ true ].concat([].slice.call(arguments))); } /** * jQuery addClass method shortcut. */ function addClass(el, classes) { return _frameworkProto.addClass.call(el, classes); } /** * jQuery removeClass method shortcut. */ function removeClass(el, classes) { return _frameworkProto.removeClass.call(el, classes); } /** * jQuery remove method shortcut. */ function remove(el) { return _frameworkProto.remove.call(el); } /** * Finds the first child element with the given selector of the given element. * @param el The root element from which the selector shall be valid. * @param selector The selector of the searched element. * @returns {*} The first element which is a child of the given element and matches the givens selector. */ function findFirst(el, selector) { return _frameworkProto.find.call(el, selector).eq(0); } //==== API ====// /** * Puts the instance to sleep. It wont respond to any changes in the DOM and won't update. Scrollbar Interactivity is also disabled as well as the resize handle. * This behavior can be reset by calling the update method. */ _base.sleep = function () { _isSleeping = true; }; /** * Updates the plugin and DOM to the current options. * This method should only be called if a update is 100% required. * @param force True if every property shall be updated and the cache shall be ignored. * !INTERNAL USAGE! : force can be a string "auto", "auto+" or "zoom" too * if this is the case then before a real update the content size and host element attributes gets checked, and if they changed only then the update method will be called. */ _base.update = function (force) { var attrsChanged; var contentSizeC; var isString = type(force) == TYPES.s; var imgElementSelector = 'img'; var imgElementLoadEvent = 'load'; if(isString) { if (force === _strAuto) { attrsChanged = meaningfulAttrsChanged(); contentSizeC = updateAutoContentSizeChanged(); if (attrsChanged || contentSizeC) update(false, contentSizeC, false); } else if (force === 'zoom') update(true, true); } else if(!synchronizeMutationObservers() || force) { force = _isSleeping || force; _isSleeping = false; update(false, false, force, true); } if(!_isTextarea) { _contentElement.find(imgElementSelector).each(function(i, el) { var index = COMPATIBILITY.inA(el, _imgs); if (index === -1) FRAMEWORK(el).off(imgElementLoadEvent, imgOnLoad).on(imgElementLoadEvent, imgOnLoad); }); } }; /** Gets or sets the current options. The update method will be called automatically if new options were set. * @param newOptions If new options are given, then the new options will be set, if new options aren't given (undefined or a not a plain object) then the current options will be returned. * @param value If new options is a property path string, then this value will be used to set the option to which the property path string leads. * @returns {*} */ _base.options = function (newOptions, value) { //return current options if newOptions are undefined or empty if (FRAMEWORK.isEmptyObject(newOptions) || !FRAMEWORK.isPlainObject(newOptions)) { if (type(newOptions) == TYPES.s) { if (arguments.length > 1) { var option = { }; setObjectPropVal(option, newOptions, value); setOptions(option); update(); return; } else return getObjectPropVal(_currentOptions, newOptions); } else return _currentOptions; } setOptions(newOptions); var isSleepingTmp = _isSleeping || false; _isSleeping = false; update(); _isSleeping = isSleepingTmp; }; /** * Restore the DOM, disconnects all observers, remove all resize observers and destroy all methods. */ _base.destroy = function () { _destroyed = true; //remove this instance from auto update loop autoUpdateLoop.remove(_base); //disconnect all mutation observers disconnectMutationObservers(); //remove all resize observers removeResizeObserver(_sizeObserverElement); if (_sizeAutoObserverAdded) removeResizeObserver(_sizeAutoObserverElement); //remove all extensions for(var extName in _extensions) _base.removeExt(extName); //remove all events from host element setupHostMouseTouchEvents(true); //remove all events from structure setupStructureEvents(true); //remove all helper / detection elements if (_contentGlueElement) remove(_contentGlueElement); if (_contentArrangeElement) remove(_contentArrangeElement); if (_sizeAutoObserverAdded) remove(_sizeAutoObserverElement); //remove all generated DOM setupScrollbarsDOM(true); setupScrollbarCornerDOM(true); setupStructureDOM(true); //remove all generated image load events for(var i = 0; i < _imgs[LEXICON.l]; i++) FRAMEWORK(_imgs[i]).off('load', imgOnLoad); _imgs = undefined; //remove this instance from the instances list INSTANCES(pluginTargetElement, 0); dispatchCallback("onDestroyed"); //remove all properties and methods for (var property in _base) delete _base[property]; _base = undefined; }; /** * Scrolls to a given position or element. * @param coordinates * 1. Can be "coordinates" which looks like: * { x : ?, y : ? } OR Object with x and y properties * { left : ?, top : ? } OR Object with left and top properties * { l : ?, t : ? } OR Object with l and t properties * [ ?, ? ] OR Array where the first two element are the coordinates (first is x, second is y) * ? A single value which stays for both axis * A value can be a number, a string or a calculation. * * Operators: * [NONE] The current scroll will be overwritten by the value. * '+=' The value will be added to the current scroll offset * '-=' The value will be subtracted from the current scroll offset * '*=' The current scroll wil be multiplicated by the value. * '/=' The current scroll wil be divided by the value. * * Units: * [NONE] The value is the final scroll amount. final = (value * 1) * 'px' Same as none * '%' The value is dependent on the current scroll value. final = ((currentScrollValue / 100) * value) * 'vw' The value is multiplicated by the viewport width. final = (value * viewportWidth) * 'vh' The value is multiplicated by the viewport height. final = (value * viewportHeight) * * example final values: * 200, '200px', '50%', '1vw', '1vh', '+=200', '/=1vw', '*=2px', '-=5vh', '+=33%', '+= 50% - 2px', '-= 1vw - 50%' * * 2. Can be a HTML or jQuery element: * The final scroll offset is the offset (without margin) of the given HTML / jQuery element. * * 3. Can be a object with a HTML or jQuery element with additional settings: * { * el : [HTMLElement, jQuery element], MUST be specified, else this object isn't valid. * scroll : [string, array, object], Default value is 'always'. * block : [string, array, object], Default value is 'begin'. * margin : [number, boolean, array, object] Default value is false. * } * * Possible scroll settings are: * 'always' Scrolls always. * 'ifneeded' Scrolls only if the element isnt fully in view. * 'never' Scrolls never. * * Possible block settings are: * 'begin' Both axis shall be docked to the "begin" edge. - The element will be docked to the top and left edge of the viewport. * 'end' Both axis shall be docked to the "end" edge. - The element will be docked to the bottom and right edge of the viewport. (If direction is RTL to the bottom and left edge.) * 'center' Both axis shall be docked to "center". - The element will be centered in the viewport. * 'nearest' The element will be docked to the nearest edge(s). * * Possible margin settings are: -- The actual margin of the element wont be affect, this option affects only the final scroll offset. * [BOOLEAN] If true the css margin of the element will be used, if false no margin will be used. * [NUMBER] The margin will be used for all edges. * * @param duration The duration of the scroll animation, OR a jQuery animation configuration object. * @param easing The animation easing. * @param complete The animation complete callback. * @returns {{ * position: {x: number, y: number}, * ratio: {x: number, y: number}, * max: {x: number, y: number}, * handleOffset: {x: number, y: number}, * handleLength: {x: number, y: number}, * handleLengthRatio: {x: number, y: number}, t * rackLength: {x: number, y: number}, * isRTL: boolean, * isRTLNormalized: boolean * }} */ _base.scroll = function (coordinates, duration, easing, complete) { if (arguments.length === 0 || coordinates === undefined) { var infoX = _scrollHorizontalInfo; var infoY = _scrollVerticalInfo; var normalizeInvert = _normalizeRTLCache && _isRTL && _rtlScrollBehavior.i; var normalizeNegate = _normalizeRTLCache && _isRTL && _rtlScrollBehavior.n; var scrollX = infoX._currentScroll; var scrollXRatio = infoX._currentScrollRatio; var maxScrollX = infoX._maxScroll; scrollXRatio = normalizeInvert ? 1 - scrollXRatio : scrollXRatio; scrollX = normalizeInvert ? maxScrollX - scrollX : scrollX; scrollX *= normalizeNegate ? -1 : 1; maxScrollX *= normalizeNegate ? -1 : 1; return { position : { x : scrollX, y : infoY._currentScroll }, ratio : { x : scrollXRatio, y : infoY._currentScrollRatio }, max : { x : maxScrollX, y : infoY._maxScroll }, handleOffset : { x : infoX._handleOffset, y : infoY._handleOffset }, handleLength : { x : infoX._handleLength, y : infoY._handleLength }, handleLengthRatio : { x : infoX._handleLengthRatio, y : infoY._handleLengthRatio }, trackLength : { x : infoX._trackLength, y : infoY._trackLength }, snappedHandleOffset : { x : infoX._snappedHandleOffset, y : infoY._snappedHandleOffset }, isRTL: _isRTL, isRTLNormalized: _normalizeRTLCache }; } synchronizeMutationObservers(); var normalizeRTL = _normalizeRTLCache; var coordinatesXAxisProps = [_strX, _strLeft, 'l']; var coordinatesYAxisProps = [_strY, _strTop, 't']; var coordinatesOperators = ['+=', '-=', '*=', '/=']; var durationIsObject = type(duration) == TYPES.o; var completeCallback = durationIsObject ? duration.complete : complete; var i; var finalScroll = { }; var specialEasing = {}; var doScrollLeft; var doScrollTop; var animationOptions; var strEnd = 'end'; var strBegin = 'begin'; var strCenter = 'center'; var strNearest = 'nearest'; var strAlways = 'always'; var strNever = 'never'; var strIfNeeded = 'ifneeded'; var strLength = LEXICON.l; var settingsAxis; var settingsScroll; var settingsBlock; var settingsMargin; var finalElement; var elementObjSettingsAxisValues = [_strX, _strY, 'xy', 'yx']; var elementObjSettingsBlockValues = [strBegin, strEnd, strCenter, strNearest]; var elementObjSettingsScrollValues = [strAlways, strNever, strIfNeeded]; var coordinatesIsElementObj = coordinates.hasOwnProperty('el'); var possibleElement = coordinatesIsElementObj ? coordinates.el : coordinates; var possibleElementIsJQuery = possibleElement instanceof FRAMEWORK || JQUERY ? possibleElement instanceof JQUERY : false; var possibleElementIsHTMLElement = possibleElementIsJQuery ? false : isHTMLElement(possibleElement); var proxyCompleteCallback = type(completeCallback) != TYPES.f ? undefined : function() { if(doScrollLeft) refreshScrollbarHandleOffset(true); if(doScrollTop) refreshScrollbarHandleOffset(false); completeCallback(); }; var checkSettingsStringValue = function (currValue, allowedValues) { for (i = 0; i < allowedValues[strLength]; i++) { if (currValue === allowedValues[i]) return true; } return false; }; var getRawScroll = function (isX, coordinates) { var coordinateProps = isX ? coordinatesXAxisProps : coordinatesYAxisProps; coordinates = type(coordinates) == TYPES.s || type(coordinates) == TYPES.n ? [ coordinates, coordinates ] : coordinates; if (type(coordinates) == TYPES.a) return isX ? coordinates[0] : coordinates[1]; else if (type(coordinates) == TYPES.o) { //decides RTL normalization "hack" with .n //normalizeRTL = type(coordinates.n) == TYPES.b ? coordinates.n : normalizeRTL; for (i = 0; i < coordinateProps[strLength]; i++) if (coordinateProps[i] in coordinates) return coordinates[coordinateProps[i]]; } }; var getFinalScroll = function (isX, rawScroll) { var isString = type(rawScroll) == TYPES.s; var operator; var amount; var scrollInfo = isX ? _scrollHorizontalInfo : _scrollVerticalInfo; var currScroll = scrollInfo._currentScroll; var maxScroll = scrollInfo._maxScroll; var mult = ' * '; var finalValue; var isRTLisX = _isRTL && isX; var normalizeShortcuts = isRTLisX && _rtlScrollBehavior.n && !normalizeRTL; var strReplace = 'replace'; var evalFunc = eval; var possibleOperator; if (isString) { //check operator if (rawScroll[strLength] > 2) { possibleOperator = rawScroll.substr(0, 2); if(FRAMEWORK.inArray(possibleOperator, coordinatesOperators) > -1) operator = possibleOperator; } //calculate units and shortcuts rawScroll = operator ? rawScroll.substr(2) : rawScroll; rawScroll = rawScroll [strReplace](/min/g, 0) //'min' = 0% [strReplace](/</g, 0) //'<' = 0% [strReplace](/max/g, (normalizeShortcuts ? '-' : _strEmpty) + _strHundredPercent) //'max' = 100% [strReplace](/>/g, (normalizeShortcuts ? '-' : _strEmpty) + _strHundredPercent) //'>' = 100% [strReplace](/px/g, _strEmpty) [strReplace](/%/g, mult + (maxScroll * (isRTLisX && _rtlScrollBehavior.n ? -1 : 1) / 100.0)) [strReplace](/vw/g, mult + _viewportSize.w) [strReplace](/vh/g, mult + _viewportSize.h); amount = parseToZeroOrNumber(isNaN(rawScroll) ? parseToZeroOrNumber(evalFunc(rawScroll), true).toFixed() : rawScroll); } else { amount = rawScroll; } if (amount !== undefined && !isNaN(amount) && type(amount) == TYPES.n) { var normalizeIsRTLisX = normalizeRTL && isRTLisX; var operatorCurrScroll = currScroll * (normalizeIsRTLisX && _rtlScrollBehavior.n ? -1 : 1); var invert = normalizeIsRTLisX && _rtlScrollBehavior.i; var negate = normalizeIsRTLisX && _rtlScrollBehavior.n; operatorCurrScroll = invert ? (maxScroll - operatorCurrScroll) : operatorCurrScroll; switch (operator) { case '+=': finalValue = operatorCurrScroll + amount; break; case '-=': finalValue = operatorCurrScroll - amount; break; case '*=': finalValue = operatorCurrScroll * amount; break; case '/=': finalValue = operatorCurrScroll / amount; break; default: finalValue = amount; break; } finalValue = invert ? maxScroll - finalValue : finalValue; finalValue *= negate ? -1 : 1; finalValue = isRTLisX && _rtlScrollBehavior.n ? MATH.min(0, MATH.max(maxScroll, finalValue)) : MATH.max(0, MATH.min(maxScroll, finalValue)); } return finalValue === currScroll ? undefined : finalValue; }; var getPerAxisValue = function (value, valueInternalType, defaultValue, allowedValues) { var resultDefault = [ defaultValue, defaultValue ]; var valueType = type(value); var valueArrLength; var valueArrItem; //value can be [ string, or array of two strings ] if (valueType == valueInternalType) { value = [value, value]; } else if (valueType == TYPES.a) { valueArrLength = value[strLength]; if (valueArrLength > 2 || valueArrLength < 1) value = resultDefault; else { if (valueArrLength === 1) value[1] = defaultValue; for (i = 0; i < valueArrLength; i++) { valueArrItem = value[i]; if (type(valueArrItem) != valueInternalType || !checkSettingsStringValue(valueArrItem, allowedValues)) { value = resultDefault; break; } } } } else if (valueType == TYPES.o) value = [ value[_strX]|| defaultValue, value[_strY] || defaultValue]; else value = resultDefault; return { x : value[0], y : value[1] }; }; var generateMargin = function (marginTopRightBottomLeftArray) { var result = [ ]; var currValue; var currValueType; var valueDirections = [ _strTop, _strRight, _strBottom, _strLeft ]; for(i = 0; i < marginTopRightBottomLeftArray[strLength]; i++) { if(i === valueDirections[strLength]) break; currValue = marginTopRightBottomLeftArray[i]; currValueType = type(currValue); if(currValueType == TYPES.b) result.push(currValue ? parseToZeroOrNumber(finalElement.css(_strMarginMinus + valueDirections[i])) : 0); else result.push(currValueType == TYPES.n ? currValue : 0); } return result; }; if (possibleElementIsJQuery || possibleElementIsHTMLElement) { //get settings var margin = coordinatesIsElementObj ? coordinates.margin : 0; var axis = coordinatesIsElementObj ? coordinates.axis : 0; var scroll = coordinatesIsElementObj ? coordinates.scroll : 0; var block = coordinatesIsElementObj ? coordinates.block : 0; var marginDefault = [ 0, 0, 0, 0 ]; var marginType = type(margin); var marginLength; finalElement = possibleElementIsJQuery ? possibleElement : FRAMEWORK(possibleElement); if (finalElement[strLength] === 0) return; //margin can be [ boolean, number, array of 2, array of 4, object ] if (marginType == TYPES.n || marginType == TYPES.b) margin = generateMargin([margin, margin, margin, margin]); else if (marginType == TYPES.a) { marginLength = margin[strLength]; if(marginLength === 2) margin = generateMargin([margin[0], margin[1], margin[0], margin[1]]); else if(marginLength >= 4) margin = generateMargin(margin); else margin = marginDefault; } else if (marginType == TYPES.o) margin = generateMargin([margin[_strTop], margin[_strRight], margin[_strBottom], margin[_strLeft]]); else margin = marginDefault; //block = type(block) === TYPES.b ? block ? [ strNearest, strBegin ] : [ strNearest, strEnd ] : block; settingsAxis = checkSettingsStringValue(axis, elementObjSettingsAxisValues) ? axis : 'xy'; settingsScroll = getPerAxisValue(scroll, TYPES.s, strAlways, elementObjSettingsScrollValues); settingsBlock = getPerAxisValue(block, TYPES.s, strBegin, elementObjSettingsBlockValues); settingsMargin = margin; var viewportScroll = { l: _scrollHorizontalInfo._currentScroll, t: _scrollVerticalInfo._currentScroll }; // use padding element instead of viewport element because padding element has never padding, margin or position applied. var viewportOffset = _paddingElement.offset(); //get coordinates var elementOffset = finalElement.offset(); var doNotScroll = { x : settingsScroll.x == strNever || settingsAxis == _strY, y : settingsScroll.y == strNever || settingsAxis == _strX }; elementOffset[_strTop] -= settingsMargin[0]; elementOffset[_strLeft] -= settingsMargin[3]; var elementScrollCoordinates = { x: MATH.round(elementOffset[_strLeft] - viewportOffset[_strLeft] + viewportScroll.l), y: MATH.round(elementOffset[_strTop] - viewportOffset[_strTop] + viewportScroll.t) }; if (_isRTL) { if (!_rtlScrollBehavior.n && !_rtlScrollBehavior.i) elementScrollCoordinates.x = MATH.round(viewportOffset[_strLeft] - elementOffset[_strLeft] + viewportScroll.l); if (_rtlScrollBehavior.n && normalizeRTL) elementScrollCoordinates.x *= -1; if (_rtlScrollBehavior.i && normalizeRTL) elementScrollCoordinates.x = MATH.round(viewportOffset[_strLeft] - elementOffset[_strLeft] + (_scrollHorizontalInfo._maxScroll - viewportScroll.l)); } //measuring is required if (settingsBlock.x != strBegin || settingsBlock.y != strBegin || settingsScroll.x == strIfNeeded || settingsScroll.y == strIfNeeded || _isRTL) { var measuringElm = finalElement[0]; var rawElementSize = _supportTransform ? measuringElm.getBoundingClientRect() : { width : measuringElm[LEXICON.oW], height : measuringElm[LEXICON.oH] }; var elementSize = { w: rawElementSize[_strWidth] + settingsMargin[3] + settingsMargin[1], h: rawElementSize[_strHeight] + settingsMargin[0] + settingsMargin[2] }; var finalizeBlock = function(isX) { var vars = getScrollbarVars(isX); var wh = vars._w_h; var lt = vars._left_top; var xy = vars._x_y; var blockIsEnd = settingsBlock[xy] == (isX ? _isRTL ? strBegin : strEnd : strEnd); var blockIsCenter = settingsBlock[xy] == strCenter; var blockIsNearest = settingsBlock[xy] == strNearest; var scrollNever = settingsScroll[xy] == strNever; var scrollIfNeeded = settingsScroll[xy] == strIfNeeded; var vpSize = _viewportSize[wh]; var vpOffset = viewportOffset[lt]; var elSize = elementSize[wh]; var elOffset = elementOffset[lt]; var divide = blockIsCenter ? 2 : 1; var elementCenterOffset = elOffset + (elSize / 2); var viewportCenterOffset = vpOffset + (vpSize / 2); var isInView = elSize <= vpSize && elOffset >= vpOffset && elOffset + elSize <= vpOffset + vpSize; if(scrollNever) doNotScroll[xy] = true; else if(!doNotScroll[xy]) { if (blockIsNearest || scrollIfNeeded) { doNotScroll[xy] = scrollIfNeeded ? isInView : false; blockIsEnd = elSize < vpSize ? elementCenterOffset > viewportCenterOffset : elementCenterOffset < viewportCenterOffset; } elementScrollCoordinates[xy] -= blockIsEnd || blockIsCenter ? ((vpSize / divide) - (elSize / divide)) * (isX && _isRTL && normalizeRTL ? -1 : 1) : 0; } }; finalizeBlock(true); finalizeBlock(false); } if (doNotScroll.y) delete elementScrollCoordinates.y; if (doNotScroll.x) delete elementScrollCoordinates.x; coordinates = elementScrollCoordinates; } finalScroll[_strScrollLeft] = getFinalScroll(true, getRawScroll(true, coordinates)); finalScroll[_strScrollTop] = getFinalScroll(false, getRawScroll(false, coordinates)); doScrollLeft = finalScroll[_strScrollLeft] !== undefined; doScrollTop = finalScroll[_strScrollTop] !== undefined; if ((doScrollLeft || doScrollTop) && (duration > 0 || durationIsObject)) { if (durationIsObject) { duration.complete = proxyCompleteCallback; _viewportElement.animate(finalScroll, duration); } else { animationOptions = { duration: duration, complete: proxyCompleteCallback }; if (type(easing) == TYPES.a || FRAMEWORK.isPlainObject(easing)) { specialEasing[_strScrollLeft] = easing[0] || easing.x; specialEasing[_strScrollTop] = easing[1] || easing.y; animationOptions.specialEasing = specialEasing; } else { animationOptions.easing = easing; } _viewportElement.animate(finalScroll, animationOptions); } } else { if (doScrollLeft) _viewportElement[_strScrollLeft](finalScroll[_strScrollLeft]); if (doScrollTop) _viewportElement[_strScrollTop](finalScroll[_strScrollTop]); } }; /** * Stops all scroll animations. * @returns {*} The current OverlayScrollbars instance (for chaining). */ _base.scrollStop = function (param1, param2, param3) { _viewportElement.stop(param1, param2, param3); return _base; }; /** * Returns all relevant elements. * @param elementName The name of the element which shall be returned. * @returns {{target: *, host: *, padding: *, viewport: *, content: *, scrollbarHorizontal: {scrollbar: *, track: *, handle: *}, scrollbarVertical: {scrollbar: *, track: *, handle: *}, scrollbarCorner: *} | *} */ _base.getElements = function (elementName) { var obj = { target: _targetElementNative, host: _hostElementNative, padding: _paddingElementNative, viewport: _viewportElementNative, content: _contentElementNative, scrollbarHorizontal: { scrollbar: _scrollbarHorizontalElement[0], track: _scrollbarHorizontalTrackElement[0], handle: _scrollbarHorizontalHandleElement[0] }, scrollbarVertical: { scrollbar: _scrollbarVerticalElement[0], track: _scrollbarVerticalTrackElement[0], handle: _scrollbarVerticalHandleElement[0] }, scrollbarCorner: _scrollbarCornerElement[0] }; return type(elementName) == TYPES.s ? getObjectPropVal(obj, elementName) : obj; }; /** * Returns a object which describes the current state of this instance. * @param stateProperty A specific property from the state object which shall be returned. * @returns {{widthAuto, heightAuto, overflowAmount, hideOverflow, hasOverflow, contentScrollSize, viewportSize, hostSize, autoUpdate} | *} */ _base.getState = function (stateProperty) { var prepare = function (obj) { if (!FRAMEWORK.isPlainObject(obj)) return obj; var extended = extendDeep({}, obj); var changePropertyName = function (from, to) { if (extended.hasOwnProperty(from)) { extended[to] = extended[from]; delete extended[from]; } }; changePropertyName('w', _strWidth); //change w to width changePropertyName('h', _strHeight); //change h to height delete extended.c; //delete c (the 'changed' prop) return extended; }; var obj = { sleeping: prepare(_isSleeping) || false, autoUpdate: prepare(!_mutationObserversConnected), widthAuto: prepare(_widthAutoCache), heightAuto: prepare(_heightAutoCache), padding: prepare(_cssPaddingCache), overflowAmount: prepare(_overflowAmountCache), hideOverflow: prepare(_hideOverflowCache), hasOverflow: prepare(_hasOverflowCache), contentScrollSize: prepare(_contentScrollSizeCache), viewportSize: prepare(_viewportSize), hostSize: prepare(_hostSizeCache), documentMixed : prepare(_documentMixed) }; return type(stateProperty) == TYPES.s ? getObjectPropVal(obj, stateProperty) : obj; }; /** * Gets all or specific extension instance. * @param extName The name of the extension from which the instance shall be got. * @returns {{}} The instance of the extension with the given name or undefined if the instance couldn't be found. */ _base.ext = function(extName) { var result; var privateMethods = _extensionsPrivateMethods.split(' '); var i = 0; if(type(extName) == TYPES.s) { if(_extensions.hasOwnProperty(extName)) { result = extendDeep({}, _extensions[extName]); for (; i < privateMethods.length; i++) delete result[privateMethods[i]]; } } else { result = { }; for(i in _extensions) result[i] = extendDeep({ }, _base.ext(i)); } return result; }; /** * Adds a extension to this instance. * @param extName The name of the extension which shall be added. * @param extensionOptions The extension options which shall be used. * @returns {{}} The instance of the added extension or undefined if the extension couldn't be added properly. */ _base.addExt = function(extName, extensionOptions) { var registeredExtensionObj = window[PLUGINNAME].extension(extName); var instance; var instanceAdded; var instanceContract; var contractResult; var contractFulfilled = true; if(registeredExtensionObj) { if(!_extensions.hasOwnProperty(extName)) { instance = registeredExtensionObj.extensionFactory.call(_base, extendDeep({ }, registeredExtensionObj.defaultOptions), FRAMEWORK, COMPATIBILITY); if (instance) { instanceContract = instance.contract; if (type(instanceContract) == TYPES.f) { contractResult = instanceContract(window); contractFulfilled = type(contractResult) == TYPES.b ? contractResult : contractFulfilled; } if(contractFulfilled) { _extensions[extName] = instance; instanceAdded = instance.added; if(type(instanceAdded) == TYPES.f) instanceAdded(extensionOptions); return _base.ext(extName); } } } else return _base.ext(extName); } else console.warn("A extension with the name \"" + extName + "\" isn't registered."); }; /** * Removes a extension from this instance. * @param extName The name of the extension which shall be removed. * @returns {boolean} True if the extension was removed, false otherwise e.g. if the extension wasn't added before. */ _base.removeExt = function(extName) { var instance = _extensions[extName]; var instanceRemoved; if(instance) { delete _extensions[extName]; instanceRemoved = instance.removed; if(type(instanceRemoved) == TYPES.f) instanceRemoved(); return true; } return false; }; /** * Constructs the plugin. * @param targetElement The element to which the plugin shall be applied. * @param options The initial options of the plugin. * @param extensions The extension(s) which shall be added right after the initialization. * @returns {boolean} True if the plugin was successfully initialized, false otherwise. */ function construct(targetElement, options, extensions) { _defaultOptions = globals.defaultOptions; _nativeScrollbarStyling = globals.nativeScrollbarStyling; _nativeScrollbarSize = extendDeep({}, globals.nativeScrollbarSize); _nativeScrollbarIsOverlaid = extendDeep({}, globals.nativeScrollbarIsOverlaid); _overlayScrollbarDummySize = extendDeep({}, globals.overlayScrollbarDummySize); _rtlScrollBehavior = extendDeep({}, globals.rtlScrollBehavior); //parse & set options but don't update setOptions(extendDeep({ }, _defaultOptions, _pluginsOptions._validate(options, _pluginsOptions._template, true))); //check if the plugin hasn't to be initialized if (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.x && !_currentPreparedOptions.nativeScrollbarsOverlaid.initialize) { dispatchCallback("onInitializationWithdrawn"); return false; } _cssCalc = globals.cssCalc; _msieVersion = globals.msie; _autoUpdateRecommended = globals.autoUpdateRecommended; _supportTransition = globals.supportTransition; _supportTransform = globals.supportTransform; _supportPassiveEvents = globals.supportPassiveEvents; _supportResizeObserver = globals.supportResizeObserver; _supportMutationObserver = globals.supportMutationObserver; _restrictedMeasuring = globals.restrictedMeasuring; _documentElement = FRAMEWORK(targetElement.ownerDocument); _documentElementNative = _documentElement[0]; _windowElement = FRAMEWORK(_documentElementNative.defaultView || _documentElementNative.parentWindow); _windowElementNative = _windowElement[0]; _htmlElement = findFirst(_documentElement, 'html'); _bodyElement = findFirst(_htmlElement, 'body'); _targetElement = FRAMEWORK(targetElement); _targetElementNative = _targetElement[0]; _isTextarea = _targetElement.is('textarea'); _isBody = _targetElement.is('body'); _documentMixed = _documentElementNative !== document; var initBodyScroll; if (_isBody) { initBodyScroll = {}; initBodyScroll.l = MATH.max(_targetElement[_strScrollLeft](), _htmlElement[_strScrollLeft](), _windowElement[_strScrollLeft]()); initBodyScroll.t = MATH.max(_targetElement[_strScrollTop](), _htmlElement[_strScrollTop](), _windowElement[_strScrollTop]()); } //build OverlayScrollbars DOM and Events setupStructureDOM(); setupStructureEvents(); //build Scrollbars DOM and Events setupScrollbarsDOM(); setupScrollbarEvents(true); setupScrollbarEvents(false); //build Scrollbar Corner DOM and Events setupScrollbarCornerDOM(); setupScrollbarCornerEvents(); //create mutation observers createMutationObservers(); if(_isBody) { //apply the body scroll to handle it right in the update method _viewportElement[_strScrollLeft](initBodyScroll.l)[_strScrollTop](initBodyScroll.t); //set the focus on the viewport element so you dont have to click on the page to use keyboard keys (up / down / space) for scrolling if(document.activeElement == targetElement && _viewportElementNative.focus) { //set a tabindex to make the viewportElement focusable _viewportElement.attr('tabindex', '-1'); _viewportElementNative.focus(); /* the tabindex has to be removed due to; * If you set the tabindex attribute on an <div>, then its child content cannot be scrolled with the arrow keys unless you set tabindex on the content, too * https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex */ _viewportElement.one(_strMouseTouchDownEvent, function() { _viewportElement.removeAttr('tabindex'); }); } } //build resize observer for the host element addResizeObserver(_sizeObserverElement, hostOnResized); //update for the first time hostOnResized(); //initialize cache for host size _base.update(_strAuto); //initialize cache for content //the plugin is initialized now! _initialized = true; dispatchCallback("onInitialized"); //call all callbacks which would fire before the initialized was complete FRAMEWORK.each(_callbacksInitQeueue, function(index, value) { dispatchCallback(value.n, value.a); }); _callbacksInitQeueue = [ ]; //add extensions if(type(extensions) == TYPES.s) extensions = [ extensions ]; if(COMPATIBILITY.isA(extensions)) FRAMEWORK.each(extensions, function (index, value) {_base.addExt(value); }); else if(FRAMEWORK.isPlainObject(extensions)) FRAMEWORK.each(extensions, function (key, value) { _base.addExt(key, value); }); //add the transition class for transitions AFTER the first update & AFTER the applied extensions (for preventing unwanted transitions) setTimeout(function () { if (_supportTransition && !_destroyed) addClass(_hostElement, _classNameHostTransition); }, 333); return _initialized; } if (construct(pluginTargetElement, options, extensions)) { INSTANCES(pluginTargetElement, _base); return _base; } _base = undefined; } /** * Initializes a new OverlayScrollbarsInstance object or changes options if already initialized or returns the current instance. * @param pluginTargetElements The elements to which the Plugin shall be initialized. * @param options The custom options with which the plugin shall be initialized. * @param extensions The extension(s) which shall be added right after initialization. * @returns {*} */ window[PLUGINNAME] = function(pluginTargetElements, options, extensions) { if(arguments[LEXICON.l] === 0) return this; var arr = [ ]; var optsIsPlainObj = FRAMEWORK.isPlainObject(options); var inst; var result; //pluginTargetElements is null or undefined if(!pluginTargetElements) return optsIsPlainObj || !options ? result : arr; /* pluginTargetElements will be converted to: 1. A jQueryElement Array 2. A HTMLElement Array 3. A Array with a single HTML Element so pluginTargetElements is always a array. */ pluginTargetElements = pluginTargetElements[LEXICON.l] != undefined ? pluginTargetElements : [ pluginTargetElements[0] || pluginTargetElements ]; initOverlayScrollbarsStatics(); if(pluginTargetElements[LEXICON.l] > 0) { if(optsIsPlainObj) { FRAMEWORK.each(pluginTargetElements, function (i, v) { inst = v; if(inst !== undefined) arr.push(OverlayScrollbarsInstance(inst, options, extensions, _pluginsGlobals, _pluginsAutoUpdateLoop)); }); } else { FRAMEWORK.each(pluginTargetElements, function(i, v) { inst = INSTANCES(v); if((options === '!' && inst instanceof window[PLUGINNAME]) || (COMPATIBILITY.type(options) == TYPES.f && options(v, inst))) arr.push(inst); else if(options === undefined) arr.push(inst); }); } result = arr[LEXICON.l] === 1 ? arr[0] : arr; } return result; }; /** * Returns a object which contains global information about the plugin and each instance of it. * The returned object is just a copy, that means that changes to the returned object won't have any effect to the original object. */ window[PLUGINNAME].globals = function () { initOverlayScrollbarsStatics(); var globals = FRAMEWORK.extend(true, { }, _pluginsGlobals); delete globals['msie']; return globals; }; /** * Gets or Sets the default options for each new plugin initialization. * @param newDefaultOptions The object with which the default options shall be extended. */ window[PLUGINNAME].defaultOptions = function(newDefaultOptions) { initOverlayScrollbarsStatics(); var currDefaultOptions = _pluginsGlobals.defaultOptions; if(newDefaultOptions === undefined) return FRAMEWORK.extend(true, { }, currDefaultOptions); //set the new default options _pluginsGlobals.defaultOptions = FRAMEWORK.extend(true, { }, currDefaultOptions , _pluginsOptions._validate(newDefaultOptions, _pluginsOptions._template, true)); }; /** * Registers, Unregisters or returns a extension. * Register: Pass the name and the extension. (defaultOptions is optional) * Unregister: Pass the name and anything except a function as extension parameter. * Get extension: Pass the name of the extension which shall be got. * Get all extensions: Pass no arguments. * @param extensionName The name of the extension which shall be registered, unregistered or returned. * @param extension A function which generates the instance of the extension or anything other to remove a already registered extension. * @param defaultOptions The default options which shall be used for the registered extension. */ window[PLUGINNAME].extension = function(extensionName, extension, defaultOptions) { var extNameTypeString = COMPATIBILITY.type(extensionName) == TYPES.s; var argLen = arguments[LEXICON.l]; var i = 0; if(argLen < 1 || !extNameTypeString) { //return a copy of all extension objects return FRAMEWORK.extend(true, { length : _pluginsExtensions[LEXICON.l] }, _pluginsExtensions); } else if(extNameTypeString) { if(COMPATIBILITY.type(extension) == TYPES.f) { //register extension _pluginsExtensions.push({ name : extensionName, extensionFactory : extension, defaultOptions : defaultOptions }); } else { for(; i < _pluginsExtensions[LEXICON.l]; i++) { if (_pluginsExtensions[i].name === extensionName) { if(argLen > 1) _pluginsExtensions.splice(i, 1); //remove extension else return FRAMEWORK.extend(true, { }, _pluginsExtensions[i]); //return extension with the given name } } } } }; return window[PLUGINNAME]; })(); if(JQUERY && JQUERY.fn) { /** * The jQuery initialization interface. * @param options The initial options for the construction of the plugin. To initialize the plugin, this option has to be a object! If it isn't a object, the instance(s) are returned and the plugin wont be initialized. * @param extensions The extension(s) which shall be added right after initialization. * @returns {*} After initialization it returns the jQuery element array, else it returns the instance(s) of the elements which are selected. */ JQUERY.fn.overlayScrollbars = function (options, extensions) { var _elements = this; if(JQUERY.isPlainObject(options)) { JQUERY.each(_elements, function() { PLUGIN(this, options, extensions); }); return _elements; } else return PLUGIN(_elements, options); }; } return PLUGIN; } ));
extend1994/cdnjs
ajax/libs/overlayscrollbars/1.7.3/js/OverlayScrollbars.js
JavaScript
mit
348,965
import _curry3 from './internal/_curry3.js'; import prop from './prop.js'; /** * Returns `true` if the specified object property satisfies the given * predicate; `false` otherwise. You can test multiple properties with * [`R.where`](#where). * * @func * @memberOf R * @since v0.16.0 * @category Logic * @sig (a -> Boolean) -> String -> {String: a} -> Boolean * @param {Function} pred * @param {String} name * @param {*} obj * @return {Boolean} * @see R.where, R.propEq, R.propIs * @example * * R.propSatisfies(x => x > 0, 'x', {x: 1, y: 2}); //=> true */ var propSatisfies = _curry3(function propSatisfies(pred, name, obj) { return pred(prop(name, obj)); }); export default propSatisfies;
ramda/ramda
source/propSatisfies.js
JavaScript
mit
715
import * as React from 'react'; /* * A utility for rendering a drag preview image */ export var DragPreviewImage = React.memo(function (_ref) { var connect = _ref.connect, src = _ref.src; React.useEffect(function () { if (typeof Image === 'undefined') return; var connected = false; var img = new Image(); img.src = src; img.onload = function () { connect(img); connected = true; }; return function () { if (connected) { connect(null); } }; }); return null; }); DragPreviewImage.displayName = 'DragPreviewImage';
cdnjs/cdnjs
ajax/libs/react-dnd/11.1.3/esm/common/DragPreviewImage.js
JavaScript
mit
595
import setupStore from 'dummy/tests/helpers/store'; import Ember from 'ember'; import testInDebug from 'dummy/tests/helpers/test-in-debug'; import {module, test} from 'qunit'; import DS from 'ember-data'; const { run } = Ember; const { attr } = DS; const { reject } = Ember.RSVP; let Person, store, env; module("integration/adapter/find - Finding Records", { beforeEach() { Person = DS.Model.extend({ updatedAt: attr('string'), name: attr('string'), firstName: attr('string'), lastName: attr('string') }); env = setupStore({ person: Person }); store = env.store; }, afterEach() { run(store, 'destroy'); } }); testInDebug("It raises an assertion when `undefined` is passed as id (#1705)", (assert) => { assert.expectAssertion(() => { store.find('person', undefined); }, "You cannot pass `undefined` as id to the store's find method"); assert.expectAssertion(() => { store.find('person', null); }, "You cannot pass `null` as id to the store's find method"); }); test("When a single record is requested, the adapter's find method should be called unless it's loaded.", (assert) => { assert.expect(2); var count = 0; env.registry.register('adapter:person', DS.Adapter.extend({ findRecord(_, type) { assert.equal(type, Person, "the find method is called with the correct type"); assert.equal(count, 0, "the find method is only called once"); count++; return { id: 1, name: "Braaaahm Dale" }; } })); run(() => { store.findRecord('person', 1); store.findRecord('person', 1); }); }); test("When a single record is requested multiple times, all .findRecord() calls are resolved after the promise is resolved", (assert) => { var deferred = Ember.RSVP.defer(); env.registry.register('adapter:person', DS.Adapter.extend({ findRecord: () => deferred.promise })); run(() => { store.findRecord('person', 1).then(assert.wait(function(person) { assert.equal(person.get('id'), "1"); assert.equal(person.get('name'), "Braaaahm Dale"); let done = assert.async(); deferred.promise.then(() => { assert.ok(true, 'expected deferred.promise to fulfill'); done(); }, () => { assert.ok(false, 'expected deferred.promise to fulfill, but rejected'); done(); }); })); }); run(() => { store.findRecord('person', 1).then(assert.wait((post) => { assert.equal(post.get('id'), "1"); assert.equal(post.get('name'), "Braaaahm Dale"); let done = assert.async(); deferred.promise.then(() => { assert.ok(true, 'expected deferred.promise to fulfill'); done(); }, () => { assert.ok(false, 'expected deferred.promise to fulfill, but rejected'); done(); }); })); }); run(() => deferred.resolve({ id: 1, name: "Braaaahm Dale" })); }); test("When a single record is requested, and the promise is rejected, .findRecord() is rejected.", (assert) => { env.registry.register('adapter:person', DS.Adapter.extend({ findRecord: () => reject() })); run(() => { store.findRecord('person', 1).then(null, assert.wait(() => { assert.ok(true, "The rejection handler was called"); })); }); }); test("When a single record is requested, and the promise is rejected, the record should be unloaded.", (assert) => { assert.expect(2); env.registry.register('adapter:person', DS.Adapter.extend({ findRecord: () => reject() })); run(() => { store.findRecord('person', 1).then(null, assert.wait((reason) => { assert.ok(true, "The rejection handler was called"); assert.ok(!store.hasRecordForId('person', 1), "The record has been unloaded"); })); }); }); testInDebug('When a single record is requested, and the payload is blank', (assert) => { env.registry.register('adapter:person', DS.Adapter.extend({ findRecord: () => Ember.RSVP.resolve({}) })); assert.expectAssertion(() => { run(() => store.findRecord('person', 'the-id')); }, /You made a `findRecord` request for a person with id the-id, but the adapter's response did not have any data/); }); testInDebug('When multiple records are requested, and the payload is blank', (assert) => { env.registry.register('adapter:person', DS.Adapter.extend({ coalesceFindRequests: true, findMany: () => Ember.RSVP.resolve({}) })); assert.expectAssertion(() => { run(() => { store.findRecord('person', '1'); store.findRecord('person', '2'); }); }, /You made a `findMany` request for person records with ids 1,2, but the adapter's response did not have any data/); }); testInDebug("warns when returned record has different id", function(assert) { env.registry.register('adapter:person', DS.Adapter.extend({ findRecord() { return { id: 1, name: "Braaaahm Dale" }; } })); assert.expectWarning(/You requested a record of type 'person' with id 'me' but the adapter returned a payload with primary data having an id of '1'/); run(function() { env.store.findRecord('person', 'me'); }); });
wecc/data
tests/integration/adapter/find-test.js
JavaScript
mit
5,129