code
stringlengths
2
1.05M
const BaseEvent = require('./base') const { EVENT_UPDATE_TASK } = require('../utils/constants') const taskSerializer = require('../serializers/task') class UpdateTaskEvent extends BaseEvent { constructor (task) { const data = taskSerializer(task, { preview: true }) if (task.isInitial()) { super(EVENT_UPDATE_TASK, data, null, null, {}) } else { super(EVENT_UPDATE_TASK, data, data, data, {}) } } } module.exports = UpdateTaskEvent
var util = require('util'); var logger = require('pomelo-logger').getLogger(__filename); var utils = module.exports; /** * Invoke callback with check */ utils.invokeCallback = function (cb) { if (!!cb && typeof cb === 'function') { cb.apply(null, Array.prototype.slice.call(arguments, 1)); } }; /** * Get the count of elements of object */ utils.size = function (obj) { var count = 0; for (var i in obj) { if (obj.hasOwnProperty(i) && typeof obj[i] !== 'function') { count++; } } return count; }; /** * Chech a string whether ends with another string */ utils.endsWith = function (str, suffix) { if (typeof(str) === 'string') { return str.indexOf(suffix, str.length - suffix.length) !== -1; } return false; }; /** * Chech a string whether starts with another string */ utils.startWith = function (str, prefix) { if (!prefix || !str || prefix.length > str.length) { return false; } if (str.substr(0, prefix.length) === prefix) { return true; } else { return false; } }; /* * Date format */ utils.format = function (date, format) { format = format || 'MMddhhmm'; var o = { "M+":date.getMonth() + 1, //month "d+":date.getDate(), //day "h+":date.getHours(), //hour "m+":date.getMinutes(), //minute "s+":date.getSeconds(), //second "q+":Math.floor((date.getMonth() + 3) / 3), //quarter "S":date.getMilliseconds() //millisecond }; if (/(y+)/.test(format)) { format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length)); } for (var k in o) { if (new RegExp("(" + k + ")").test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); } } return format; }; /** * Process command line arguments. * * @param args command line arguments * * @return Object args_map map of arguments */ utils.argsInfo = function (args) { var args_map = {}; var main_pos = 1; while(args[main_pos].indexOf('--')>0){ main_pos++; } args_map.main = args[main_pos]; for (var i = (main_pos+1); i < args.length; i++) { var str = args[i].split('='); args_map[str[0]] = str[1]; } return args_map; };
module.exports = require('./lib/imagesize');
version https://git-lfs.github.com/spec/v1 oid sha256:cbdbcc4f4f30dcc5647630554208a2fc507a43f31c7e6aa2e15ed4071cf758bb size 2680
requirejs.config( { paths: { "main-gsap": "vendor/gsap/main-gsap", "tocify": "vendor/tocify/jquery.tocify.min", "jquery-ui": "vendor/jquery-ui/js/jquery-ui-1.10.3.minimal.min", "jquery-1.11.0.min": "vendor/jquery-1.11.0.min", "bootstrap": "vendor/bootstrap.min", "front-neon-slider": "vendor/front-neon-slider", "front-joinable": "vendor/front-joinable", "front-resizeable": "vendor/front-resizeable", "front-selectnav.min": "vendor/front-selectnav.min", "resizeable": "vendor/resizeable", "joinable": "vendor/joinable", "scrollMonitor": "vendor/scrollMonitor", "jquery.bootstrap.wizard.min": "vendor/jquery.bootstrap.wizard.min", "jquery.validate.min": "vendor/jquery.validate.min", "jquery.inputmask.bundle.min": "vendor/jquery.inputmask.bundle.min", "order-information-logic": "vendor/order-information-logic", "front-neon-custom": "vendor/front-neon-custom", "neon-custom": "vendor/neon-custom", "neon-demo": "vendor/neon-demo", "neon-api": "vendor/neon-api", "neon-register": "vendor/neon-register", "jquery-ui-1.10.3.minimal.min": "vendor/jquery-ui/js/jquery-ui-1.10.3.minimal.min", "neon-login": "vendor/neon-login" }, shim: { "bootstrap": { deps:["jquery-1.11.0.min"] }, "neon-login": { deps:["jquery-1.11.0.min"] } } }); require(["main-gsap", "jquery-1.11.0.min", "neon-demo", "neon-custom", "bootstrap", "joinable", "resizeable", "neon-api", "neon-register", "neon-login", "jquery.validate.min", "jquery.inputmask.bundle.min", "jquery-ui-1.10.3.minimal.min"], function (bootstrap) { })
/* @flow */ export default function FelaThemeFactory( createElement: Function, ThemeContext: any ): any { function FelaTheme({ children }) { const renderFn = children return createElement(ThemeContext.Consumer, undefined, renderFn) } return FelaTheme }
(function(){ 'use strict'; Global.define('Sample.controller.Top',{ extend: Global.app.Controller, init: function(config) { this._super(config); $('.pagename').text('page top'); console.log('init page top'); }, restart: function() { $('.pagename').text('page top'); console.log('restart page top'); } }); })();
'use strict'; var ensureDate = require('es5-ext/date/valid-date') , ensureString = require('es5-ext/object/validate-stringifiable-value') , db = require('../db') , toDateInTimeZone = require('./to-date-in-time-zone') , daysOff = db.globalPrimitives.holidays.map(Number); var isDayOff = function (date) { var dayOfWeek = date.getUTCDay(); return dayOfWeek === 0 || dayOfWeek === 6 || daysOff.has(Number(date)); }; module.exports = function (startDate, endDate, timeZone) { var daysPassed = 0; timeZone = ensureString(timeZone); startDate = toDateInTimeZone(ensureDate(startDate), timeZone); endDate = toDateInTimeZone(ensureDate(endDate), timeZone); while (startDate < endDate) { if (!isDayOff(startDate)) ++daysPassed; startDate.setUTCDate(startDate.getUTCDate() + 1); } return daysPassed; };
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("circle", { cx: "9", cy: "8.5", r: "1.5", opacity: ".3" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M4.77 17h4.28c.01-.06.12-.58.29-.99-.11 0-.23-.01-.34-.01-1.53 0-3.25.5-4.23 1z", opacity: ".3" }, "1"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M9 12c1.93 0 3.5-1.57 3.5-3.5S10.93 5 9 5 5.5 6.57 5.5 8.5 7.07 12 9 12zm0-5c.83 0 1.5.67 1.5 1.5S9.83 10 9 10s-1.5-.67-1.5-1.5S8.17 7 9 7zm.05 10H4.77c.99-.5 2.7-1 4.23-1 .11 0 .23.01.34.01.34-.73.93-1.33 1.64-1.81-.73-.13-1.42-.2-1.98-.2-2.34 0-7 1.17-7 3.5V19h7v-1.5c0-.17.02-.34.05-.5zm7.45-2.5c-1.84 0-5.5 1.01-5.5 3V19h11v-1.5c0-1.99-3.66-3-5.5-3zm1.21-1.82c.76-.43 1.29-1.24 1.29-2.18C19 9.12 17.88 8 16.5 8S14 9.12 14 10.5c0 .94.53 1.75 1.29 2.18.36.2.77.32 1.21.32s.85-.12 1.21-.32z" }, "2")], 'SupervisorAccountTwoTone'); exports.default = _default;
import Ember from 'ember'; export default Ember.Helper.helper((params, hash) => { return hash; });
require('ember-bootstrap/mixins/item_selection_support'); require('ember-bootstrap/mixins/item_view_href_support'); var A = Ember.A; Bootstrap.Pagination = Ember.CollectionView.extend({ tagName: 'ul', classNames: ['pagination'], itemTitleKey: 'title', itemHrefKey: 'href', init: function() { this._super(); if (!this.get('content')) { this.set('content', new A([])); } }, itemViewClass: Ember.View.extend(Bootstrap.ItemSelectionSupport, Bootstrap.ItemViewHrefSupport, { classNameBindings: ['content.disabled'], template: Ember.Handlebars.compile('<a {{bindAttr href="view.href"}}>{{view.title}}</a>') }) });
/* 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.widget.FilePicker"]){ dojo._hasResource["dojox.widget.FilePicker"]=true; dojo.provide("dojox.widget.FilePicker"); dojo.require("dojox.widget.RollingList"); dojo.require("dojo.i18n"); dojo.requireLocalization("dojox.widget","FilePicker",null,"ROOT,ar,ca,cs,da,de,el,es,fi,fr,he,hu,it,ja,ko,nb,nl,pl,pt,pt-pt,ru,sk,sl,sv,th,tr,zh,zh-tw"); dojo.declare("dojox.widget._FileInfoPane",[dojox.widget._RollingListPane],{templateString:"",templateString:"<div class=\"dojoxFileInfoPane\">\n\t<table>\n\t\t<tbody>\n\t\t\t<tr>\n\t\t\t\t<td class=\"dojoxFileInfoLabel dojoxFileInfoNameLabel\">${_messages.name}</td>\n\t\t\t\t<td class=\"dojoxFileInfoName\" dojoAttachPoint=\"nameNode\"></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td class=\"dojoxFileInfoLabel dojoxFileInfoPathLabel\">${_messages.path}</td>\n\t\t\t\t<td class=\"dojoxFileInfoPath\" dojoAttachPoint=\"pathNode\"></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td class=\"dojoxFileInfoLabel dojoxFileInfoSizeLabel\">${_messages.size}</td>\n\t\t\t\t<td class=\"dojoxFileInfoSize\" dojoAttachPoint=\"sizeNode\"></td>\n\t\t\t</tr>\n\t\t</tbody>\n\t</table>\n\t<div dojoAttachPoint=\"containerNode\" style=\"display:none;\"></div>\n</div>\n",postMixInProperties:function(){ this._messages=dojo.i18n.getLocalization("dojox.widget","FilePicker",this.lang); this.inherited(arguments); },onItems:function(){ var _1=this.store,_2=this.items[0]; if(!_2){ this._onError("Load",new Error("No item defined")); }else{ this.nameNode.innerHTML=_1.getLabel(_2); this.pathNode.innerHTML=_1.getIdentity(_2); this.sizeNode.innerHTML=_1.getValue(_2,"size"); this.parentWidget.scrollIntoView(this); this.inherited(arguments); } }}); dojo.declare("dojox.widget.FilePicker",dojox.widget.RollingList,{className:"dojoxFilePicker",pathSeparator:"",topDir:"",parentAttr:"parentDir",pathAttr:"path",preloadItems:50,selectDirectories:true,selectFiles:true,_itemsMatch:function(_3,_4){ if(!_3&&!_4){ return true; }else{ if(!_3||!_4){ return false; }else{ if(_3==_4){ return true; }else{ if(this._isIdentity){ var _5=[this.store.getIdentity(_3),this.store.getIdentity(_4)]; dojo.forEach(_5,function(i,_7){ if(i.lastIndexOf(this.pathSeparator)==(i.length-1)){ _5[_7]=i.substring(0,i.length-1); }else{ } },this); return (_5[0]==_5[1]); } } } } return false; },startup:function(){ if(this._started){ return; } this.inherited(arguments); var _8,_9=this.getChildren()[0]; var _a=dojo.hitch(this,function(){ if(_8){ this.disconnect(_8); } delete _8; var _b=_9.items[0]; if(_b){ var _c=this.store; var _d=_c.getValue(_b,this.parentAttr); var _e=_c.getValue(_b,this.pathAttr); this.pathSeparator=this.pathSeparator||_c.pathSeparator; if(!this.pathSeparator){ this.pathSeparator=_e.substring(_d.length,_d.length+1); } if(!this.topDir){ this.topDir=_d; if(this.topDir.lastIndexOf(this.pathSeparator)!=(this.topDir.length-1)){ this.topDir+=this.pathSeparator; } } } }); if(!this.pathSeparator||!this.topDir){ if(!_9.items){ _8=this.connect(_9,"onItems",_a); }else{ _a(); } } },getChildItems:function(_f){ var ret=this.inherited(arguments); if(!ret&&this.store.getValue(_f,"directory")){ ret=[]; } return ret; },getMenuItemForItem:function(_11,_12,_13){ var _14={iconClass:"dojoxDirectoryItemIcon"}; if(!this.store.getValue(_11,"directory")){ _14.iconClass="dojoxFileItemIcon"; var l=this.store.getLabel(_11),idx=l.lastIndexOf("."); if(idx>=0){ _14.iconClass+=" dojoxFileItemIcon_"+l.substring(idx+1); } if(!this.selectFiles){ _14.disabled=true; } } var ret=new dijit.MenuItem(_14); return ret; },getPaneForItem:function(_18,_19,_1a){ var ret=null; if(!_18||(this.store.isItem(_18)&&this.store.getValue(_18,"directory"))){ ret=new dojox.widget._RollingListGroupPane({}); }else{ if(this.store.isItem(_18)&&!this.store.getValue(_18,"directory")){ ret=new dojox.widget._FileInfoPane({}); } } return ret; },_setPathValueAttr:function(_1c,_1d,_1e){ if(!_1c){ this.attr("value",null); return; } if(_1c.lastIndexOf(this.pathSeparator)==(_1c.length-1)){ _1c=_1c.substring(0,_1c.length-1); } this.store.fetchItemByIdentity({identity:_1c,onItem:function(v){ if(_1d){ this._lastExecutedValue=v; } this.attr("value",v); if(_1e){ _1e(); } },scope:this}); },_getPathValueAttr:function(val){ if(!val){ val=this.value; } if(val&&this.store.isItem(val)){ return this.store.getValue(val,this.pathAttr); }else{ return ""; } },_setValue:function(_21){ delete this._setInProgress; var _22=this.store; if(_21&&_22.isItem(_21)){ var _23=this.store.getValue(_21,"directory"); if((_23&&!this.selectDirectories)||(!_23&&!this.selectFiles)){ return; } }else{ _21=null; } if(!this._itemsMatch(this.value,_21)){ this.value=_21; this._onChange(_21); } }}); }
module.exports = { all : ['frontend/app/**/*.js'], options: { jshintrc : '.jshintrc' } };
(function($){ $.fn.go_top = function(params){ var defaults = { "top":200, "in":200, "out":200, "duration":400, }; var options = jQuery.extend(defaults, params); var go_top = $(this); $(window).on('load scroll', function(){ if ($(this).scrollTop() > options.top) { go_top.css({'display':'inline'}) } else { go_top.fadeOut(options.out); } }); return go_top.click(function(event) { event.preventDefault(); $('html, body').animate({scrollTop: 0}, options.duration); }); }; }( jQuery ));
Eatsery = new Mongo.Collection('eatsery');
define([ 'backbone', 'moment', 'underscore', 'find/app/util/array-equality', 'find/app/model/dates-filter-model' ], function(Backbone, moment, _, arraysEqual, DatesFilterModel) { "use strict"; /** * Models representing the state of a search. * @typedef {Object} QueryState * @property {DatesFilterModel} datesFilterModel Contains the date restrictions * @property {Backbone.Model} queryTextModel Contains the input text and related concepts * @property {Backbone.Collection} selectedIndexes * @property {Backbone.Collection} selectedParametricValues */ /** * The attributes saved on a saved search model. * @typedef {Object} SavedSearchModelAttributes * @property {String} title * @property {String} queryText * @property {String[][]} relatedConcepts * @property {{name: String, domain: String}[]} indexes * @property {{field: String, value: String}[]} parametricValues * @property {{field: String, min: Number, max: Number, type: String}[]} parametricRanges * @property {Integer} minScore * @property {Moment} minDate * @property {Moment} maxDate * @property {Moment} dateModified * @property {Moment} dateCreated * @property {DateRange} dateRange */ var DATE_FIELDS = [ 'minDate', 'maxDate', 'dateCreated', 'dateModified', 'dateNewDocsLastFetched' ]; /** * @readonly * @enum {String} */ var Type = { QUERY: 'QUERY', SNAPSHOT: 'SNAPSHOT' }; function parseParametricRestrictions(models) { var parametricValues = []; var parametricRanges = []; models.forEach(function (model) { if (model.has('value')) { parametricValues.push({ field: model.get('field'), value: model.get('value') }); } else if (model.has('range')) { parametricRanges.push({ field: model.get('field'), min: model.get('range')[0], max: model.get('range')[1], type: model.get('dataType') === 'numeric' ? 'Numeric' : 'Date' }); } }); return { parametricValues: parametricValues, parametricRanges: parametricRanges }; } function nullOrUndefined(input) { return input === null || input === undefined; } var optionalMomentsEqual = optionalEqual(function(optionalMoment1, optionalMoment2) { return optionalMoment1.isSame(optionalMoment2); }); var optionalExactlyEqual = optionalEqual(function(optionalItem1, optionalItem2) { return optionalItem1 === optionalItem2; }); // Treat as equal if they are both either null or undefined, or pass a regular equality test function optionalEqual(equalityTest) { return function(optionalItem1, optionalItem2) { if (nullOrUndefined(optionalItem1)) { return nullOrUndefined(optionalItem2); } else if (nullOrUndefined(optionalItem2)) { return false; } else { return equalityTest(optionalItem1, optionalItem2); } }; } var arrayEqualityPredicate = _.partial(arraysEqual, _, _, _.isEqual); // TODO: Remove this when toResourceIdentifiers consistently returns null for domains against IDOL function selectedIndexToResourceIdentifier(selectedIndex) { // Selected indexes against IDOL are either null, undefined or the empty string; normalize to null here return {name: selectedIndex.name, domain: selectedIndex.domain || null}; } function relatedConceptsToClusterModel(relatedConcepts, clusterId) { if(!relatedConcepts.length) { return null; } return _.map(relatedConcepts, function(concept, index) { return { clusterId: clusterId, phrase: concept, primary: index === 0 }; }); } return Backbone.Model.extend({ defaults: { queryText: null, title: null, indexes: [], parametricValues: [], parametricRanges: [], relatedConcepts: [], minDate: null, maxDate: null, newDocuments: 0, dateRange: null, dateNewDocsLastFetched: null, minScore: 0 }, parse: function(response) { var dateAttributes = _.mapObject(_.pick(response, DATE_FIELDS), function(value) { return value && moment(value); }); var relatedConcepts = _.chain(response.conceptClusterPhrases) .groupBy('clusterId') .map(function(clusterPhrases) { return _.chain(clusterPhrases) .sortBy('primary') .reverse() .pluck('phrase') .value(); }) .value(); // group token strings by type var tokensByType = _.chain(response.stateTokens) .groupBy('type') .mapObject(function(arr) { return _.pluck(arr, 'stateToken'); }) .value(); return _.defaults(dateAttributes, {queryStateTokens: tokensByType.QUERY}, {promotionsStateTokens: tokensByType.PROMOTIONS}, {relatedConcepts: relatedConcepts}, response); }, toJSON: function() { return _.defaults({ conceptClusterPhrases: _.flatten(this.get('relatedConcepts').map(relatedConceptsToClusterModel)) }, Backbone.Model.prototype.toJSON.call(this)); }, destroy: function(options) { return Backbone.Model.prototype.destroy.call(this, _.extend(options || options, { // The server returns an empty body (ie: not JSON) // TODO: check for collision of names dataType: 'text' })); }, /** * Does this model represent the same search as the given query state? * @param {QueryState} queryState * @return {Boolean} */ equalsQueryState: function(queryState) { var selectedIndexes = _.map(queryState.selectedIndexes.toResourceIdentifiers(), selectedIndexToResourceIdentifier); var parametricRestrictions = parseParametricRestrictions(queryState.selectedParametricValues); return this.get('queryText') === queryState.queryTextModel.get('inputText') && this.equalsQueryStateDateFilters(queryState) && arraysEqual(this.get('relatedConcepts'), queryState.queryTextModel.get('relatedConcepts'), arrayEqualityPredicate) && arraysEqual(this.get('indexes'), selectedIndexes, _.isEqual) && this.get('minScore') === queryState.minScoreModel.get('minScore') && arraysEqual(this.get('parametricValues'), parametricRestrictions.parametricValues, _.isEqual) && arraysEqual(this.get('parametricRanges'), parametricRestrictions.parametricRanges, _.isEqual); }, equalsQueryStateDateFilters: function(queryState) { var datesAttributes = queryState.datesFilterModel.toQueryModelAttributes(); if(this.get('dateRange') === DatesFilterModel.DateRange.CUSTOM) { return this.get('dateRange') === datesAttributes.dateRange && optionalMomentsEqual(this.get('minDate'), datesAttributes.minDate) && optionalMomentsEqual(this.get('maxDate'), datesAttributes.maxDate); } else { return optionalExactlyEqual(this.get('dateRange'), datesAttributes.dateRange); } }, toDatesFilterModelAttributes: function() { var minDate = this.get('minDate'); var maxDate = this.get('maxDate'); return { dateRange: this.get('dateRange'), customMinDate: minDate, customMaxDate: maxDate, dateNewDocsLastFetched: this.get('dateNewDocsLastFetched') }; }, toQueryTextModelAttributes: function() { return { inputText: this.get('queryText'), relatedConcepts: this.get('relatedConcepts') }; }, toMinScoreModelAttributes: function() { return this.pick('minScore'); }, toSelectedParametricValues: function() { return this.get('parametricValues').concat(this.get('parametricRanges').map(function (range) { return { field: range.field, range: [range.min, range.max], dataType: range.type === 'Numeric' ? 'numeric' : 'date', // TODO: Replace numeric with the more expressive dataType numeric: range.type === 'Numeric' }; })); }, toSelectedIndexes: function() { return this.get('indexes'); } }, { Type: Type, /** * Build saved search model attributes from the given query state models. * @param {QueryState} queryState * @return {SavedSearchModelAttributes} */ attributesFromQueryState: function(queryState) { var indexes = _.map(queryState.selectedIndexes.toResourceIdentifiers(), selectedIndexToResourceIdentifier); var parametricRestrictions = parseParametricRestrictions(queryState.selectedParametricValues); return _.extend( { queryText: queryState.queryTextModel.get('inputText'), relatedConcepts: queryState.queryTextModel.get('relatedConcepts'), indexes: indexes, parametricValues: parametricRestrictions.parametricValues, parametricRanges: parametricRestrictions.parametricRanges, minScore: queryState.minScoreModel.get('minScore') }, queryState.datesFilterModel.toQueryModelAttributes(), { dateNewDocsLastFetched: moment(), dateDocsLastFetched: moment() } ); } }); });
import { create, visitable } from 'ember-cli-page-object'; import details from './components/program-year/details'; import overview from './components/program-year/overview'; import header from './components/program-year/header'; export default create({ visit: visitable('/programs/:programId/programyears/:programYearId'), details, overview, header, });
var Bob = require('./bob.js'); describe('Bob', function() { var bob = new Bob(); it('stating something', function() { var result = bob.hey('Tom-ay-to, tom-aaaah-to.'); expect(result).toEqual('Whatever.'); }); xit('shouting', function() { var result = bob.hey('WATCH OUT!'); expect(result).toEqual('Whoa, chill out!'); }); xit('asking a question', function() { var result = bob.hey('Does this cryogenic chamber make me look fat?'); expect(result).toEqual('Sure.'); }); xit('talking forcefully', function() { var result = bob.hey('Let\'s go make out behind the gym!'); expect(result).toEqual('Whatever.'); }); xit('using acronyms in regular speech', function() { var result = bob.hey('It\'s OK if you don\'t want to go to the DMV.'); expect(result).toEqual('Whatever.'); }); xit('forceful questions', function() { var result = bob.hey('WHAT THE HELL WERE YOU THINKING?'); expect(result).toEqual('Whoa, chill out!'); }); xit('shouting numbers', function() { var result = bob.hey('1, 2, 3 GO!'); expect(result).toEqual('Whoa, chill out!'); }); xit('only numbers', function() { var result = bob.hey('1, 2, 3'); expect(result).toEqual('Whatever.'); }); xit('question with only numbers', function() { var result = bob.hey('4?'); expect(result).toEqual('Sure.'); }); xit('shouting with special characters', function() { var result = bob.hey('ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!'); expect(result).toEqual('Whoa, chill out!'); }); xit('shouting with umlauts', function() { // NOTE: "\xfcML\xe4\xdcTS" === "üMLäÜTS" var result = bob.hey('\xdcML\xc4\xdcTS!'); expect(result).toEqual('Whoa, chill out!'); }); xit('calmly speaking about umlauts', function() { var result = bob.hey('\xfcML\xe4\xdcTS'); expect(result).toEqual('Whatever.'); }); xit('shouting with no exclamation mark', function () { var result = bob.hey('I HATE YOU'); expect(result).toEqual('Whoa, chill out!'); }); xit('statement containing question mark', function() { var result = bob.hey('Ending with a ? means a question.'); expect(result).toEqual('Whatever.'); }); xit('prattling on', function () { var result = bob.hey('Wait! Hang on. Are you going to be OK?'); expect(result).toEqual('Sure.'); }); xit('silence', function () { var result = bob.hey(''); expect(result).toEqual('Fine. Be that way!'); }); xit('prolonged silence', function () { var result = bob.hey(' '); expect(result).toEqual('Fine. Be that way!'); }); });
(function() { angular.module('builder', ['builder.directive']); }).call(this);
import run from "ember-metal/run_loop"; import Namespace from 'ember-runtime/system/namespace'; import { Registry } from "ember-runtime/system/container"; import EmberView from "ember-views/views/view"; import ObjectProxy from "ember-runtime/system/object_proxy"; import EmberObject from "ember-runtime/system/object"; import _MetamorphView from 'ember-views/views/metamorph_view'; import compile from "ember-template-compiler/system/compile"; import { set } from 'ember-metal/property_set'; import { fmt } from 'ember-runtime/system/string'; import { typeOf } from 'ember-metal/utils'; import { forEach } from 'ember-metal/enumerable_utils'; import { runAppend, runDestroy } from "ember-runtime/tests/utils"; var originalLookup = Ember.lookup; var view, lookup, registry, container, TemplateTests; QUnit.module("ember-htmlbars: {{#if}} and {{#unless}} helpers", { setup: function() { Ember.lookup = lookup = {}; lookup.TemplateTests = TemplateTests = Namespace.create(); registry = new Registry(); container = registry.container(); registry.optionsForType('template', { instantiate: false }); registry.register('view:default', _MetamorphView); registry.register('view:toplevel', EmberView.extend()); }, teardown: function() { runDestroy(container); runDestroy(view); registry = container = view = null; Ember.lookup = lookup = originalLookup; TemplateTests = null; } }); test("unless should keep the current context (#784) [DEPRECATED]", function() { view = EmberView.create({ o: EmberObject.create({ foo: '42' }), template: compile('{{#with view.o}}{{#view}}{{#unless view.doesNotExist}}foo: {{foo}}{{/unless}}{{/view}}{{/with}}') }); expectDeprecation(function() { runAppend(view); }, 'Using the context switching form of `{{with}}` is deprecated. Please use the keyword form (`{{with foo as bar}}`) instead.'); equal(view.$().text(), 'foo: 42'); }); test("The `if` helper tests for `isTruthy` if available", function() { view = EmberView.create({ truthy: EmberObject.create({ isTruthy: true }), falsy: EmberObject.create({ isTruthy: false }), template: compile('{{#if view.truthy}}Yep{{/if}}{{#if view.falsy}}Nope{{/if}}') }); runAppend(view); equal(view.$().text(), 'Yep'); }); test("The `if` helper does not error on undefined", function() { view = EmberView.create({ undefinedValue: undefined, template: compile('{{#if view.undefinedValue}}Yep{{/if}}{{#unbound if view.undefinedValue}}Yep{{/unbound}}') }); runAppend(view); equal(view.$().text(), ''); }); test("The `unless` helper does not error on undefined", function() { view = EmberView.create({ undefinedValue: undefined, template: compile('{{#unless view.undefinedValue}}YepBound{{/unless}}{{#unbound unless view.undefinedValue}}YepUnbound{{/unbound}}') }); runAppend(view); equal(view.$().text(), 'YepBoundYepUnbound'); }); test("The `if` helper does not print the contents for an object proxy without content", function() { view = EmberView.create({ truthy: ObjectProxy.create({ content: {} }), falsy: ObjectProxy.create({ content: null }), template: compile('{{#if view.truthy}}Yep{{/if}}{{#if view.falsy}}Nope{{/if}}') }); runAppend(view); equal(view.$().text(), 'Yep'); }); test("The `if` helper updates if an object proxy gains or loses context", function() { view = EmberView.create({ proxy: ObjectProxy.create({ content: null }), template: compile('{{#if view.proxy}}Yep{{/if}}') }); runAppend(view); equal(view.$().text(), ''); run(function() { view.set('proxy.content', {}); }); equal(view.$().text(), 'Yep'); run(function() { view.set('proxy.content', null); }); equal(view.$().text(), ''); }); test("The `if` helper updates if an array is empty or not", function() { view = EmberView.create({ array: Ember.A(), template: compile('{{#if view.array}}Yep{{/if}}') }); runAppend(view); equal(view.$().text(), ''); run(function() { view.get('array').pushObject(1); }); equal(view.$().text(), 'Yep'); run(function() { view.get('array').removeObject(1); }); equal(view.$().text(), ''); }); test("The `if` helper updates when the value changes", function() { view = EmberView.create({ conditional: true, template: compile('{{#if view.conditional}}Yep{{/if}}') }); runAppend(view); equal(view.$().text(), 'Yep'); run(function() { view.set('conditional', false); }); equal(view.$().text(), ''); }); test("The `unbound if` helper does not update when the value changes", function() { view = EmberView.create({ conditional: true, template: compile('{{#unbound if view.conditional}}Yep{{/unbound}}') }); runAppend(view); equal(view.$().text(), 'Yep'); run(function() { view.set('conditional', false); }); equal(view.$().text(), 'Yep'); }); test("The `unless` helper updates when the value changes", function() { view = EmberView.create({ conditional: false, template: compile('{{#unless view.conditional}}Nope{{/unless}}') }); runAppend(view); equal(view.$().text(), 'Nope'); run(function() { view.set('conditional', true); }); equal(view.$().text(), ''); }); test("The `unbound if` helper does not update when the value changes", function() { view = EmberView.create({ conditional: false, template: compile('{{#unbound unless view.conditional}}Nope{{/unbound}}') }); runAppend(view); equal(view.$().text(), 'Nope'); run(function() { view.set('conditional', true); }); equal(view.$().text(), 'Nope'); }); test("The `unbound if` helper should work when its inverse is not present", function() { view = EmberView.create({ conditional: false, template: compile('{{#unbound if view.conditional}}Yep{{/unbound}}') }); runAppend(view); equal(view.$().text(), ''); }); test("The `if` helper ignores a controller option", function() { var lookupCalled = false; view = EmberView.create({ container: { lookup: function() { lookupCalled = true; } }, truthy: true, template: compile('{{#if view.truthy controller="foo"}}Yep{{/if}}') }); runAppend(view); equal(lookupCalled, false, 'controller option should NOT be used'); }); test('should not rerender if truthiness does not change', function() { var renderCount = 0; view = EmberView.create({ template: compile('<h1 id="first">{{#if view.shouldDisplay}}{{view view.InnerViewClass}}{{/if}}</h1>'), shouldDisplay: true, InnerViewClass: EmberView.extend({ template: compile('bam'), render: function() { renderCount++; return this._super.apply(this, arguments); } }) }); runAppend(view); equal(renderCount, 1, 'precond - should have rendered once'); equal(view.$('#first').text(), 'bam', 'renders block when condition is true'); run(function() { set(view, 'shouldDisplay', 1); }); equal(renderCount, 1, 'should not have rerendered'); equal(view.$('#first').text(), 'bam', 'renders block when condition is true'); }); test('should update the block when object passed to #unless helper changes', function() { registry.register('template:advice', compile('<h1>{{#unless view.onDrugs}}{{view.doWellInSchool}}{{/unless}}</h1>')); view = EmberView.create({ container: container, templateName: 'advice', onDrugs: true, doWellInSchool: 'Eat your vegetables' }); runAppend(view); equal(view.$('h1').text(), '', 'hides block if true'); var tests = [false, null, undefined, [], '', 0]; forEach(tests, function(val) { run(function() { set(view, 'onDrugs', val); }); equal(view.$('h1').text(), 'Eat your vegetables', fmt('renders block when conditional is "%@"; %@', [String(val), typeOf(val)])); run(function() { set(view, 'onDrugs', true); }); equal(view.$('h1').text(), '', 'precond - hides block when conditional is true'); }); }); test('properties within an if statement should not fail on re-render', function() { view = EmberView.create({ template: compile('{{#if view.value}}{{view.value}}{{/if}}'), value: null }); runAppend(view); equal(view.$().text(), ''); run(function() { view.set('value', 'test'); }); equal(view.$().text(), 'test'); run(function() { view.set('value', null); }); equal(view.$().text(), ''); }); test('should update the block when object passed to #if helper changes', function() { registry.register('template:menu', compile('<h1>{{#if view.inception}}{{view.INCEPTION}}{{/if}}</h1>')); view = EmberView.create({ container: container, templateName: 'menu', INCEPTION: 'BOOOOOOOONG doodoodoodoodooodoodoodoo', inception: 'OOOOoooooOOOOOOooooooo' }); runAppend(view); equal(view.$('h1').text(), 'BOOOOOOOONG doodoodoodoodooodoodoodoo', 'renders block if a string'); var tests = [false, null, undefined, [], '', 0]; forEach(tests, function(val) { run(function() { set(view, 'inception', val); }); equal(view.$('h1').text(), '', fmt('hides block when conditional is "%@"', [String(val)])); run(function() { set(view, 'inception', true); }); equal(view.$('h1').text(), 'BOOOOOOOONG doodoodoodoodooodoodoodoo', 'precond - renders block when conditional is true'); }); }); test('should update the block when object passed to #if helper changes and an inverse is supplied', function() { registry.register('template:menu', compile('<h1>{{#if view.inception}}{{view.INCEPTION}}{{else}}{{view.SAD}}{{/if}}</h1>')); view = EmberView.create({ container: container, templateName: 'menu', INCEPTION: 'BOOOOOOOONG doodoodoodoodooodoodoodoo', inception: false, SAD: 'BOONG?' }); runAppend(view); equal(view.$('h1').text(), 'BOONG?', 'renders alternate if false'); run(function() { set(view, 'inception', true); }); var tests = [false, null, undefined, [], '', 0]; forEach(tests, function(val) { run(function() { set(view, 'inception', val); }); equal(view.$('h1').text(), 'BOONG?', fmt('renders alternate if %@', [String(val)])); run(function() { set(view, 'inception', true); }); equal(view.$('h1').text(), 'BOOOOOOOONG doodoodoodoodooodoodoodoo', 'precond - renders block when conditional is true'); }); }); test('views within an if statement should be sane on re-render', function() { view = EmberView.create({ template: compile('{{#if view.display}}{{input}}{{/if}}'), display: false }); runAppend(view); equal(view.$('input').length, 0); run(function() { // Setting twice will trigger the observer twice, this is intentional view.set('display', true); view.set('display', 'yes'); }); var textfield = view.$('input'); equal(textfield.length, 1); // Make sure the view is still registered in View.views ok(EmberView.views[textfield.attr('id')]); }); test('the {{this}} helper should not fail on removal', function() { view = EmberView.create({ context: 'abc', template: compile('{{#if view.show}}{{this}}{{/if}}'), show: true }); runAppend(view); equal(view.$().text(), 'abc', 'should start property - precond'); run(function() { view.set('show', false); }); equal(view.$().text(), ''); }); test('should update the block when object passed to #unless helper changes', function() { registry.register('template:advice', compile('<h1>{{#unless view.onDrugs}}{{view.doWellInSchool}}{{/unless}}</h1>')); view = EmberView.create({ container: container, templateName: 'advice', onDrugs: true, doWellInSchool: 'Eat your vegetables' }); runAppend(view); equal(view.$('h1').text(), '', 'hides block if true'); var tests = [false, null, undefined, [], '', 0]; forEach(tests, function(val) { run(function() { set(view, 'onDrugs', val); }); equal(view.$('h1').text(), 'Eat your vegetables', fmt('renders block when conditional is "%@"; %@', [String(val), typeOf(val)])); run(function() { set(view, 'onDrugs', true); }); equal(view.$('h1').text(), '', 'precond - hides block when conditional is true'); }); }); test('properties within an if statement should not fail on re-render', function() { view = EmberView.create({ template: compile('{{#if view.value}}{{view.value}}{{/if}}'), value: null }); runAppend(view); equal(view.$().text(), ''); run(function() { view.set('value', 'test'); }); equal(view.$().text(), 'test'); run(function() { view.set('value', null); }); equal(view.$().text(), ''); }); test('should update the block when object passed to #if helper changes', function() { registry.register('template:menu', compile('<h1>{{#if view.inception}}{{view.INCEPTION}}{{/if}}</h1>')); view = EmberView.create({ container: container, templateName: 'menu', INCEPTION: 'BOOOOOOOONG doodoodoodoodooodoodoodoo', inception: 'OOOOoooooOOOOOOooooooo' }); runAppend(view); equal(view.$('h1').text(), 'BOOOOOOOONG doodoodoodoodooodoodoodoo', 'renders block if a string'); var tests = [false, null, undefined, [], '', 0]; forEach(tests, function(val) { run(function() { set(view, 'inception', val); }); equal(view.$('h1').text(), '', fmt('hides block when conditional is "%@"', [String(val)])); run(function() { set(view, 'inception', true); }); equal(view.$('h1').text(), 'BOOOOOOOONG doodoodoodoodooodoodoodoo', 'precond - renders block when conditional is true'); }); }); test('should update the block when object passed to #if helper changes and an inverse is supplied', function() { registry.register('template:menu', compile('<h1>{{#if view.inception}}{{view.INCEPTION}}{{else}}{{view.SAD}}{{/if}}</h1>')); view = EmberView.create({ container: container, templateName: 'menu', INCEPTION: 'BOOOOOOOONG doodoodoodoodooodoodoodoo', inception: false, SAD: 'BOONG?' }); runAppend(view); equal(view.$('h1').text(), 'BOONG?', 'renders alternate if false'); run(function() { set(view, 'inception', true); }); var tests = [false, null, undefined, [], '', 0]; forEach(tests, function(val) { run(function() { set(view, 'inception', val); }); equal(view.$('h1').text(), 'BOONG?', fmt('renders alternate if %@', [String(val)])); run(function() { set(view, 'inception', true); }); equal(view.$('h1').text(), 'BOOOOOOOONG doodoodoodoodooodoodoodoo', 'precond - renders block when conditional is true'); }); }); test('the {{this}} helper should not fail on removal', function() { view = EmberView.create({ context: 'abc', template: compile('{{#if view.show}}{{this}}{{/if}}'), show: true }); runAppend(view); equal(view.$().text(), 'abc', 'should start property - precond'); run(function() { view.set('show', false); }); equal(view.$().text(), ''); }); test('edge case: child conditional should not render children if parent conditional becomes false', function() { var childCreated = false; var child = null; view = EmberView.create({ cond1: true, cond2: false, viewClass: EmberView.extend({ init: function() { this._super.apply(this, arguments); childCreated = true; child = this; } }), template: compile('{{#if view.cond1}}{{#if view.cond2}}{{#view view.viewClass}}test{{/view}}{{/if}}{{/if}}') }); runAppend(view); ok(!childCreated, 'precondition'); run(function() { // The order of these sets is important for the test view.set('cond2', true); view.set('cond1', false); }); // TODO: Priority Queue, for now ensure correct result. //ok(!childCreated, 'child should not be created'); ok(child.isDestroyed, 'child should be gone'); equal(view.$().text(), ''); }); test('edge case: rerender appearance of inner virtual view', function() { view = EmberView.create({ tagName: '', cond2: false, template: compile('{{#if view.cond2}}test{{/if}}') }); runAppend(view); equal(Ember.$('#qunit-fixture').text(), ''); run(function() { view.set('cond2', true); }); equal(Ember.$('#qunit-fixture').text(), 'test'); }); if (Ember.FEATURES.isEnabled('ember-htmlbars-inline-if-helper')) { test("`if` helper with inline form: renders the second argument when conditional is truthy", function() { view = EmberView.create({ conditional: true, template: compile('{{if view.conditional "truthy" "falsy"}}') }); runAppend(view); equal(view.$().text(), 'truthy'); }); test("`if` helper with inline form: renders the third argument when conditional is falsy", function() { view = EmberView.create({ conditional: false, template: compile('{{if view.conditional "truthy" "falsy"}}') }); runAppend(view); equal(view.$().text(), 'falsy'); }); test("`if` helper with inline form: can omit the falsy argument", function() { view = EmberView.create({ conditional: true, template: compile('{{if view.conditional "truthy"}}') }); runAppend(view); equal(view.$().text(), 'truthy'); }); test("`if` helper with inline form: can omit the falsy argument and renders nothing when conditional is falsy", function() { view = EmberView.create({ conditional: false, template: compile('{{if view.conditional "truthy"}}') }); runAppend(view); equal(view.$().text(), ''); }); test("`if` helper with inline form: truthy and falsy arguments are changed if conditional changes", function() { view = EmberView.create({ conditional: true, template: compile('{{if view.conditional "truthy" "falsy"}}') }); runAppend(view); equal(view.$().text(), 'truthy'); run(function() { view.set('conditional', false); }); equal(view.$().text(), 'falsy'); }); test("`if` helper with inline form: can use truthy param as binding", function() { view = EmberView.create({ truthy: 'ok', conditional: true, template: compile('{{if view.conditional view.truthy}}') }); runAppend(view); equal(view.$().text(), 'ok'); run(function() { view.set('truthy', 'yes'); }); equal(view.$().text(), 'yes'); }); test("`if` helper with inline form: can use falsy param as binding", function() { view = EmberView.create({ truthy: 'ok', falsy: 'boom', conditional: false, template: compile('{{if view.conditional view.truthy view.falsy}}') }); runAppend(view); equal(view.$().text(), 'boom'); run(function() { view.set('falsy', 'no'); }); equal(view.$().text(), 'no'); }); test("`if` helper with inline form: raises when using more than three arguments", function() { view = EmberView.create({ conditional: true, template: compile('{{if one two three four}}') }); expectAssertion(function() { runAppend(view); }, /The inline form of the `if` and `unless` helpers expect two or three arguments/); }); test("`if` helper with inline form: raises when using less than two arguments", function() { view = EmberView.create({ conditional: true, template: compile('{{if one}}') }); expectAssertion(function() { runAppend(view); }, /The inline form of the `if` and `unless` helpers expect two or three arguments/); }); test("`if` helper with inline form: works when used in a sub expression", function() { view = EmberView.create({ conditional: true, innerConditional: true, template: compile('{{if view.conditional (if view.innerConditional "truthy" )}}') }); runAppend(view); equal(view.$().text(), 'truthy'); }); test("`if` helper with inline form: updates if condition changes in a sub expression", function() { view = EmberView.create({ conditional: true, innerConditional: true, template: compile('{{if view.conditional (if view.innerConditional "innerTruthy" "innerFalsy")}}') }); runAppend(view); equal(view.$().text(), 'innerTruthy'); run(function() { view.set('innerConditional', false); }); equal(view.$().text(), 'innerFalsy'); }); test("`if` helper with inline form: can use truthy param as binding in a sub expression", function() { view = EmberView.create({ conditional: true, innerConditional: true, innerTruthy: "innerTruthy", template: compile('{{if view.conditional (if view.innerConditional view.innerTruthy)}}') }); runAppend(view); equal(view.$().text(), 'innerTruthy'); run(function() { view.set('innerTruthy', 'innerOk'); }); equal(view.$().text(), 'innerOk'); }); test("`if` helper with inline form: respects isTruthy when object changes", function() { view = EmberView.create({ conditional: Ember.Object.create({ isTruthy: false }), template: compile('{{if view.conditional "truthy" "falsy"}}') }); runAppend(view); equal(view.$().text(), 'falsy'); run(function() { view.set('conditional', Ember.Object.create({ isTruthy: true })); }); equal(view.$().text(), 'truthy'); run(function() { view.set('conditional', Ember.Object.create({ isTruthy: false })); }); equal(view.$().text(), 'falsy'); }); test("`if` helper with inline form: respects isTruthy when property changes", function() { var candidate = Ember.Object.create({ isTruthy: false }); view = EmberView.create({ conditional: candidate, template: compile('{{if view.conditional "truthy" "falsy"}}') }); runAppend(view); equal(view.$().text(), 'falsy'); run(function() { candidate.set('isTruthy', true); }); equal(view.$().text(), 'truthy'); run(function() { candidate.set('isTruthy', false); }); equal(view.$().text(), 'falsy'); }); test("`if` helper with inline form: respects length test when list content changes", function() { var list = Ember.A(); view = EmberView.create({ conditional: list, template: compile('{{if view.conditional "truthy" "falsy"}}') }); runAppend(view); equal(view.$().text(), 'falsy'); run(function() { list.pushObject(1); }); equal(view.$().text(), 'truthy'); run(function() { list.replace(0, 1); }); equal(view.$().text(), 'falsy'); }); test("`if` helper with inline form: respects length test when list itself", function() { view = EmberView.create({ conditional: [], template: compile('{{if view.conditional "truthy" "falsy"}}') }); runAppend(view); equal(view.$().text(), 'falsy'); run(function() { view.set('conditional', [1]); }); equal(view.$().text(), 'truthy'); run(function() { view.set('conditional', []); }); equal(view.$().text(), 'falsy'); }); }
const fs = require('fs-extra'); const path = require('path'); const tmpDir = path.join(__dirname, 'tmp'); const REAR_PROCESS_TEST = 'REAR_PROCESS_TEST'; const REAR_DOTENV_TEST = 'REAR_DOTENV_TEST'; const REAR_PACKAGE_TEST = 'REAR_PACKAGE_TEST'; const PKG_FILE = path.join(tmpDir, 'package.json'); const DOTENV_FILE = path.join(tmpDir, '.env'); describe('get-rear-env', () => { beforeEach(() => { fs.ensureDirSync(tmpDir); fs.writeFileSync(PKG_FILE, JSON.stringify({ name: 'get-rear-env-test', version: '0.1.0', private: true, dependencies: { 'rear-core': '^0.1.0' }, rear: { package: { test: 'REAR_PACKAGE_TEST' } } }, null, 2)); fs.writeFileSync(DOTENV_FILE, 'REAR_DOTENV_TEST=REAR_DOTENV_TEST'); process.env.REAR_PROCESS_TEST = REAR_PROCESS_TEST; process.env.NODE_ENV = 'test'; }); afterEach(() => { fs.removeSync(tmpDir); delete process.env.REAR_PROCESS_TEST; }); it('Should get rear-only environmet variables', () => { const expectedPropCount = 4; const root = process.cwd(); process.chdir(tmpDir); const env = require('../get-rear-env')(); const actualPropCount = Object.keys(env || {}).length; process.chdir(root); expect(actualPropCount).toEqual(expectedPropCount); expect(env.REAR_PROCESS_TEST).toEqual(REAR_PROCESS_TEST); expect(env.REAR_DOTENV_TEST).toEqual(REAR_DOTENV_TEST); expect(env.REAR_PACKAGE_TEST).toEqual(REAR_PACKAGE_TEST) expect(env.NODE_ENV).toEqual('test'); }); });
function ScampDashboard($scope) { var scope = $scope; //var ws = new ScampWebSocket(scope, "local", ""); var resourceUsageEscalationLevels = [ { maxUsage: 50, cssClass: "success" }, { maxUsage: 70, cssClass: "info" }, { maxUsage: 85, cssClass: "warning" }, { maxUsage: 101, cssClass: "danger" } ]; var chartsToRender = [ { fieldName: 'usageEscalation', domElement: 'usageDonutChart' }, { fieldName: 'groupName', domElement: 'groupDonutChart' }, { fieldName: 'resourceTypeDesc', domElement: 'typeDonutChart' }, { fieldName: 'stateDescription', domElement: 'stateDonutChart' } ]; /* ws.wsConnection.onmessage = function (msg) { var data = msg.data; if(data && scope.resources) this.updateRsrcScopeFromWSUpdate(data); };*/ this.updateRsrcScopeFromWSUpdate = function(msg){ //make sure that the user on the message is the same person logged in if (msg.resource && msg.user === scope.userProfile.id) this.processResourceUpdate(msg); else console.error('Received the following resource update without an resource ID'); } this.processResourceUpdate = function (modifiedRsc) { var resourceUpdated = false; scope.resources.map(function (item) { if (item.id === modifiedRsc.resource) { updateResouce(item, modifiedRsc.state); resourceUpdated = true; } }); //if the updated resource cannot be found on the scope, then refresh the dashboard by calling the service if (!resourceUpdated) scope.populate(); //else // renderCharts(scope.resources); }; var setResources = function(rspData){ scope.resources = rspData.filter(function (item) { return scope.rscStateDescMapping[item.state];//Make sure the state code is valid }).map(function (rsc) { updateResouce(rsc, rsc.state);//prepare and update the resource object on the scope to be rendered on the dashboard return rsc; }); }; var updateResouce = function(rsc, currentState){ var alertClassArr = resourceUsageEscalationLevels.filter(function (el) { return rsc.remaining < el.maxUsage; }); rsc.usageEscalation = alertClassArr && alertClassArr.length > 0 ? alertClassArr[0].cssClass : "danger"; rsc.groupName = rsc.resourceGroup.name; rsc.groupId = rsc.resourceGroup.id; rsc.state = currentState; rsc.stateDescription = scope.rscStateDescMapping[currentState].description; rsc.resourceTypeDesc = scope.resourceTypes[rsc.resourceType]; }; var renderCharts = function(rscs){ var groupBy = function (resources, groupField, cb) { return _.chain(resources).groupBy(groupField).map(cb); }; var renderChart = function (groupByField, cb, chartDomEl, resources) { var chartDataSrc = groupBy(resources, groupByField, cb).value(); Morris.Donut({ element: chartDomEl, data: chartDataSrc }); }; chartsToRender.forEach(function (item) { renderChart(item.fieldName, function (val, key) { return { label: key, value: val.length } }, item.domElement, rscs); }); }; this.render = function (rspData) { setResources(rspData); //renderCharts(scope.resources); scope.dashboardStatus = 'loaded'; } } ScampDashboard.prototype.initialize = function () { (function initGrid() { var table = $("table.table-hover"); if (table) { table.on('mouseover', 'td', function () { var idx = $(this).index(); var rows = $(this).closest('table').find('tr'); rows.each(function () { $(this).find('td:eq(' + idx + ')').addClass('beauty-hover'); }); }) .on('mouseleave', 'td', function (e) { var idx = $(this).index(); var rows = $(this).closest('table').find('tr'); rows.each(function () { $(this).find('td:eq(' + idx + ')').removeClass('beauty-hover'); }); }); } })(); }
lyrics(["head", "and", "toes"].concat(parts));
import FEATURE_TOGGLE from '../../src/feature-toggle'; export default class Vector { constructor(settings) { settings = settings || {}; settings.x = settings.x || 0; settings.y = settings.y || 0; settings.length = settings.length || 0; settings.angle = settings.angle || 0; this._x = settings.x; this._y = settings.y; if (settings.length) { this.setLength(settings.length); } if (settings.angle) { this.setAngle(settings.angle); } } setX(value) { this._x = value; } getX(value) { return this._x; } setY(value) { this._y = value; } getY(value) { return this._y; } setAngle(angle) { let length = this.getLength(); this._x = Math.cos(angle) * length; this._y = Math.sin(angle) * length; } getAngle() { return Math.atan2(this.getY(), this.getX()); } setLength(length) { let angle = this.getAngle(); this._x = Math.cos(angle) * length; this._y = Math.sin(angle) * length; } getLength() { return Math.sqrt(this._x * this._x + this._y * this._y); } add(vector) { return new Vector({ x: this._x + vector.getX(), y: this._y + vector.getY() }); } substract(vector) { return new Vector({ x: this._x - vector.getX(), y: this._y - vector.getY() }); } multiply(value) { return new Vector({ x: this._x * value, y: this._y * value }); } divide(value) { return new Vector({ x: this._x / value, y: this._y / value }); } addTo(vector) { this._x += vector.getX(); this._y += vector.getY(); } substractFrom(vector) { this._x -= vector.getX(); this._y -= vector.getY(); } multiplyBy(value) { this._x *= value; this._y *= value; } divideBy(value) { this._x /= value; this._y /= value; } dot(v) { return this._x*v._x + this._y*v._y; } cross(v) { return (this._x*v._y) - (this._y*v._x); } angleBetween(v) { //return Math.acos( (v1.x * v2.x + v1.y * v2.y) / ( Math.sqrt(v1.x*v1.x + v1.y*v1.y) * Math.sqrt(v2.x*v2.x + v2.y*v2.y) ) ) let v1 = this.copy(); let v2 = v.copy(); v1.normalize(); v2.normalize(); let dot = v1.dot(v2); let theta = Math.acos(dot); if (isNaN(theta)) { console.warn("Theta is 'NaN' on Vector.angleBetween()") } return theta; } angleDirection(v) { let crossProduct = this.cross(v); if (crossProduct > 0.0) { return 1; } else if (crossProduct < 0.0) { return -1; } else { return 0; } } angleDifference(v) { let theta = this.angleBetween(v); let dir = this.angleDirection(v); return theta * dir; } copy() { return new Vector({ x: this.getX(), y: this.getY() }); } normalize() { var length = this.getLength(); if (length != 0) { this.divideBy(length); } } dist(p) { let d = p.substract(this); return d.getLength(); } limit(n) { if (this.getLength() > n) { this.setLength(n); } } };
import { StyleSheet, Platform, } from 'react-native'; let webFixes = (Platform.OS === 'web') ? { listText: { }, } : {}; let iosFixes = (Platform.OS === 'ios') ? { layoutTabIconStyle: { }, } : {}; const styles = StyleSheet.create(Object.assign({ listTextContainer:{ flexDirection: 'row', overflow: 'hidden', }, }, webFixes)); export default styles;
exports.withoutBreaking = [ { closes: [], breaks: [], hash: '1d4f604363094d4eee3b4d7b1ca01133edaad344', subject: 'did one thing', body: '', type: 'fix', component: '$scope' }, { closes: [], breaks: [], hash: '1d4f604363094d4eee3b4d7b1ca01133edaad344', subject: 'did 2 thing', body: '', type: 'feat', component: '$scope' }, { closes: [], breaks: [], hash: '1d4f604363094d4eee3b4d7b1ca01133edaad344', subject: 'did 3 thing', body: '', type: 'refact', component: '$scope' }, { closes: [], breaks: [], hash: '1d4f604363094d4eee3b4d7b1ca01133edaad344', subject: 'did 4 thing', body: '', type: 'chore', component: '$scope' }, { closes: [], breaks: [], hash: '1d4f604363094d4eee3b4d7b1ca01133edaad344', subject: 'did 5 thing', body: '', type: 'chore', component: '$scope' }, { closes: [], breaks: [], hash: '1d4f604363094d4eee3b4d7b1ca01133edaad344', subject: 'did 6 thing', body: '', type: 'chore', component: '$scope' } ]; exports.withBreaking = [ { closes: [], breaks: [], hash: '1d4f604363094d4eee3b4d7b1ca01133edaad344', subject: 'did one thing', body: '', type: 'fix', component: '$scope' }, { closes: [], breaks: [], hash: '1d4f604363094d4eee3b4d7b1ca01133edaad344', subject: 'did 2 thing', body: '', type: 'feat', component: '$scope', breaking: true }, { closes: [], breaks: [], hash: '1d4f604363094d4eee3b4d7b1ca01133edaad344', subject: 'did 3 thing', body: '', type: 'refact', component: '$scope' }, { closes: [], breaks: [3, 4], hash: '1d4f604363094d4eee3b4d7b1ca01133edaad344', subject: 'did 4 thing', body: '', type: 'chore', component: '$scope' }, { closes: [], breaks: [2,3], hash: '1d4f604363094d4eee3b4d7b1ca01133edaad344', subject: 'did 5 thing', body: '', type: 'chore', component: '$scope' }, { closes: [], breaks: [], hash: '1d4f604363094d4eee3b4d7b1ca01133edaad344', subject: 'did 6 thing', body: '', type: 'chore', component: '$scope' } ];
var net = require('net'); var noble = require('noble'); var util = require('util'); var server = net.createServer(function(client) { client.vehicles = []; client.on("error", (err) => { console.log("connection error"); // client disconnected? client.vehicles.forEach((vehicle) => vehicle.disconnect()); }); client.on("data", function(data) { data.toString().split("\r\n").forEach(function(line) { var command = line.toString().trim().split(";"); if (command[0]) console.log(command) switch(command[0]) { case "SCAN": console.log(noble); if (noble.state === 'poweredOn') { var discover = function(device) { client.write(util.format("SCAN;%s;%s;%s\n", device.id, device.advertisement.manufacturerData.toString('hex'), new Buffer(device.advertisement.localName).toString('hex'))); }; noble.on('discover', discover); noble.startScanning(['be15beef6186407e83810bd89c4d8df4']); setTimeout(function() { noble.stopScanning(); noble.removeListener('discover', discover) client.write("SCAN;COMPLETED\n"); }, 2000); } else { client.write("SCAN;ERROR\n"); } break; case "CONNECT": console.log("connect begin"); if (command.length != 2) { client.write("CONNECT;ERROR\n"); break; } var vehicle = noble._peripherals[command[1]]; if (vehicle === undefined) { client.write("CONNECT;ERROR\n"); break; } var success = false; vehicle.connect(function(error) { vehicle.discoverSomeServicesAndCharacteristics( ["be15beef6186407e83810bd89c4d8df4"], ["be15bee06186407e83810bd89c4d8df4", "be15bee16186407e83810bd89c4d8df4"], function(error, services, characteristics) { vehicle.reader = characteristics.find(x => !x.properties.includes("write")); vehicle.writer = characteristics.find(x => x.properties.includes("write")); vehicle.reader.notify(true); vehicle.reader.on('read', function(data, isNotification) { client.write(util.format("%s;%s\n", vehicle.id, data.toString("hex"))); //console.log(util.format("%s;%s\n", vehicle.id, data.toString("hex"))); }); client.write("CONNECT;SUCCESS\n"); client.vehicles.push(vehicle); console.log("connect success"); success = true; } ); }); setTimeout(() => { if (!success) { client.write("CONNECT;ERROR\n"); console.log("connect error"); } }, 500); break; case "DISCONNECT": if (command.length != 2) { client.write("DISCONNECT;ERROR\n"); break; } var vehicle = noble._peripherals[command[1]]; if (vehicle === undefined) { client.write("DISCONNECT;ERROR\n"); break; } vehicle.disconnect(); client.write("DISCONNECT;SUCCESS\n"); break; default: if (command.length == 2 && noble._peripherals[command[0]] !== undefined) { var vehicle = noble._peripherals[command[0]]; vehicle.writer.write(new Buffer(command[1], 'hex')); } } }); }); }); server.listen(5000); console.log("Server gestartet")
var path = require('path'); module.exports = { root: [path.join(__dirname, '..')] };
(function() { var Query; Query = window._test.Query; describe('Query', function() { var query; query = null; beforeEach(function() { return query = new Query(2); }); describe('#initialize', function() { return it('sets the minLength property to the provided parameter', function() { return expect(query.minLength).toEqual(2); }); }); describe('#getValue', function() { return it('gets the current value', function() { query.value = 'string'; return expect(query.getValue()).toEqual('string'); }); }); describe('#setValue', function() { it('sets the current value', function() { query.setValue('string'); return expect(query.value).toEqual('string'); }); return it('sets the last value to the old current value', function() { query.lastValue = 'first'; query.value = 'second'; query.setValue('third'); return expect(query.lastValue).toEqual('second'); }); }); describe('#hasChanged', function() { return it('is true if the value has changed', function() { query.setValue('1'); query.setValue('2'); return expect(query.hasChanged()).toBeTruthy(); }); }); describe('#markEmpty', function() { return it('adds the current value to the list of values with empty results', function() { query.setValue('empty'); query.markEmpty(); return expect(query.emptyValues).toContain('empty'); }); }); return describe('#willHaveResults', function() { it('is false if the current value has less than minLength characters', function() { query.setValue('a'); return expect(query.willHaveResults()).toBeFalsy(); }); it('is false if the current value begins with any empty queries', function() { query.setValue('abc'); query.markEmpty(); query.setValue('abcdefg'); return expect(query.willHaveResults()).toBeFalsy(); }); return it('is true if the current value is not empty and is long enough', function() { query.setValue('abc'); return expect(query.willHaveResults()).toBeTruthy(); }); }); }); }).call(this);
/*global describe, it, beforeEach, expect, xit, jasmine */ /*jshint laxbreak:true */ describe("Multigraph JSON parsing", function () { "use strict"; var ArrayData = require('../../../src/core/array_data.js'), Axis = require('../../../src/core/axis.js'), Background = require('../../../src/core/background.js'), DataPlot = require('../../../src/core/data_plot.js'), Graph = require('../../../src/core/graph.js'), Icon = require('../../../src/core/icon.js'), Legend = require('../../../src/core/legend.js'), Multigraph, Plotarea = require('../../../src/core/plotarea.js'), Title = require('../../../src/core/title.js'), Window = require('../../../src/core/window.js'), mg, json; var $, jqw = require('../../node_jquery_helper.js').createJQuery(); beforeEach(function() { $ = jqw.$; }); beforeEach(function () { Multigraph = require('../../../src/core/multigraph.js')($); require('../../../src/parser/json/multigraph.js')($); }); describe("with graph subtags", function () { beforeEach(function () { json = [ { "window" : { "margin" : 2, "padding" : 5, "bordercolor" : "0x000000", "border" : 2 }, "legend" : { "color" : "0x56839c", "bordercolor" : "0x941394", "base" : [-1,-1], "anchor" : [0,0], "position" : [0,0], "visible" : "true", "frame" : "padding", "opacity" : 1, "border" : 10, "rows" : 4, "columns" : 3, "cornerradius" : 5, "padding" : 4, "icon" : { "height" : 30, "width" : 40, "border" : 1 } }, "background" : { "color" : "0x123456" }, "plotarea" : { "margintop" : 5, "marginleft" : 10, "marginbottom" : 19, "marginright" : 5, "bordercolor" : "0x111223", "border" : 0 }, "title" : { "color" : "0xfffaab", "bordercolor" : "0x127752", "border" : 2, "opacity" : 0, "padding" : 4, "cornerradius" : 10, "anchor" : [1,1], "base" : [0,0], "position" : [-1,1], "text" : "graph title" }, "horizontalaxis" : [ { "color" : "0x123456", "id" : "x", "type" : "number", "pregap" : 2, "postgap" : 4, "anchor" : 1, "min" : 0, "minoffset" : 19, "max" : 10, "maxoffset" : 2, "tickmin" : -3, "tickmax" : 3, "highlightstyle" : "bold", "linewidth" : 1, "length" : 1, "position" : [1,1], "base" : [1,-1], "minposition" : [-0.9], "maxposition" : 0.6, "labels" : { "start" : 0, "angle" : 0, "format" : "%1d", "anchor" : [0,0], "position" : [0,0], "spacing" : [10000,5000,2000,1000,500,200,100,50,20,10,5,2,1,0.1,0.01,0.001] }, "grid" : { "color" : "0xeeeeee", "visible" : false } }, { "color" : "0x123456", "id" : "x2", "type" : "number", "pregap" : 2, "postgap" : 4, "anchor" : 1, "min" : 0, "minoffset" : 19, "max" : 10, "maxoffset" : 2, "tickmin" : -3, "tickmax" : 3, "highlightstyle" : "bold", "linewidth" : 1, "length" : 1, "position" : [1,1], "base" : [1,-1], "minposition" : 0.1, "maxposition" : 0.3, "labels" : { "start" : 0, "angle" : 0, "format" : "%1d", "anchor" : [0,0], "position" : [0,0], "spacing" : [10000,5000,2000,1000,500,200,100,50,20,10,5,2,1,0.1,0.01,0.001] }, "grid" : { "color" : "0xeeeeee", "visible" : false } } ], "verticalaxis" : [ { "color" : "0x000000", "id" : "y", "type" : "number", "pregap" : 2, "postgap" : 4, "anchor" : 1, "min" : 0, "minoffset" : 19, "max" : 10, "maxoffset" : 2, "tickmin" : -3, "tickmax" : 3, "highlightstyle" : "bold", "linewidth" : 1, "length" : 1, "position" : [1,1], "base" : [1,-1], "minposition" : 0.2, "maxposition" : 0.4, "labels" : { "start" : 0, "angle" : 0, "format" : "%1d", "anchor" : [0,0], "position" : [0,0], "spacing" : [10000,5000,2000,1000,500,200,100,50,20,10,5,2,1,0.1,0.01,0.001] }, "grid" : { "color" : "0xeeeeee", "visible" : false } }, { "color" : "0x1aa456", "id" : "y2", "type" : "number", "pregap" : 2, "postgap" : 4, "anchor" : 1, "min" : 0, "minoffset" : 19, "max" : 10, "maxoffset" : 2, "tickmin" : -3, "tickmax" : 3, "highlightstyle" : "bold", "linewidth" : 1, "length" : 1, "position" : [1,1], "base" : [1,-1], "minposition" : -0.34, "maxposition" : 0.87, "labels" : { "start" : 0, "angle" : 0, "format" : "%1d", "anchor" : [0,0], "position" : [0,0], "spacing" : [10000,5000,2000,1000,500,200,100,50,20,10,5,2,1,0.1,0.01,0.001] }, "grid" : { "color" : "0xeeeeee", "visible" : false } } ], "data" : { "variables" : [ { "id": "x", "column": 0, "type": "number", "missingvalue": -9000, "missingop": "le" }, { "id": "y", "column": 1, "type": "number", "missingvalue": -9000, "missingop": "le" } ], "values" : [ [1,2], [3,4], [5,6] ] } }, { "window" : { "margin" : 2, "padding" : 5, "bordercolor" : "0x000000", "border" : 2 }, "legend" : { "color" : "0x56839c", "bordercolor" : "0x941394", "base" : [-1,-1], "anchor" : [0,0], "position" : [0,0], "visible" : "true", "frame" : "padding", "opacity" : 1, "border" : 10, "rows" : 4, "columns" : 3, "cornerradius" : 5, "padding" : 4, "icon" : { "height" : 30, "width" : 40, "border" : 1 } }, "background" : { "color" : "0x123456" }, "plotarea" : { "margintop" : 5, "marginleft" : 10, "marginbottom" : 19, "marginright" : 5, "bordercolor" : "0x111223", "border" : 0 }, "title" : { "bordercolor" : "0x127752", "border" : 2, "opacity" : 0, "padding" : 4, "cornerradius" : 10, "anchor" : [1,1], "base" : [0,0], "position" : [-1,1], "text" : "graph title" }, "horizontalaxis" : [ { "color" : "0x123456", "id" : "x", "type" : "number", "pregap" : 2, "postgap" : 4, "anchor" : 1, "min" : 0, "minoffset" : 19, "max" : 10, "maxoffset" : 2, "tickmin" : -3, "tickmax" : 3, "highlightstyle" : "bold", "linewidth" : 1, "length" : 1, "position" : [1,1], "base" : [1,-1], "minposition" : 0.14567, "maxposition" : 0.2, "labels" : { "start" : 0, "angle" : 0, "format" : "%1d", "anchor" : [0,0], "position" : [0,0], "spacing" : [10000,5000,2000,1000,500,200,100,50,20,10,5,2,1,0.1,0.01,0.001] }, "grid" : { "color" : "0xeeeeee", "visible" : false } }, { "color" : "0x1234bb", "id" : "x2", "type" : "number", "pregap" : 2, "postgap" : 4, "anchor" : 1, "min" : 0, "minoffset" : 19, "max" : 10, "maxoffset" : 2, "tickmin" : -3, "tickmax" : 3, "highlightstyle" : "bold", "linewidth" : 1, "length" : 1, "position" : [1,1], "base" : [1,-1], "minposition" : 0.3, "maxposition" : 0.4, "labels" : { "start" : 0, "angle" : 0, "format" : "%1d", "anchor" : [0,0], "position" : [0,0], "spacing" : [10000,5000,2000,1000,500,200,100,50,20,10,5,2,1,0.1,0.01,0.001] }, "grid" : { "color" : "0xeeeeee", "visible" : false } } ], "verticalaxis" : [ { "color" : "0x123456", "id" : "y", "type" : "number", "pregap" : 2, "postgap" : 4, "anchor" : 1, "min" : 0, "minoffset" : 19, "max" : 10, "maxoffset" : 2, "tickmin" : -3, "tickmax" : 3, "highlightstyle" : "bold", "linewidth" : 1, "length" : 1, "position" : [1,1], "base" : [1,-1], "minposition" : 0, "maxposition" : 1, "labels" : { "start" : 0, "angle" : 0, "format" : "%1d", "anchor" : [0,0], "position" : [0,0], "spacing" : [10000,5000,2000,1000,500,200,100,50,20,10,5,2,1,0.1,0.01,0.001] }, "grid" : { "color" : "0xeeeeee", "visible" : false } }, { "color" : "0xa23ff6", "id" : "y2", "type" : "number", "pregap" : 2, "postgap" : 4, "anchor" : 1, "min" : 0, "minoffset" : 19, "max" : 10, "maxoffset" : 2, "tickmin" : -3, "tickmax" : 3, "highlightstyle" : "bold", "linewidth" : 1, "length" : 1, "position" : [1,1], "base" : [1,-1], "minposition" : -0.34, "maxposition" : 0.98, "labels" : { "start" : 0, "angle" : 0, "format" : "%1d", "anchor" : [0,0], "position" : [0,0], "spacing" : [10000,5000,2000,1000,500,200,100,50,20,10,5,2,1,0.1,0.01,0.001] }, "grid" : { "color" : "0xeeeeee", "visible" : false } } ], "data" : { "variables" : [ { "id": "x", "column": 0, "type": "number", "missingvalue": -9000, "missingop": "le" }, { "id": "y", "column": 1, "type": "number", "missingvalue": -9000, "missingop": "le" } ], "values" : [ [1,2], [3,4], [5,6] ] } } ]; mg = Multigraph.parseJSON(json); }); it("should be able to parse a multigraph from JSON", function () { expect(mg).not.toBeUndefined(); expect(mg instanceof Multigraph).toBe(true); }); it("should properly parse a multigraph from JSON", function () { expect(mg.graphs().size()).toEqual(2); expect(mg.graphs().at(0) instanceof Graph).toBe(true); expect(mg.graphs().at(0).window() instanceof Window).toBe(true); expect(mg.graphs().at(0).legend() instanceof Legend).toBe(true); expect(mg.graphs().at(0).legend().icon() instanceof Icon).toBe(true); expect(mg.graphs().at(0).background() instanceof Background).toBe(true); expect(mg.graphs().at(0).plotarea() instanceof Plotarea).toBe(true); expect(mg.graphs().at(0).axes().size()).toEqual(4); expect(mg.graphs().at(0).axes().at(0) instanceof Axis).toBe(true); expect(mg.graphs().at(0).axes().at(0).orientation()).toEqual(Axis.HORIZONTAL); expect(mg.graphs().at(0).axes().at(1) instanceof Axis).toBe(true); expect(mg.graphs().at(0).axes().at(1).orientation()).toEqual(Axis.HORIZONTAL); expect(mg.graphs().at(0).axes().at(2) instanceof Axis).toBe(true); expect(mg.graphs().at(0).axes().at(2).orientation()).toEqual(Axis.VERTICAL); expect(mg.graphs().at(0).axes().at(3) instanceof Axis).toBe(true); expect(mg.graphs().at(0).axes().at(3).orientation()).toEqual(Axis.VERTICAL); expect(mg.graphs().at(0).data().size()).toEqual(1); expect(mg.graphs().at(0).data().at(0) instanceof ArrayData).toBe(true); expect(mg.graphs().at(1) instanceof Graph).toBe(true); expect(mg.graphs().at(1).window() instanceof Window).toBe(true); expect(mg.graphs().at(1).legend() instanceof Legend).toBe(true); expect(mg.graphs().at(1).legend().icon() instanceof Icon).toBe(true); expect(mg.graphs().at(1).background() instanceof Background).toBe(true); expect(mg.graphs().at(1).plotarea() instanceof Plotarea).toBe(true); expect(mg.graphs().at(1).axes().size()).toEqual(4); expect(mg.graphs().at(1).axes().at(0) instanceof Axis).toBe(true); expect(mg.graphs().at(1).axes().at(0).orientation()).toEqual(Axis.HORIZONTAL); expect(mg.graphs().at(1).axes().at(1) instanceof Axis).toBe(true); expect(mg.graphs().at(1).axes().at(1).orientation()).toEqual(Axis.HORIZONTAL); expect(mg.graphs().at(1).axes().at(2) instanceof Axis).toBe(true); expect(mg.graphs().at(1).axes().at(2).orientation()).toEqual(Axis.VERTICAL); expect(mg.graphs().at(1).axes().at(3) instanceof Axis).toBe(true); expect(mg.graphs().at(1).axes().at(3).orientation()).toEqual(Axis.VERTICAL); expect(mg.graphs().at(1).data().size()).toEqual(1); expect(mg.graphs().at(1).data().at(0) instanceof ArrayData).toBe(true); }); }); describe("without graph subtags", function () { beforeEach(function () { json = { "window" : { "margin" : 1, "padding" : 10, "bordercolor" : "0x111223", "width" : 2, "height" : 97, "border" : 0 }, "legend" : { "color" : "0x56839c", "bordercolor" : "0x941394", "base" : [-1,-1], "anchor" : [0,0], "position" : [0,0], "visible" : "true", "frame" : "padding", "opacity" : 1, "border" : 10, "rows" : 4, "columns" : 3, "cornerradius" : 5, "padding" : 4, "icon" : { "height" : 30, "width" : 40, "border" : 1 }, }, "background" : { "color" : "0x123456" }, "plotarea" : { "margintop" : 5, "marginleft" : 10, "marginbottom" : 19, "marginright" : 5, "bordercolor" : "0x111223", "border" : 0 }, "title" : { "color" : "0xfffaab", "bordercolor" : "0x127752", "border" : 2, "opacity" : 0, "padding" : 4, "cornerradius" : 10, "anchor" : [1,1], "base" : [0,0], "position" : [-1,1], "text" : "Graph Title" }, "horizontalaxis" : [ { "color" : "0x123456", "id" : "x", "type" : "number", "pregap" : 2, "postgap" : 4, "anchor" : 1, "min" : 0, "minoffset" : 19, "max" : 10, "maxoffset" : 2, "tickmin" : -3, "tickmax" : 3, "highlightstyle" : "bold", "linewidth" : 1, "length" : 1, "position" : [1,1], "base" : [1,-1], "minposition" : -0.123, "maxposition" : 0.324, "labels" : { "start" : 0, "angle" : 0, "format" : "%1d", "anchor" : [0,0], "position" : [0,0], "spacing" : [10000,5000,2000,1000,500,200,100,50,20,10,5,2,1,0.1,0.01,0.001] }, "grid" : { "color" : "0xeeeeee", "visible" : false } }, { "color" : "0x000000", "id" : "x2", "type" : "number", "pregap" : 2, "postgap" : 4, "anchor" : 1, "min" : 0, "minoffset" : 19, "max" : 10, "maxoffset" : 2, "tickmin" : -3, "tickmax" : 3, "highlightstyle" : "bold", "linewidth" : 1, "length" : 1, "position" : [1,1], "base" : [1,-1], "minposition" : -0.8, "maxposition" : 0.953, "labels" : { "start" : 0, "angle" : 0, "format" : "%1d", "anchor" : [0,0], "position" : [0,0], "spacing" : [10000,5000,2000,1000,500,200,100,50,20,10,5,2,1,0.1,0.01,0.001] }, "grid" : { "color" : "0xeeeeee", "visible" : false } } ], "verticalaxis" : [ { "color" : "0x123456", "id" : "y", "type" : "number", "pregap" : 2, "postgap" : 4, "anchor" : 1, "min" : 0, "minoffset" : 19, "max" : 10, "maxoffset" : 2, "tickmin" : -3, "tickmax" : 3, "highlightstyle" : "bold", "linewidth" : 1, "length" : 1, "position" : [1,1], "base" : [1,-1], "minposition" : 0.1, "maxposition" : 0.9, "labels" : { "start" : 0, "angle" : 0, "format" : "%1d", "anchor" : [0,0], "position" : [0,0], "spacing" : [10000,5000,2000,1000,500,200,100,50,20,10,5,2,1,0.1,0.01,0.001] }, "grid" : { "color" : "0xeeeeee", "visible" : false } }, { "color" : "0x123456", "id" : "y2", "type" : "number", "pregap" : 2, "postgap" : 4, "anchor" : 1, "min" : 0, "minoffset" : 19, "max" : 10, "maxoffset" : 2, "tickmin" : -3, "tickmax" : 3, "highlightstyle" : "bold", "linewidth" : 1, "length" : 1, "position" : [1,1], "base" : [1,-1], "minposition" : -0.3, "maxposition" : 1, "labels" : { "start" : 0, "angle" : 0, "format" : "%1d", "anchor" : [0,0], "position" : [0,0], "spacing" : [10000,5000,2000,1000,500,200,100,50,20,10,5,2,1,0.1,0.01,0.001] }, "grid" : { "color" : "0xeeeeee", "visible" : false } }, { "color" : "0x123456", "id" : "y3", "type" : "number", "pregap" : 2, "postgap" : 4, "anchor" : 1, "min" : 0, "minoffset" : 19, "max" : 10, "maxoffset" : 2, "tickmin" : -3, "tickmax" : 3, "highlightstyle" : "bold", "linewidth" : 1, "length" : 1, "position" : [1,1], "base" : [1,-1], "minposition" : 0.1, "maxposition" : 0.9, "labels" : { "start" : 0, "angle" : 0, "format" : "%1d", "anchor" : [0,0], "position" : [0,0], "spacing" : [10000,5000,2000,1000,500,200,100,50,20,10,5,2,1,0.1,0.01,0.001] }, "grid" : { "color" : "0xeeeeee", "visible" : false } } ], "plot" : [ { "horizontalaxis" : { "x" : [ "x" ] }, "verticalaxis" : { "y" : [ "y" ] }, "legend" : { "visible" : "true", "label" : "y" } }, { "horizontalaxis" : { "x2" : [ "x" ] }, "verticalaxis" : { "y2": [ "y" ] }, "legend" : { "visible" : "true", "label" : "y" } } ], "data" : { "variables" : [ { "id": "x", "column": 0, "type": "number", "missingvalue": -9000, "missingop": "le" }, { "id": "y", "column": 1, "type": "number", "missingvalue": -9000, "missingop": "le" } ], "values" : [ [1,2], [3,4], [5,6] ] } }, mg = Multigraph.parseJSON(json); }); it("should be able to parse a multigraph from JSON", function () { expect(mg).not.toBeUndefined(); expect(mg instanceof Multigraph).toBe(true); }); it("should properly parse a multigraph from JSON", function () { expect(mg.graphs().size()).toEqual(1); expect(mg.graphs().at(0) instanceof Graph).toBe(true); expect(mg.graphs().at(0).window() instanceof Window).toBe(true); expect(mg.graphs().at(0).legend() instanceof Legend).toBe(true); expect(mg.graphs().at(0).legend().icon() instanceof Icon).toBe(true); expect(mg.graphs().at(0).background() instanceof Background).toBe(true); expect(mg.graphs().at(0).plotarea() instanceof Plotarea).toBe(true); expect(mg.graphs().at(0).axes().size()).toEqual(5); expect(mg.graphs().at(0).axes().at(0) instanceof Axis).toBe(true); expect(mg.graphs().at(0).axes().at(0).orientation()).toEqual(Axis.HORIZONTAL); expect(mg.graphs().at(0).axes().at(1) instanceof Axis).toBe(true); expect(mg.graphs().at(0).axes().at(1).orientation()).toEqual(Axis.HORIZONTAL); expect(mg.graphs().at(0).axes().at(2) instanceof Axis).toBe(true); expect(mg.graphs().at(0).axes().at(2).orientation()).toEqual(Axis.VERTICAL); expect(mg.graphs().at(0).axes().at(3) instanceof Axis).toBe(true); expect(mg.graphs().at(0).axes().at(3).orientation()).toEqual(Axis.VERTICAL); expect(mg.graphs().at(0).axes().at(4) instanceof Axis).toBe(true); expect(mg.graphs().at(0).axes().at(4).orientation()).toEqual(Axis.VERTICAL); expect(mg.graphs().at(0).plots().size()).toEqual(2); expect(mg.graphs().at(0).plots().at(0) instanceof DataPlot).toBe(true); expect(mg.graphs().at(0).plots().at(1) instanceof DataPlot).toBe(true); expect(mg.graphs().at(0).data().size()).toEqual(1); expect(mg.graphs().at(0).data().at(0) instanceof ArrayData).toBe(true); }); }); });
/** * @arguments _none_ * @example * "0.5".asInteger(); // => 0 * [1, 2, 3.14].asInteger(); // => [1, 2, 3] */ sc.define("asInteger", { Number: function() { return this|0; }, Array: function() { return this.map(function(x) { return x.asInteger(); }); }, String: function() { return this|0; } });
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M3 5v14h18V5H3zm5.33 12H5V7h3.33v10zm5.34 0h-3.33v-4h3.33v4zM19 17h-3.33v-4H19v4zm0-6h-8.67V7H19v4z" }), 'ViewQuiltOutlined');
import React, { Component } from 'react'; import { Text, View, Image, TextInput, ListView, TouchableHighlight, TouchableOpacity, Switch } from 'react-native'; import helpers from '../helpers/helpers.js'; import styles from '../styles.ios.js'; import FoodpairResults from './FoodpairResults.ios.js'; import AddIngredientCamera from './AddIngredientCamera.ios.js'; import { connect } from 'react-redux'; import { showSearch, rendering } from '../actions/addIngredientActions.ios.js'; import { bindActionCreators } from 'redux'; import * as addIngredient from '../actions/addIngredientActions.ios.js'; class AddIngredient extends Component { constructor(props) { super(props); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); const ingredients = props.currentIngredients || props.ingredients; this.state = { currentIngredients: ds.cloneWithRows(ingredients), ingredientToAdd: '' } } addIngredient() { const ingredients = []; for (let ingredient of this.state.currentIngredients._dataBlob.s1) { ingredients.push(ingredient); } ingredients.push(this.state.ingredientToAdd) const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.setState({ currentIngredients: ds.cloneWithRows(ingredients), ingredientToAdd: '' }) this.forceUpdate(); } navigateAddIngredientCamera() { this.props.navigator.push({ component: AddIngredientCamera, passProps: { currentIngredients: this.state.currentIngredients._dataBlob.s1, store: this.props.store } }) } removeIngredient(ingredient) { const ingredients = this.state.currentIngredients._dataBlob.s1; const removeIndex = ingredients.indexOf(ingredient); ingredients.splice(removeIndex, 1); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.setState({ currentIngredients: ds.cloneWithRows(ingredients) }) this.forceUpdate(); } searchMultipleFoodpairs() { this.props.actions.rendering(); helpers.foodpairing.getFoodID(this.state.currentIngredients._dataBlob.s1) .then( resp => { helpers.foodpairing.getMultipleFoodpairings(resp.data) .then( response => { this.props.actions.rendering(); const ingredients = this.state.currentIngredients._dataBlob.s1; this.props.navigator.push({ component: FoodpairResults, passProps: { foodpairs: response.data, ingredients: ingredients, store: this.props.store } }) }) .catch( error => { console.log('Error ', error); }) }) .catch( err => { console.log('Error: ', err); }) } goBack() { this.props.navigator.pop(); } render() { const { state, actions } = this.props if (state.rendering) { return ( <Image source= {{uri: 'https://media.blueapron.com/assets/loader/pot-loader-6047abec2ec57c18d848f623c036f7fe80236dce689bb48279036c4f914d0c9e.gif'}} style = {styles.loadingGif} /> ) } if (state.showSearch) { return ( <View style={styles.addIngredientsContainer}> <View style={styles.resultsTitle}> <TouchableHighlight style={styles.backButton} onPress={this.goBack.bind(this)}> <Image style={styles.backButtonImage} source={{uri: 'https://cdn0.iconfinder.com/data/icons/vector-basic-tab-bar-icons/48/back_button-128.png'}} /> </TouchableHighlight> <Text style={styles.resultsTitleText}>Current Ingredients</Text> </View> <ListView style={styles.addIngredientListView} dataSource={this.state.currentIngredients} renderRow={(ingredient, i) => ( <View style={styles.addIngredientListItem}> <Text style={styles.addIngredientListItemText}>{ingredient}</Text> <TouchableOpacity style={styles.removeListItem} onPress={this.removeIngredient.bind(this, ingredient)} > <Image style={styles.removeIcon} source={require('../public/removeicon.png')} /> </TouchableOpacity> </View> )} /> <TouchableOpacity style={styles.searchIconContainer} onPress={this.searchMultipleFoodpairs.bind(this)} > <Image style={styles.searchIcon} source={require('../public/searchicon.png')} /> </TouchableOpacity> <View style={styles.addMoreIngredientsContainer}> <View style={styles.searchBarPictureFrame}> <TextInput onSubmitEditing={this.addIngredient.bind(this)} style={styles.addIngredientInput} onChangeText={(ingredientToAdd) => this.setState({ingredientToAdd})} value={this.state.ingredientToAdd} placeholder={'Add ingredient'} /> </View> <Switch onValueChange={actions.showSearch} style={styles.addIngredientSwitch} value={state.showSearch} /> </View> </View> ) } else { return ( <View style={styles.addIngredientsContainer}> <View style={styles.resultsTitle}> <TouchableHighlight style={styles.backButton} onPress={this.goBack.bind(this)}> <Image style={styles.backButtonImage} source={{uri: 'https://cdn0.iconfinder.com/data/icons/vector-basic-tab-bar-icons/48/back_button-128.png'}} /> </TouchableHighlight> <Text style={styles.resultsTitleText}>Current Ingredients</Text> </View> <ListView style={styles.addIngredientListView} dataSource={this.state.currentIngredients} renderRow={(ingredient, i) => ( <View style={styles.addIngredientListItem}> <Text style={styles.addIngredientListItemText}>{ingredient}</Text> <TouchableOpacity style={styles.removeListItem} onPress={this.removeIngredient.bind(this, ingredient)} > <Image style={styles.removeIcon} source={require('../public/removeicon.png')} /> </TouchableOpacity> </View> )} /> <View style={styles.addMoreIngredientsContainer}> <TouchableOpacity style={styles.searchIconContainer} onPress={this.searchMultipleFoodpairs.bind(this)} > <Image style={styles.searchIcon} source={require('../public/searchicon.png')} /> </TouchableOpacity> <TouchableOpacity style={styles.buttonView} onPress={this.navigateAddIngredientCamera.bind(this)}> <Image style={[styles.takePicture]} source={{uri: 'https://s3.amazonaws.com/features.ifttt.com/newsletter_images/2015_February/camera512x512+(1).png'}}/> </TouchableOpacity> <Switch onValueChange={actions.showSearch} style={styles.addIngredientSwitch} value={state.showSearch} /> </View> </View> ) } } } export default connect(state => ({ state: state.addIngredient }), (dispatch) => ({ actions: bindActionCreators(addIngredient.default, dispatch) }) )(AddIngredient);
(function() { 'use strict'; angular .module('app.station') .controller('StationCamsAndPhotosPhotosCtrl', StationCamsAndPhotosPhotosCtrl); StationCamsAndPhotosPhotosCtrl.$inject = ['$scope', '$mdDialog', '$mdMedia', 'stationStorage', 'StationWebcamsFactory']; function StationCamsAndPhotosPhotosCtrl($scope, $mdDialog, $mdMedia, stationStorage, StationWebcamsFactory) { var vm = this; vm.customFullscreen = $mdMedia('xs') || $mdMedia('sm'); vm.$onInit = onInit; vm.dateChange = dateChange; vm.getWebcamPhotosOnDate = getWebcamPhotosOnDate; vm.station = stationStorage.getStation(); vm.noWebcamPhotos = noWebcamPhotos; vm.showPhoto = showPhoto; vm.updateWebcamPhotos = updateWebcamPhotos; vm.webcamPhotos = []; vm.datePickerModel = { date: moment().startOf('day') }; function dateChange() { updateWebcamPhotos(); } function getWebcamPhotosOnDate() { var stationId = vm.station.id; var onDate = Number(vm.datePickerModel.date); return StationWebcamsFactory.getHourlyWebcamPhotos(stationId, onDate) .then(function(response) { return response.data; }); } function noWebcamPhotos() { if (vm.webcamPhotos.length == 0) { return true; } return false; } function onInit() { updateWebcamPhotos(); } function showPhoto(ev, index) { var useFullScreen = ($mdMedia('sm') || $mdMedia('xs')) && vm.customFullscreen; $mdDialog.show({ templateUrl: '/static/partials/station/station-cams-and-photos-dialog.html', locals: {photoData: vm.webcamPhotos[index]}, targetEvent: ev, clickOutsideToClose: true, fullscreen: useFullScreen, controller: DialogController, controllerAs: 'dialogVm' }) .then(function(answer) { vm.status = 'You said the information was "' + answer + '".'; }, function() { vm.status = 'You cancelled the dialog.'; }); $scope.$watch(function() { return $mdMedia('xs') || $mdMedia('sm'); }, function(wantsFullScreen) { vm.customFullscreen = (wantsFullScreen === true); }); }; function updateWebcamPhotos() { vm.getWebcamPhotosOnDate().then(function(data) { vm.webcamPhotos = data; }); } } function DialogController($mdDialog, photoData) { var vm = this; vm.webcamPhoto = photoData; vm.hide = function() { $mdDialog.hide(); }; vm.cancel = function() { $mdDialog.cancel(); }; vm.answer = function(answer) { $mdDialog.hide(answer); }; } })();
'use strict';// Promises are put into their own facade file so that they can be used without // introducing a dependency on rxjs. They are re-exported through facade/async. var PromiseWrapper = (function () { function PromiseWrapper() { } PromiseWrapper.resolve = function (obj) { return Promise.resolve(obj); }; PromiseWrapper.reject = function (obj, _) { return Promise.reject(obj); }; // Note: We can't rename this method into `catch`, as this is not a valid // method name in Dart. PromiseWrapper.catchError = function (promise, onError) { return promise.catch(onError); }; PromiseWrapper.all = function (promises) { if (promises.length == 0) return Promise.resolve([]); return Promise.all(promises); }; PromiseWrapper.then = function (promise, success, rejection) { return promise.then(success, rejection); }; PromiseWrapper.wrap = function (computation) { return new Promise(function (res, rej) { try { res(computation()); } catch (e) { rej(e); } }); }; PromiseWrapper.scheduleMicrotask = function (computation) { PromiseWrapper.then(PromiseWrapper.resolve(null), computation, function (_) { }); }; PromiseWrapper.isPromise = function (obj) { return obj instanceof Promise; }; PromiseWrapper.completer = function () { var resolve; var reject; var p = new Promise(function (res, rej) { resolve = res; reject = rej; }); return { promise: p, resolve: resolve, reject: reject }; }; return PromiseWrapper; })(); exports.PromiseWrapper = PromiseWrapper; //# sourceMappingURL=promise.js.map
// Copyright 2015-2021 JC Fisher import reduce from "./reduce"; // CONCATENATE reduces a list of values into a single string. export default function concatenate(...values) { // Combine into a single string value return reduce(values, (acc, item) => `${acc}${item}`, ""); }
donut = { name: "donut", ingredients: [frosting] //depends on the global sugar.js being available };
'use strict'; // Modules var path = require('path'); var fs = require('fs'); var _ = require('lodash'); // "Constants" var PLUGIN_NAME = 'kalabox-plugin-pantheon'; module.exports = function(kbox) { var globalConfig = kbox.core.deps.get('globalConfig'); var events = kbox.core.events; var engine = kbox.engine; var Promise = kbox.Promise; kbox.ifApp(function(app) { // Helpers /** * Gets plugin conf from the appconfig or from CLI arg **/ var getOpts = function(options) { // Grab our options from config var defaults = app.config.pluginConf[PLUGIN_NAME]; // Override any config coming in on the CLI _.each(Object.keys(defaults), function(key) { if (_.has(options, key) && options[key]) { defaults[key] = options[key]; } }); return defaults; }; /** * Runs a wp-cli command on the app data container **/ var runWpCMD = function(cmd, opts, done) { // Run the wp-cli command in the correct directory in the container if the // user is somewhere inside the code directory on the host side. // @todo: consider if this is better in the actual engine.run command // vs here. // Get current working directory. var cwd = process.cwd(); // Get code root. var codeRoot = app.config.codeRoot; // Get the branch of current working directory. // Run the wp-cli command in the correct directory in the container if the // user is somewhere inside the code directory on the host side. // @todo: consider if this is better in the actual engine.run command // vs here. var workingDirExtra = ''; if (_.startsWith(cwd, codeRoot)) { workingDirExtra = cwd.replace(codeRoot, ''); } var codeDir = globalConfig.codeDir; var workingDir = '/' + codeDir + workingDirExtra; // Image name. var image = 'terminus'; // Build create options. var createOpts = kbox.util.docker.CreateOpts() .workingDir(workingDir) .volumeFrom(app.dataContainerName) .json(); // Change entrypoint to wp-cli /* jshint ignore:start */ //jscs:disable createOpts.Entrypoint = ["/usr/local/bin/kwp"]; /* jshint ignore:end */ // Build start options. var startOpts = kbox.util.docker.StartOpts() .bind(app.config.homeBind, '/ssh') .bind(app.rootBind, '/src') .json(); // Perform a container run. return engine.run(image, cmd, createOpts, startOpts) // Return. .nodeify(done); }; // Tasks // wp-cli wrapper: kbox wp COMMAND kbox.tasks.add(function(task) { task.path = [app.name, 'wp']; task.category = 'appCmd'; task.description = 'Run wp-cli commands.'; task.kind = 'delegate'; task.func = function(done) { var opts = getOpts(this.options); var cmd = this.payload; cmd.unshift('--allow-root'); runWpCMD(cmd, opts, done); }; }); }); };
/* * index.js: Database client for MongoHQ Cloud Databases * * (C) 2012 Nodejitsu Inc. * */ var util = require('util'), urlJoin = require('url-join'), base = require('../../../core/base'), auth = require('../../../common/auth'), url = require('url'), request = require('request'), errs = require('errs'), _ = require('underscore'); var Client = exports.Client = function (options) { base.Client.call(this, options); if (!this.before) { this.before = []; } this.protocol = options.protocol || 'https://'; this.databaseUrl = options.databaseUrl || 'providers.mongohq.com'; this.before.push(auth.basic); _.extend(this, require('./databases')); }; util.inherits(Client, base.Client); Client.prototype._getUrl = function (options) { options = options || {}; return urlJoin([this.protocol + this.databaseUrl, 'provider'].join('/'), typeof options === 'string' ? options : options.path); }; Client.prototype.failCodes = { 400: 'Bad Request', 401: 'Unauthorized', 403: 'Resize not allowed', 404: 'Item or Account not found', 409: 'Build in progress', 413: 'Over Limit', 415: 'Bad Media Type', 500: 'Fault', 503: 'Service Unavailable' }; Client.prototype.successCodes = { 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-authoritative information', 204: 'No content' };
'use strict'; var express = require('express'); var controller = require('./problem.controller'); var router = express.Router(); router.get('/', controller.index); router.get('/:id', controller.show); router.post('/', controller.create); router.put('/:id', controller.update); router.patch('/:id', controller.update); router.delete('/:id', controller.destroy); module.exports = router;
this.primereact = this.primereact || {}; this.primereact.tooltip = (function (exports, React, ReactDOM, utils, portal, PrimeReact) { 'use strict'; function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var React__default = /*#__PURE__*/_interopDefaultLegacy(React); var ReactDOM__default = /*#__PURE__*/_interopDefaultLegacy(ReactDOM); var PrimeReact__default = /*#__PURE__*/_interopDefaultLegacy(PrimeReact); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function tip(props) { var appendTo = props.appendTo || document.body; var tooltipWrapper = document.createDocumentFragment(); utils.DomHandler.appendChild(tooltipWrapper, appendTo); props = _objectSpread(_objectSpread({}, props), props.options); var tooltipEl = /*#__PURE__*/React__default["default"].createElement(Tooltip, props); ReactDOM__default["default"].render(tooltipEl, tooltipWrapper); var updateTooltip = function updateTooltip(newProps) { props = _objectSpread(_objectSpread({}, props), newProps); ReactDOM__default["default"].render( /*#__PURE__*/React__default["default"].cloneElement(tooltipEl, props), tooltipWrapper); }; return { destroy: function destroy() { ReactDOM__default["default"].unmountComponentAtNode(tooltipWrapper); }, updateContent: function updateContent(newContent) { console.warn("The 'updateContent' method has been deprecated on Tooltip. Use update(newProps) method."); updateTooltip({ content: newContent }); }, update: function update(newProps) { updateTooltip(newProps); } }; } var Tooltip = /*#__PURE__*/function (_Component) { _inherits(Tooltip, _Component); var _super = _createSuper(Tooltip); function Tooltip(props) { var _this; _classCallCheck(this, Tooltip); _this = _super.call(this, props); _this.state = { visible: false, position: _this.props.position }; _this.show = _this.show.bind(_assertThisInitialized(_this)); _this.hide = _this.hide.bind(_assertThisInitialized(_this)); _this.onMouseEnter = _this.onMouseEnter.bind(_assertThisInitialized(_this)); _this.onMouseLeave = _this.onMouseLeave.bind(_assertThisInitialized(_this)); return _this; } _createClass(Tooltip, [{ key: "isTargetContentEmpty", value: function isTargetContentEmpty(target) { return !(this.props.content || this.getTargetOption(target, 'tooltip')); } }, { key: "isContentEmpty", value: function isContentEmpty(target) { return !(this.props.content || this.getTargetOption(target, 'tooltip') || this.props.children); } }, { key: "isMouseTrack", value: function isMouseTrack(target) { return this.getTargetOption(target, 'mousetrack') || this.props.mouseTrack; } }, { key: "isDisabled", value: function isDisabled(target) { return this.getTargetOption(target, 'disabled') === 'true' || this.hasTargetOption(target, 'disabled') || this.props.disabled; } }, { key: "isAutoHide", value: function isAutoHide() { return this.getTargetOption(this.currentTarget, 'autohide') || this.props.autoHide; } }, { key: "getTargetOption", value: function getTargetOption(target, option) { if (this.hasTargetOption(target, "data-pr-".concat(option))) { return target.getAttribute("data-pr-".concat(option)); } return null; } }, { key: "hasTargetOption", value: function hasTargetOption(target, option) { return target && target.hasAttribute(option); } }, { key: "getEvents", value: function getEvents(target) { var showEvent = this.getTargetOption(target, 'showevent') || this.props.showEvent; var hideEvent = this.getTargetOption(target, 'hideevent') || this.props.hideEvent; if (this.isMouseTrack(target)) { showEvent = 'mousemove'; hideEvent = 'mouseleave'; } else { var event = this.getTargetOption(target, 'event') || this.props.event; if (event === 'focus') { showEvent = 'focus'; hideEvent = 'blur'; } } return { showEvent: showEvent, hideEvent: hideEvent }; } }, { key: "getPosition", value: function getPosition(target) { return this.getTargetOption(target, 'position') || this.state.position; } }, { key: "getMouseTrackPosition", value: function getMouseTrackPosition(target) { var top = this.getTargetOption(target, 'mousetracktop') || this.props.mouseTrackTop; var left = this.getTargetOption(target, 'mousetrackleft') || this.props.mouseTrackLeft; return { top: top, left: left }; } }, { key: "updateText", value: function updateText(target, callback) { if (this.tooltipTextEl) { var content = this.getTargetOption(target, 'tooltip') || this.props.content; if (content) { this.tooltipTextEl.innerHTML = ''; // remove children this.tooltipTextEl.appendChild(document.createTextNode(content)); callback(); } else if (this.props.children) { callback(); } } } }, { key: "show", value: function show(e) { var _this2 = this; this.currentTarget = e.currentTarget; if (this.isContentEmpty(this.currentTarget) || this.isDisabled(this.currentTarget)) { return; } var updateTooltipState = function updateTooltipState() { _this2.updateText(_this2.currentTarget, function () { if (_this2.props.autoZIndex && !utils.ZIndexUtils.get(_this2.containerEl)) { utils.ZIndexUtils.set('tooltip', _this2.containerEl, PrimeReact__default["default"].autoZIndex, _this2.props.baseZIndex || PrimeReact__default["default"].zIndex['tooltip']); } _this2.containerEl.style.left = ''; _this2.containerEl.style.top = ''; if (_this2.isMouseTrack(_this2.currentTarget) && !_this2.containerSize) { _this2.containerSize = { width: utils.DomHandler.getOuterWidth(_this2.containerEl), height: utils.DomHandler.getOuterHeight(_this2.containerEl) }; } _this2.align(_this2.currentTarget, { x: e.pageX, y: e.pageY }); }); }; if (this.state.visible) { this.applyDelay('updateDelay', updateTooltipState); } else { this.sendCallback(this.props.onBeforeShow, { originalEvent: e, target: this.currentTarget }); this.applyDelay('showDelay', function () { _this2.setState({ visible: true, position: _this2.getPosition(_this2.currentTarget) }, function () { updateTooltipState(); _this2.sendCallback(_this2.props.onShow, { originalEvent: e, target: _this2.currentTarget }); }); _this2.bindDocumentResizeListener(); _this2.bindScrollListener(); utils.DomHandler.addClass(_this2.currentTarget, _this2.getTargetOption(_this2.currentTarget, 'classname')); }); } } }, { key: "hide", value: function hide(e) { var _this3 = this; this.clearTimeouts(); if (this.state.visible) { utils.DomHandler.removeClass(this.currentTarget, this.getTargetOption(this.currentTarget, 'classname')); this.sendCallback(this.props.onBeforeHide, { originalEvent: e, target: this.currentTarget }); this.applyDelay('hideDelay', function () { utils.ZIndexUtils.clear(_this3.containerEl); utils.DomHandler.removeClass(_this3.containerEl, 'p-tooltip-active'); if (!_this3.isAutoHide() && _this3.allowHide === false) { return; } _this3.setState({ visible: false, position: _this3.props.position }, function () { if (_this3.tooltipTextEl) { ReactDOM__default["default"].unmountComponentAtNode(_this3.tooltipTextEl); } _this3.unbindDocumentResizeListener(); _this3.unbindScrollListener(); _this3.currentTarget = null; _this3.scrollHandler = null; _this3.containerSize = null; _this3.allowHide = true; _this3.sendCallback(_this3.props.onHide, { originalEvent: e, target: _this3.currentTarget }); }); }); } } }, { key: "align", value: function align(target, coordinate) { var _this4 = this; var left = 0, top = 0; if (this.isMouseTrack(target) && coordinate) { var containerSize = { width: utils.DomHandler.getOuterWidth(this.containerEl), height: utils.DomHandler.getOuterHeight(this.containerEl) }; left = coordinate.x; top = coordinate.y; var _this$getMouseTrackPo = this.getMouseTrackPosition(target), mouseTrackTop = _this$getMouseTrackPo.top, mouseTrackLeft = _this$getMouseTrackPo.left; switch (this.state.position) { case 'left': left -= containerSize.width + mouseTrackLeft; top -= containerSize.height / 2 - mouseTrackTop; break; case 'right': left += mouseTrackLeft; top -= containerSize.height / 2 - mouseTrackTop; break; case 'top': left -= containerSize.width / 2 - mouseTrackLeft; top -= containerSize.height + mouseTrackTop; break; case 'bottom': left -= containerSize.width / 2 - mouseTrackLeft; top += mouseTrackTop; break; } if (left <= 0 || this.containerSize.width > containerSize.width) { this.containerEl.style.left = '0px'; this.containerEl.style.right = window.innerWidth - containerSize.width - left + 'px'; } else { this.containerEl.style.right = ''; this.containerEl.style.left = left + 'px'; } this.containerEl.style.top = top + 'px'; utils.DomHandler.addClass(this.containerEl, 'p-tooltip-active'); } else { var pos = utils.DomHandler.findCollisionPosition(this.state.position); var my = this.getTargetOption(target, 'my') || this.props.my || pos.my; var at = this.getTargetOption(target, 'at') || this.props.at || pos.at; this.containerEl.style.padding = '0px'; utils.DomHandler.flipfitCollision(this.containerEl, target, my, at, function (currentPosition) { var _currentPosition$at = currentPosition.at, atX = _currentPosition$at.x, atY = _currentPosition$at.y; var myX = currentPosition.my.x; var position = _this4.props.at ? atX !== 'center' && atX !== myX ? atX : atY : currentPosition.at["".concat(pos.axis)]; _this4.containerEl.style.padding = ''; _this4.setState({ position: position }, function () { _this4.updateContainerPosition(); utils.DomHandler.addClass(_this4.containerEl, 'p-tooltip-active'); }); }); } } }, { key: "updateContainerPosition", value: function updateContainerPosition() { if (this.containerEl) { var style = getComputedStyle(this.containerEl); if (this.state.position === 'left') this.containerEl.style.left = parseFloat(style.left) - parseFloat(style.paddingLeft) * 2 + 'px';else if (this.state.position === 'top') this.containerEl.style.top = parseFloat(style.top) - parseFloat(style.paddingTop) * 2 + 'px'; } } }, { key: "onMouseEnter", value: function onMouseEnter() { if (!this.isAutoHide()) { this.allowHide = false; } } }, { key: "onMouseLeave", value: function onMouseLeave(e) { if (!this.isAutoHide()) { this.allowHide = true; this.hide(e); } } }, { key: "bindDocumentResizeListener", value: function bindDocumentResizeListener() { var _this5 = this; this.documentResizeListener = function (e) { if (!utils.DomHandler.isAndroid()) { _this5.hide(e); } }; window.addEventListener('resize', this.documentResizeListener); } }, { key: "unbindDocumentResizeListener", value: function unbindDocumentResizeListener() { if (this.documentResizeListener) { window.removeEventListener('resize', this.documentResizeListener); this.documentResizeListener = null; } } }, { key: "bindScrollListener", value: function bindScrollListener() { var _this6 = this; if (!this.scrollHandler) { this.scrollHandler = new utils.ConnectedOverlayScrollHandler(this.currentTarget, function (e) { if (_this6.state.visible) { _this6.hide(e); } }); } this.scrollHandler.bindScrollListener(); } }, { key: "unbindScrollListener", value: function unbindScrollListener() { if (this.scrollHandler) { this.scrollHandler.unbindScrollListener(); } } }, { key: "bindTargetEvent", value: function bindTargetEvent(target) { if (target) { var _this$getEvents = this.getEvents(target), showEvent = _this$getEvents.showEvent, hideEvent = _this$getEvents.hideEvent; target.addEventListener(showEvent, this.show); target.addEventListener(hideEvent, this.hide); } } }, { key: "unbindTargetEvent", value: function unbindTargetEvent(target) { if (target) { var _this$getEvents2 = this.getEvents(target), showEvent = _this$getEvents2.showEvent, hideEvent = _this$getEvents2.hideEvent; target.removeEventListener(showEvent, this.show); target.removeEventListener(hideEvent, this.hide); } } }, { key: "applyDelay", value: function applyDelay(delayProp, callback) { this.clearTimeouts(); var delay = this.getTargetOption(this.currentTarget, delayProp.toLowerCase()) || this.props[delayProp]; if (!!delay) { this["".concat(delayProp, "Timeout")] = setTimeout(function () { return callback(); }, delay); } else { callback(); } } }, { key: "sendCallback", value: function sendCallback(callback) { if (callback) { for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { params[_key - 1] = arguments[_key]; } callback.apply(void 0, params); } } }, { key: "clearTimeouts", value: function clearTimeouts() { clearTimeout(this.showDelayTimeout); clearTimeout(this.updateDelayTimeout); clearTimeout(this.hideDelayTimeout); } }, { key: "updateTargetEvents", value: function updateTargetEvents(target) { this.unloadTargetEvents(target); this.loadTargetEvents(target); } }, { key: "loadTargetEvents", value: function loadTargetEvents(target) { this.setTargetEventOperations(target || this.props.target, 'bindTargetEvent'); } }, { key: "unloadTargetEvents", value: function unloadTargetEvents(target) { this.setTargetEventOperations(target || this.props.target, 'unbindTargetEvent'); } }, { key: "setTargetEventOperations", value: function setTargetEventOperations(target, operation) { var _this7 = this; if (target) { if (utils.DomHandler.isElement(target)) { this[operation](target); } else { var setEvent = function setEvent(target) { var element = utils.DomHandler.find(document, target); element.forEach(function (el) { _this7[operation](el); }); }; if (target instanceof Array) { target.forEach(function (t) { setEvent(t); }); } else { setEvent(target); } } } } }, { key: "componentDidMount", value: function componentDidMount() { if (this.props.target) { this.loadTargetEvents(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { var _this8 = this; if (prevProps.target !== this.props.target) { this.unloadTargetEvents(prevProps.target); this.loadTargetEvents(); } if (this.state.visible) { if (prevProps.content !== this.props.content) { this.applyDelay('updateDelay', function () { _this8.updateText(_this8.currentTarget, function () { _this8.align(_this8.currentTarget); }); }); } if (this.currentTarget && this.isDisabled(this.currentTarget)) { this.hide(); } } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.clearTimeouts(); this.unbindDocumentResizeListener(); this.unloadTargetEvents(); if (this.scrollHandler) { this.scrollHandler.destroy(); this.scrollHandler = null; } utils.ZIndexUtils.clear(this.containerEl); } }, { key: "renderElement", value: function renderElement() { var _this9 = this; var tooltipClassName = utils.classNames('p-tooltip p-component', _defineProperty({}, "p-tooltip-".concat(this.state.position), true), this.props.className); var isTargetContentEmpty = this.isTargetContentEmpty(this.currentTarget); return /*#__PURE__*/React__default["default"].createElement("div", { id: this.props.id, ref: function ref(el) { return _this9.containerEl = el; }, className: tooltipClassName, style: this.props.style, role: "tooltip", "aria-hidden": this.state.visible, onMouseEnter: this.onMouseEnter, onMouseLeave: this.onMouseLeave }, /*#__PURE__*/React__default["default"].createElement("div", { className: "p-tooltip-arrow" }), /*#__PURE__*/React__default["default"].createElement("div", { ref: function ref(el) { return _this9.tooltipTextEl = el; }, className: "p-tooltip-text" }, isTargetContentEmpty && this.props.children)); } }, { key: "render", value: function render() { if (this.state.visible) { var element = this.renderElement(); return /*#__PURE__*/React__default["default"].createElement(portal.Portal, { element: element, appendTo: this.props.appendTo, visible: true }); } return null; } }]); return Tooltip; }(React.Component); _defineProperty(Tooltip, "defaultProps", { id: null, target: null, content: null, disabled: false, className: null, style: null, appendTo: null, position: 'right', my: null, at: null, event: null, showEvent: 'mouseenter', hideEvent: 'mouseleave', autoZIndex: true, baseZIndex: 0, mouseTrack: false, mouseTrackTop: 5, mouseTrackLeft: 5, showDelay: 0, updateDelay: 0, hideDelay: 0, autoHide: true, onBeforeShow: null, onBeforeHide: null, onShow: null, onHide: null }); exports.Tooltip = Tooltip; exports.tip = tip; Object.defineProperty(exports, '__esModule', { value: true }); return exports; })({}, React, ReactDOM, primereact.utils, primereact.portal, primereact.api);
/* * * * Networkgraph series * * (c) 2010-2020 Paweł Fus * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ import Chart from '../../parts/Chart.js'; import H from '../../parts/Globals.js'; import U from '../../parts/Utilities.js'; var addEvent = U.addEvent; /* eslint-disable no-invalid-this, valid-jsdoc */ H.dragNodesMixin = { /** * Mouse down action, initializing drag&drop mode. * * @private * @param {Highcharts.Point} point The point that event occured. * @param {Highcharts.PointerEventObject} event Browser event, before normalization. * @return {void} */ onMouseDown: function (point, event) { var normalizedEvent = this.chart.pointer.normalize(event); point.fixedPosition = { chartX: normalizedEvent.chartX, chartY: normalizedEvent.chartY, plotX: point.plotX, plotY: point.plotY }; point.inDragMode = true; }, /** * Mouse move action during drag&drop. * * @private * * @param {global.Event} event Browser event, before normalization. * @param {Highcharts.Point} point The point that event occured. * * @return {void} */ onMouseMove: function (point, event) { if (point.fixedPosition && point.inDragMode) { var series = this, chart = series.chart, normalizedEvent = chart.pointer.normalize(event), diffX = point.fixedPosition.chartX - normalizedEvent.chartX, diffY = point.fixedPosition.chartY - normalizedEvent.chartY, newPlotX, newPlotY, graphLayoutsLookup = chart.graphLayoutsLookup; // At least 5px to apply change (avoids simple click): if (Math.abs(diffX) > 5 || Math.abs(diffY) > 5) { newPlotX = point.fixedPosition.plotX - diffX; newPlotY = point.fixedPosition.plotY - diffY; if (chart.isInsidePlot(newPlotX, newPlotY)) { point.plotX = newPlotX; point.plotY = newPlotY; point.hasDragged = true; this.redrawHalo(point); graphLayoutsLookup.forEach(function (layout) { layout.restartSimulation(); }); } } } }, /** * Mouse up action, finalizing drag&drop. * * @private * @param {Highcharts.Point} point The point that event occured. * @return {void} */ onMouseUp: function (point, event) { if (point.fixedPosition && point.hasDragged) { if (this.layout.enableSimulation) { this.layout.start(); } else { this.chart.redraw(); } point.inDragMode = point.hasDragged = false; if (!this.options.fixedDraggable) { delete point.fixedPosition; } } }, // Draggable mode: /** * Redraw halo on mousemove during the drag&drop action. * * @private * @param {Highcharts.Point} point The point that should show halo. * @return {void} */ redrawHalo: function (point) { if (point && this.halo) { this.halo.attr({ d: point.haloPath(this.options.states.hover.halo.size) }); } } }; /* * Draggable mode: */ addEvent(Chart, 'load', function () { var chart = this, mousedownUnbinder, mousemoveUnbinder, mouseupUnbinder; if (chart.container) { mousedownUnbinder = addEvent(chart.container, 'mousedown', function (event) { var point = chart.hoverPoint; if (point && point.series && point.series.hasDraggableNodes && point.series.options.draggable) { point.series.onMouseDown(point, event); mousemoveUnbinder = addEvent(chart.container, 'mousemove', function (e) { return point && point.series && point.series.onMouseMove(point, e); }); mouseupUnbinder = addEvent(chart.container.ownerDocument, 'mouseup', function (e) { mousemoveUnbinder(); mouseupUnbinder(); return point && point.series && point.series.onMouseUp(point, e); }); } }); } addEvent(chart, 'destroy', function () { mousedownUnbinder(); }); });
import"./switch-case.js";import"./bind-attr.js";import"./if.js";import"./repeat.js";
/* Highstock JS v8.2.0 (2020-08-20) All technical indicators for Highstock (c) 2010-2019 Pawel Fus License: www.highcharts.com/license */ (function(h){"object"===typeof module&&module.exports?(h["default"]=h,module.exports=h):"function"===typeof define&&define.amd?define("highcharts/indicators/indicators-all",["highcharts","highcharts/modules/stock"],function(t){h(t);h.Highcharts=t;return h}):h("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(h){function t(d,k,l,g){d.hasOwnProperty(k)||(d[k]=g.apply(null,l))}h=h?h._modules:{};t(h,"Mixins/IndicatorRequired.js",[h["Core/Utilities.js"]],function(d){var k=d.error;return{isParentLoaded:function(l, g,e,a,c){if(l)return a?a(l):!0;k(c||this.generateMessage(e,g));return!1},generateMessage:function(l,g){return'Error: "'+l+'" indicator type requires "'+g+'" indicator loaded before. Please read docs: https://api.highcharts.com/highstock/plotOptions.'+l}}});t(h,"Stock/Indicators/Indicators.js",[h["Core/Globals.js"],h["Mixins/IndicatorRequired.js"],h["Core/Utilities.js"]],function(d,k,l){var g=l.addEvent,e=l.error,a=l.extend,c=l.isArray,b=l.pick,f=l.seriesType,u=l.splat,x=d.Series,n=d.seriesTypes,q= d.seriesTypes.ohlc.prototype,m=k.generateMessage;g(d.Series,"init",function(b){b=b.options;b.useOhlcData&&"highcharts-navigator-series"!==b.id&&a(this,{pointValKey:q.pointValKey,keys:q.keys,pointArrayMap:q.pointArrayMap,toYData:q.toYData})});g(x,"afterSetOptions",function(b){b=b.options;var c=b.dataGrouping;c&&b.useOhlcData&&"highcharts-navigator-series"!==b.id&&(c.approximation="ohlc")});f("sma","line",{name:void 0,tooltip:{valueDecimals:4},linkedTo:void 0,compareToMain:!1,params:{index:0,period:14}}, {processData:function(){var b=this.options.compareToMain,c=this.linkedParent;x.prototype.processData.apply(this,arguments);c&&c.compareValue&&b&&(this.compareValue=c.compareValue)},bindTo:{series:!0,eventName:"updatedData"},hasDerivedData:!0,useCommonDataGrouping:!0,nameComponents:["period"],nameSuffixes:[],calculateOn:"init",requiredIndicators:[],requireIndicators:function(){var b={allLoaded:!0};this.requiredIndicators.forEach(function(c){n[c]?n[c].prototype.requireIndicators():(b.allLoaded=!1,b.needed= c)});return b},init:function(b,c){function f(){var b=a.points||[],c=(a.xData||[]).length,f=a.getValues(a.linkedParent,a.options.params)||{values:[],xData:[],yData:[]},e=[],p=!0;if(c&&!a.hasGroupedData&&a.visible&&a.points)if(a.cropped){if(a.xAxis){var n=a.xAxis.min;var g=a.xAxis.max}c=a.cropData(f.xData,f.yData,n,g);for(n=0;n<c.xData.length;n++)e.push([c.xData[n]].concat(u(c.yData[n])));c=f.xData.indexOf(a.xData[0]);n=f.xData.indexOf(a.xData[a.xData.length-1]);-1===c&&n===f.xData.length-2&&e[0][0]=== b[0].x&&e.shift();a.updateData(e)}else f.xData.length!==c-1&&f.xData.length!==c+1&&(p=!1,a.updateData(f.values));p&&(a.xData=f.xData,a.yData=f.yData,a.options.data=f.values);!1===a.bindTo.series&&(delete a.processedXData,a.isDirty=!0,a.redraw());a.isDirtyData=!1}var a=this,p=a.requireIndicators();if(!p.allLoaded)return e(m(a.type,p.needed));x.prototype.init.call(a,b,c);b.linkSeries();a.dataEventsToUnbind=[];if(!a.linkedParent)return e("Series "+a.options.linkedTo+" not found! Check `linkedTo`.",!1, b);a.dataEventsToUnbind.push(g(a.bindTo.series?a.linkedParent:a.linkedParent.xAxis,a.bindTo.eventName,f));if("init"===a.calculateOn)f();else var n=g(a.chart,a.calculateOn,function(){f();n()});return a},getName:function(){var c=this.name,a=[];c||((this.nameComponents||[]).forEach(function(c,f){a.push(this.options.params[c]+b(this.nameSuffixes[f],""))},this),c=(this.nameBase||this.type.toUpperCase())+(this.nameComponents?" ("+a.join(", ")+")":""));return c},getValues:function(b,a){var f=a.period,e= b.xData;b=b.yData;var u=b.length,n=0,p=0,g=[],x=[],q=[],l=-1;if(!(e.length<f)){for(c(b[0])&&(l=a.index?a.index:0);n<f-1;)p+=0>l?b[n]:b[n][l],n++;for(a=n;a<u;a++){p+=0>l?b[a]:b[a][l];var m=[e[a],p/f];g.push(m);x.push(m[0]);q.push(m[1]);p-=0>l?b[a-n]:b[a-n][l]}return{values:g,xData:x,yData:q}}},destroy:function(){this.dataEventsToUnbind.forEach(function(b){b()});x.prototype.destroy.apply(this,arguments)}});""});t(h,"Stock/Indicators/ADIndicator.js",[h["Core/Utilities.js"]],function(d){var k=d.error; d=d.seriesType;d("ad","sma",{params:{volumeSeriesID:"volume"}},{nameComponents:!1,nameBase:"Accumulation/Distribution",getValues:function(l,g){var e=g.period,a=l.xData,c=l.yData,b=g.volumeSeriesID,f=l.chart.get(b);g=f&&f.yData;var u=c?c.length:0,x=[],n=[],q=[];if(!(a.length<=e&&u&&4!==c[0].length)){if(f){for(;e<u;e++){l=x.length;b=c[e][1];f=c[e][2];var m=c[e][3],p=g[e];b=[a[e],m===b&&m===f||b===f?0:(2*m-f-b)/(b-f)*p];0<l&&(b[1]+=x[l-1][1]);x.push(b);n.push(b[0]);q.push(b[1])}return{values:x,xData:n, yData:q}}k("Series "+b+" not found! Check `volumeSeriesID`.",!0,l.chart)}}});""});t(h,"Stock/Indicators/AOIndicator.js",[h["Core/Globals.js"],h["Core/Utilities.js"]],function(d,k){var l=k.correctFloat,g=k.isArray;k=k.seriesType;k("ao","sma",{greaterBarColor:"#06B535",lowerBarColor:"#F21313",threshold:0,groupPadding:.2,pointPadding:.2,crisp:!1,states:{hover:{halo:{size:0}}}},{nameBase:"AO",nameComponents:!1,markerAttribs:d.noop,getColumnMetrics:d.seriesTypes.column.prototype.getColumnMetrics,crispCol:d.seriesTypes.column.prototype.crispCol, translate:d.seriesTypes.column.prototype.translate,drawPoints:d.seriesTypes.column.prototype.drawPoints,drawGraph:function(){var e=this.options,a=this.points,c=e.greaterBarColor;e=e.lowerBarColor;var b=a[0];if(!this.userOptions.color&&b)for(b.color=c,b=1;b<a.length;b++)a[b].color=a[b].y>a[b-1].y?c:a[b].y<a[b-1].y?e:a[b-1].color},getValues:function(e){var a=e.xData||[];e=e.yData||[];var c=e.length,b=[],f=[],u=[],x=0,n=0,q;if(!(34>=a.length)&&g(e[0])&&4===e[0].length){for(q=0;33>q;q++){var m=(e[q][1]+ e[q][2])/2;29<=q&&(x=l(x+m));n=l(n+m)}for(q=33;q<c;q++){m=(e[q][1]+e[q][2])/2;x=l(x+m);n=l(n+m);m=x/5;var p=n/34;m=l(m-p);b.push([a[q],m]);f.push(a[q]);u.push(m);m=q+1-5;p=q+1-34;x=l(x-(e[m][1]+e[m][2])/2);n=l(n-(e[p][1]+e[p][2])/2)}return{values:b,xData:f,yData:u}}}});""});t(h,"Mixins/MultipleLines.js",[h["Core/Globals.js"],h["Core/Utilities.js"]],function(d,k){var l=k.defined,g=k.error,e=k.merge,a=d.seriesTypes.sma;return{pointArrayMap:["top","bottom"],pointValKey:"top",linesApiNames:["bottomLine"], getTranslatedLinesNames:function(c){var b=[];(this.pointArrayMap||[]).forEach(function(a){a!==c&&b.push("plot"+a.charAt(0).toUpperCase()+a.slice(1))});return b},toYData:function(c){var b=[];(this.pointArrayMap||[]).forEach(function(a){b.push(c[a])});return b},translate:function(){var c=this,b=c.pointArrayMap,f=[],e;f=c.getTranslatedLinesNames();a.prototype.translate.apply(c,arguments);c.points.forEach(function(a){b.forEach(function(b,u){e=a[b];null!==e&&(a[f[u]]=c.yAxis.toPixels(e,!0))})})},drawGraph:function(){var c= this,b=c.linesApiNames,f=c.points,u=f.length,x=c.options,n=c.graph,q={options:{gapSize:x.gapSize}},m=[],p;c.getTranslatedLinesNames(c.pointValKey).forEach(function(b,c){for(m[c]=[];u--;)p=f[u],m[c].push({x:p.x,plotX:p.plotX,plotY:p[b],isNull:!l(p[b])});u=f.length});b.forEach(function(b,f){m[f]?(c.points=m[f],x[b]?c.options=e(x[b].styles,q):g('Error: "There is no '+b+' in DOCS options declared. Check if linesApiNames are consistent with your DOCS line names." at mixin/multiple-line.js:34'),c.graph= c["graph"+b],a.prototype.drawGraph.call(c),c["graph"+b]=c.graph):g('Error: "'+b+" doesn't have equivalent in pointArrayMap. To many elements in linesApiNames relative to pointArrayMap.\"")});c.points=f;c.options=x;c.graph=n;a.prototype.drawGraph.call(c)}}});t(h,"Stock/Indicators/AroonIndicator.js",[h["Core/Utilities.js"],h["Mixins/MultipleLines.js"]],function(d,k){function l(a,c){var b=a[0],f=0,e;for(e=1;e<a.length;e++)if("max"===c&&a[e]>=b||"min"===c&&a[e]<=b)b=a[e],f=e;return f}var g=d.merge,e= d.pick;d=d.seriesType;d("aroon","sma",{params:{period:25},marker:{enabled:!1},tooltip:{pointFormat:'<span style="color:{point.color}">\u25cf</span><b> {series.name}</b><br/>Aroon Up: {point.y}<br/>Aroon Down: {point.aroonDown}<br/>'},aroonDown:{styles:{lineWidth:1,lineColor:void 0}},dataGrouping:{approximation:"averages"}},g(k,{nameBase:"Aroon",pointArrayMap:["y","aroonDown"],pointValKey:"y",linesApiNames:["aroonDown"],getValues:function(a,c){c=c.period;var b=a.xData,f=(a=a.yData)?a.length:0,u=[], g=[],n=[],q;for(q=c-1;q<f;q++){var m=a.slice(q-c+1,q+2);var p=l(m.map(function(b){return e(b[2],b)}),"min");m=l(m.map(function(b){return e(b[1],b)}),"max");m=m/c*100;p=p/c*100;b[q+1]&&(u.push([b[q+1],m,p]),g.push(b[q+1]),n.push([m,p]))}return{values:u,xData:g,yData:n}}}));""});t(h,"Stock/Indicators/AroonOscillatorIndicator.js",[h["Core/Globals.js"],h["Mixins/MultipleLines.js"],h["Mixins/IndicatorRequired.js"],h["Core/Utilities.js"]],function(d,k,l,g){var e=g.merge;g=g.seriesType;var a=d.seriesTypes.aroon; g("aroonoscillator","aroon",{params:{period:25},tooltip:{pointFormat:'<span style="color:{point.color}">\u25cf</span><b> {series.name}</b>: {point.y}'}},e(k,{nameBase:"Aroon Oscillator",pointArrayMap:["y"],pointValKey:"y",linesApiNames:[],init:function(){var c=arguments,b=this;l.isParentLoaded(a,"aroon",b.type,function(a){a.prototype.init.apply(b,c)})},getValues:function(c,b){var f=[],e=[],g=[];c=a.prototype.getValues.call(this,c,b);for(b=0;b<c.yData.length;b++){var n=c.yData[b][0];var q=c.yData[b][1]; n-=q;f.push([c.xData[b],n]);e.push(c.xData[b]);g.push(n)}return{values:f,xData:e,yData:g}}}));""});t(h,"Stock/Indicators/ATRIndicator.js",[h["Core/Utilities.js"]],function(d){function k(e,a){return Math.max(e[1]-e[2],a===g?0:Math.abs(e[1]-a[3]),a===g?0:Math.abs(e[2]-a[3]))}var l=d.isArray;d=d.seriesType;var g;d("atr","sma",{params:{period:14}},{getValues:function(e,a){a=a.period;var c=e.xData,b=(e=e.yData)?e.length:0,f=1,g=0,x=0,n=[],q=[],m=[],p;var d=[[c[0],e[0]]];if(!(c.length<=a)&&l(e[0])&&4=== e[0].length){for(p=1;p<=b;p++)if(d.push([c[p],e[p]]),a<f){var w=a;var r=c[p-1],A=k(e[p-1],e[p-2]);w=[r,(g*(w-1)+A)/w];g=w[1];n.push(w);q.push(w[0]);m.push(w[1])}else a===f?(g=x/(p-1),n.push([c[p-1],g]),q.push(c[p-1]),m.push(g)):x+=k(e[p-1],e[p-2]),f++;return{values:n,xData:q,yData:m}}}});""});t(h,"Stock/Indicators/BBIndicator.js",[h["Core/Globals.js"],h["Core/Utilities.js"],h["Mixins/MultipleLines.js"]],function(d,k,l){var g=k.isArray,e=k.merge;k=k.seriesType;var a=d.seriesTypes.sma;k("bb","sma", {params:{period:20,standardDeviation:2,index:3},bottomLine:{styles:{lineWidth:1,lineColor:void 0}},topLine:{styles:{lineWidth:1,lineColor:void 0}},tooltip:{pointFormat:'<span style="color:{point.color}">\u25cf</span><b> {series.name}</b><br/>Top: {point.top}<br/>Middle: {point.middle}<br/>Bottom: {point.bottom}<br/>'},marker:{enabled:!1},dataGrouping:{approximation:"averages"}},e(l,{pointArrayMap:["top","middle","bottom"],pointValKey:"middle",nameComponents:["period","standardDeviation"],linesApiNames:["topLine", "bottomLine"],init:function(){a.prototype.init.apply(this,arguments);this.options=e({topLine:{styles:{lineColor:this.color}},bottomLine:{styles:{lineColor:this.color}}},this.options)},getValues:function(c,b){var f=b.period,e=b.standardDeviation,x=c.xData,n=(c=c.yData)?c.length:0,q=[],l=[],p=[],k;if(!(x.length<f)){var w=g(c[0]);for(k=f;k<=n;k++){var r=x.slice(k-f,k);var d=c.slice(k-f,k);var h=a.prototype.getValues.call(this,{xData:r,yData:d},b);r=h.xData[0];h=h.yData[0];for(var z=0,v=d.length,y=0;y< v;y++){var E=(w?d[y][b.index]:d[y])-h;z+=E*E}E=Math.sqrt(z/(v-1));d=h+e*E;E=h-e*E;q.push([r,d,h,E]);l.push(r);p.push([d,h,E])}return{values:q,xData:l,yData:p}}}}));""});t(h,"Stock/Indicators/CCIIndicator.js",[h["Core/Utilities.js"]],function(d){function k(g){return g.reduce(function(e,a){return e+a},0)}var l=d.isArray;d=d.seriesType;d("cci","sma",{params:{period:14}},{getValues:function(g,e){e=e.period;var a=g.xData,c=(g=g.yData)?g.length:0,b=[],f=1,u=[],x=[],n=[];if(!(a.length<=e)&&l(g[0])&&4=== g[0].length){for(;f<e;){var q=g[f-1];b.push((q[1]+q[2]+q[3])/3);f++}for(f=e;f<=c;f++){q=g[f-1];q=(q[1]+q[2]+q[3])/3;var m=b.push(q);var p=b.slice(m-e);m=k(p)/e;var d,w=p.length,r=0;for(d=0;d<w;d++)r+=Math.abs(m-p[d]);p=r/e;q=(q-m)/(.015*p);u.push([a[f-1],q]);x.push(a[f-1]);n.push(q)}return{values:u,xData:x,yData:n}}}});""});t(h,"Stock/Indicators/CMFIndicator.js",[h["Core/Utilities.js"]],function(d){d=d.seriesType;d("cmf","sma",{params:{period:14,volumeSeriesID:"volume"}},{nameBase:"Chaikin Money Flow", isValid:function(){var k=this.chart,l=this.options,g=this.linkedParent;k=this.volumeSeries||(this.volumeSeries=k.get(l.params.volumeSeriesID));var e=g&&g.yData&&4===g.yData[0].length;return!!(g&&k&&g.xData&&g.xData.length>=l.params.period&&k.xData&&k.xData.length>=l.params.period&&e)},getValues:function(k,l){if(this.isValid())return this.getMoneyFlow(k.xData,k.yData,this.volumeSeries.yData,l.period)},getMoneyFlow:function(k,l,g,e){function a(b,c){var a=b[1],f=b[2];b=b[3];return null!==c&&null!==a&& null!==f&&null!==b&&a!==f?(b-f-(a-b))/(a-f)*c:(p=m,null)}var c=l.length,b=[],f=0,u=0,x=[],n=[],q=[],m,p=-1;if(0<e&&e<=c){for(m=0;m<e;m++)b[m]=a(l[m],g[m]),f+=g[m],u+=b[m];x.push(k[m-1]);n.push(m-p>=e&&0!==f?u/f:null);for(q.push([x[0],n[0]]);m<c;m++){b[m]=a(l[m],g[m]);f-=g[m-e];f+=g[m];u-=b[m-e];u+=b[m];var d=[k[m],m-p>=e?u/f:null];x.push(d[0]);n.push(d[1]);q.push([d[0],d[1]])}}return{values:q,xData:x,yData:n}}});""});t(h,"Stock/Indicators/DPOIndicator.js",[h["Core/Utilities.js"]],function(d){function k(e, a,c,b,f){a=g(a[c][b],a[c]);return f?l(e-a):l(e+a)}var l=d.correctFloat,g=d.pick;d=d.seriesType;d("dpo","sma",{params:{period:21}},{nameBase:"DPO",getValues:function(e,a){var c=a.period;a=a.index;var b=c+Math.floor(c/2+1),f=e.xData||[];e=e.yData||[];var u=e.length,l=[],n=[],q=[],m=0,p,d;if(!(f.length<=b)){for(p=0;p<c-1;p++)m=k(m,e,p,a);for(d=0;d<=u-b;d++){var w=d+c-1;p=d+b-1;m=k(m,e,w,a);w=g(e[p][a],e[p]);w-=m/c;m=k(m,e,d,a,!0);l.push([f[p],w]);n.push(f[p]);q.push(w)}return{values:l,xData:n,yData:q}}}}); ""});t(h,"Stock/Indicators/EMAIndicator.js",[h["Core/Utilities.js"]],function(d){var k=d.correctFloat,l=d.isArray;d=d.seriesType;d("ema","sma",{params:{index:3,period:9}},{accumulatePeriodPoints:function(g,e,a){for(var c=0,b=0,f;b<g;)f=0>e?a[b]:a[b][e],c+=f,b++;return c},calculateEma:function(g,e,a,c,b,f,u){g=g[a-1];e=0>f?e[a-1]:e[a-1][f];c="undefined"===typeof b?u:k(e*c+b*(1-c));return[g,c]},getValues:function(g,e){var a=e.period,c=g.xData,b=(g=g.yData)?g.length:0,f=2/(a+1),u=[],x=[],n=[],q=-1;if(!(b< a)){l(g[0])&&(q=e.index?e.index:0);e=this.accumulatePeriodPoints(a,q,g);for(e/=a;a<b+1;a++){var m=this.calculateEma(c,g,a,f,m,q,e);u.push(m);x.push(m[0]);n.push(m[1]);m=m[1]}return{values:u,xData:x,yData:n}}}});""});t(h,"Stock/Indicators/ChaikinIndicator.js",[h["Core/Globals.js"],h["Core/Utilities.js"],h["Mixins/IndicatorRequired.js"]],function(d,k,l){var g=k.correctFloat,e=k.error;k=k.seriesType;var a=d.seriesTypes.ema,c=d.seriesTypes.ad;k("chaikin","ema",{params:{volumeSeriesID:"volume",periods:[3, 10]}},{nameBase:"Chaikin Osc",nameComponents:["periods"],init:function(){var b=arguments,c=this;l.isParentLoaded(a,"ema",c.type,function(a){a.prototype.init.apply(c,b)})},getValues:function(b,f){var u=f.periods,l=f.period,n=[],q=[],m=[],p;if(2!==u.length||u[1]<=u[0])e('Error: "Chaikin requires two periods. Notice, first period should be lower than the second one."');else if(f=c.prototype.getValues.call(this,b,{volumeSeriesID:f.volumeSeriesID,period:l}))if(b=a.prototype.getValues.call(this,f,{period:u[0]}), f=a.prototype.getValues.call(this,f,{period:u[1]}),b&&f){u=u[1]-u[0];for(p=0;p<f.yData.length;p++)l=g(b.yData[p+u]-f.yData[p]),n.push([f.xData[p],l]),q.push(f.xData[p]),m.push(l);return{values:n,xData:q,yData:m}}}});""});t(h,"Stock/Indicators/DEMAIndicator.js",[h["Core/Globals.js"],h["Core/Utilities.js"],h["Mixins/IndicatorRequired.js"]],function(d,k,l){var g=k.correctFloat,e=k.isArray;k=k.seriesType;var a=d.seriesTypes.ema;k("dema","ema",{},{init:function(){var c=arguments,b=this;l.isParentLoaded(a, "ema",b.type,function(a){a.prototype.init.apply(b,c)})},getEMA:function(c,b,f,e,g,n){return a.prototype.calculateEma(n||[],c,"undefined"===typeof g?1:g,this.chart.series[0].EMApercent,b,"undefined"===typeof e?-1:e,f)},getValues:function(c,b){var f=b.period,l=2*f,x=c.xData,n=c.yData,q=n?n.length:0,m=-1,p=[],k=[],w=[],r=0,d=[],h;c.EMApercent=2/(f+1);if(!(q<2*f-1)){e(n[0])&&(m=b.index?b.index:0);c=a.prototype.accumulatePeriodPoints(f,m,n);b=c/f;c=0;for(h=f;h<q+2;h++){h<q+1&&(r=this.getEMA(n,z,b,m,h)[1], d.push(r));var z=r;if(h<l)c+=r;else{h===l&&(b=c/f);r=d[h-f-1];var v=this.getEMA([r],v,b)[1];var y=[x[h-2],g(2*r-v)];p.push(y);k.push(y[0]);w.push(y[1])}}return{values:p,xData:k,yData:w}}}});""});t(h,"Stock/Indicators/TEMAIndicator.js",[h["Core/Globals.js"],h["Core/Utilities.js"],h["Mixins/IndicatorRequired.js"]],function(d,k,l){var g=k.correctFloat,e=k.isArray;k=k.seriesType;var a=d.seriesTypes.ema;k("tema","ema",{},{init:function(){var c=arguments,b=this;l.isParentLoaded(a,"ema",b.type,function(a){a.prototype.init.apply(b, c)})},getEMA:function(c,b,f,e,g,n){return a.prototype.calculateEma(n||[],c,"undefined"===typeof g?1:g,this.chart.series[0].EMApercent,b,"undefined"===typeof e?-1:e,f)},getTemaPoint:function(a,b,f,e){return[a[e-3],g(3*f.level1-3*f.level2+f.level3)]},getValues:function(c,b){var f=b.period,g=2*f,l=3*f,n=c.xData,q=c.yData,m=q?q.length:0,p=-1,k=[],w=[],r=[],d=[],h=[],z,v,y={};c.EMApercent=2/(f+1);if(!(m<3*f-2)){e(q[0])&&(p=b.index?b.index:0);c=a.prototype.accumulatePeriodPoints(f,p,q);b=c/f;c=0;for(z= f;z<m+3;z++){z<m+1&&(y.level1=this.getEMA(q,E,b,p,z)[1],d.push(y.level1));var E=y.level1;if(z<g)c+=y.level1;else{z===g&&(b=c/f,c=0);y.level1=d[z-f-1];y.level2=this.getEMA([y.level1],L,b)[1];h.push(y.level2);var L=y.level2;if(z<l)c+=y.level2;else{z===l&&(b=c/f);z===m+1&&(y.level1=d[z-f-1],y.level2=this.getEMA([y.level1],L,b)[1],h.push(y.level2));y.level1=d[z-f-2];y.level2=h[z-2*f-1];y.level3=this.getEMA([y.level2],y.prevLevel3,b)[1];if(v=this.getTemaPoint(n,l,y,z))k.push(v),w.push(v[0]),r.push(v[1]); y.prevLevel3=y.level3}}}return{values:k,xData:w,yData:r}}}});""});t(h,"Stock/Indicators/TRIXIndicator.js",[h["Core/Globals.js"],h["Core/Utilities.js"],h["Mixins/IndicatorRequired.js"]],function(d,k,l){var g=k.correctFloat;k=k.seriesType;var e=d.seriesTypes.tema;k("trix","tema",{},{init:function(){var a=arguments,c=this;l.isParentLoaded(e,"tema",c.type,function(b){b.prototype.init.apply(c,a)})},getTemaPoint:function(a,c,b,f){if(f>c)var e=[a[f-3],0!==b.prevLevel3?g(b.level3-b.prevLevel3)/b.prevLevel3* 100:null];return e}});""});t(h,"Stock/Indicators/APOIndicator.js",[h["Core/Globals.js"],h["Core/Utilities.js"],h["Mixins/IndicatorRequired.js"]],function(d,k,l){var g=k.error;k=k.seriesType;var e=d.seriesTypes.ema;k("apo","ema",{params:{periods:[10,20]}},{nameBase:"APO",nameComponents:["periods"],init:function(){var a=arguments,c=this;l.isParentLoaded(e,"ema",c.type,function(b){b.prototype.init.apply(c,a)})},getValues:function(a,c){var b=c.periods,f=c.index;c=[];var l=[],d=[],n;if(2!==b.length||b[1]<= b[0])g('Error: "APO requires two periods. Notice, first period should be lower than the second one."');else{var q=e.prototype.getValues.call(this,a,{index:f,period:b[0]});a=e.prototype.getValues.call(this,a,{index:f,period:b[1]});if(q&&a){b=b[1]-b[0];for(n=0;n<a.yData.length;n++)f=q.yData[n+b]-a.yData[n],c.push([a.xData[n],f]),l.push(a.xData[n]),d.push(f);return{values:c,xData:l,yData:d}}}}});""});t(h,"Stock/Indicators/IKHIndicator.js",[h["Core/Globals.js"],h["Core/Color.js"],h["Core/Utilities.js"]], function(d,k,l){function g(b){return b.reduce(function(b,a){return Math.max(b,a[1])},-Infinity)}function e(b){return b.reduce(function(b,a){return Math.min(b,a[2])},Infinity)}function a(b){return{high:g(b),low:e(b)}}function c(b){var a,c,f,e,g;b.series.forEach(function(b){if(b.xData)for(e=b.xData,g=c=b.xIncrement?1:e.length-1;0<g;g--)if(f=e[g]-e[g-1],a===p||f<a)a=f});return a}function b(b,a,c,f){if(b&&a&&c&&f){var e=a.plotX-b.plotX;a=a.plotY-b.plotY;var g=f.plotX-c.plotX;f=f.plotY-c.plotY;var n=b.plotX- c.plotX,p=b.plotY-c.plotY;c=(-a*n+e*p)/(-g*a+e*f);g=(g*p-f*n)/(-g*a+e*f);if(0<=c&&1>=c&&0<=g&&1>=g)return{plotX:b.plotX+g*e,plotY:b.plotY+g*a}}return!1}function f(b){var a=b.indicator;a.points=b.points;a.nextPoints=b.nextPoints;a.color=b.color;a.options=q(b.options.senkouSpan.styles,b.gap);a.graph=b.graph;a.fillGraph=!0;h.prototype.drawGraph.call(a)}var u=k.parse,x=l.defined,n=l.isArray,q=l.merge,m=l.objectEach;k=l.seriesType;var p,h=d.seriesTypes.sma;d.approximations["ichimoku-averages"]=function(){var b= [],a;[].forEach.call(arguments,function(c,f){b.push(d.approximations.average(c));a=!a&&"undefined"===typeof b[f]});return a?void 0:b};k("ikh","sma",{params:{period:26,periodTenkan:9,periodSenkouSpanB:52},marker:{enabled:!1},tooltip:{pointFormat:'<span style="color:{point.color}">\u25cf</span> <b> {series.name}</b><br/>TENKAN SEN: {point.tenkanSen:.3f}<br/>KIJUN SEN: {point.kijunSen:.3f}<br/>CHIKOU SPAN: {point.chikouSpan:.3f}<br/>SENKOU SPAN A: {point.senkouSpanA:.3f}<br/>SENKOU SPAN B: {point.senkouSpanB:.3f}<br/>'}, tenkanLine:{styles:{lineWidth:1,lineColor:void 0}},kijunLine:{styles:{lineWidth:1,lineColor:void 0}},chikouLine:{styles:{lineWidth:1,lineColor:void 0}},senkouSpanA:{styles:{lineWidth:1,lineColor:void 0}},senkouSpanB:{styles:{lineWidth:1,lineColor:void 0}},senkouSpan:{styles:{fill:"rgba(255, 0, 0, 0.5)"}},dataGrouping:{approximation:"ichimoku-averages"}},{pointArrayMap:["tenkanSen","kijunSen","chikouSpan","senkouSpanA","senkouSpanB"],pointValKey:"tenkanSen",nameComponents:["periodSenkouSpanB","period", "periodTenkan"],init:function(){h.prototype.init.apply(this,arguments);this.options=q({tenkanLine:{styles:{lineColor:this.color}},kijunLine:{styles:{lineColor:this.color}},chikouLine:{styles:{lineColor:this.color}},senkouSpanA:{styles:{lineColor:this.color,fill:u(this.color).setOpacity(.5).get()}},senkouSpanB:{styles:{lineColor:this.color,fill:u(this.color).setOpacity(.5).get()}},senkouSpan:{styles:{fill:u(this.color).setOpacity(.2).get()}}},this.options)},toYData:function(b){return[b.tenkanSen,b.kijunSen, b.chikouSpan,b.senkouSpanA,b.senkouSpanB]},translate:function(){var b=this;h.prototype.translate.apply(b);b.points.forEach(function(a){b.pointArrayMap.forEach(function(c){x(a[c])&&(a["plot"+c]=b.yAxis.toPixels(a[c],!0),a.plotY=a["plot"+c],a.tooltipPos=[a.plotX,a["plot"+c]],a.isNull=!1)})})},drawGraph:function(){var a=this,c=a.points,e=c.length,g=a.options,n=a.graph,p=a.color,l={options:{gapSize:g.gapSize}},d=a.pointArrayMap.length,k=[[],[],[],[],[],[]],u={tenkanLine:k[0],kijunLine:k[1],chikouLine:k[2], senkouSpanA:k[3],senkouSpanB:k[4],senkouSpan:k[5]},C=[],D=a.options.senkouSpan,t=D.color||D.styles.fill,N=D.negativeColor,J=[[],[]],M=[[],[]],P=0,K,Q,O;for(a.ikhMap=u;e--;){var F=c[e];for(K=0;K<d;K++)D=a.pointArrayMap[K],x(F[D])&&k[K].push({plotX:F.plotX,plotY:F["plot"+D],isNull:!1});N&&e!==c.length-1&&(D=u.senkouSpanB.length-1,F=b(u.senkouSpanA[D-1],u.senkouSpanA[D],u.senkouSpanB[D-1],u.senkouSpanB[D]),K={plotX:F.plotX,plotY:F.plotY,isNull:!1,intersectPoint:!0},F&&(u.senkouSpanA.splice(D,0,K),u.senkouSpanB.splice(D, 0,K),C.push(D)))}m(u,function(b,c){g[c]&&"senkouSpan"!==c&&(a.points=k[P],a.options=q(g[c].styles,l),a.graph=a["graph"+c],a.fillGraph=!1,a.color=p,h.prototype.drawGraph.call(a),a["graph"+c]=a.graph);P++});a.graphCollection&&a.graphCollection.forEach(function(b){a[b].destroy();delete a[b]});a.graphCollection=[];if(N&&u.senkouSpanA[0]&&u.senkouSpanB[0]){C.unshift(0);C.push(u.senkouSpanA.length-1);for(d=0;d<C.length-1;d++){D=C[d];F=C[d+1];e=u.senkouSpanB.slice(D,F+1);D=u.senkouSpanA.slice(D,F+1);if(1<= Math.floor(e.length/2))if(F=Math.floor(e.length/2),e[F].plotY===D[F].plotY){for(O=K=F=0;O<e.length;O++)F+=e[O].plotY,K+=D[O].plotY;F=F>K?0:1}else F=e[F].plotY>D[F].plotY?0:1;else F=e[0].plotY>D[0].plotY?0:1;J[F]=J[F].concat(e);M[F]=M[F].concat(D)}["graphsenkouSpanColor","graphsenkouSpanNegativeColor"].forEach(function(b,c){J[c].length&&M[c].length&&(Q=0===c?t:N,f({indicator:a,points:J[c],nextPoints:M[c],color:Q,options:g,gap:l,graph:a[b]}),a[b]=a.graph,a.graphCollection.push(b))})}else f({indicator:a, points:u.senkouSpanB,nextPoints:u.senkouSpanA,color:t,options:g,gap:l,graph:a.graphsenkouSpan}),a.graphsenkouSpan=a.graph;delete a.nextPoints;delete a.fillGraph;a.points=c;a.options=g;a.graph=n},getGraphPath:function(b){b=b||this.points;if(this.fillGraph&&this.nextPoints){var a=h.prototype.getGraphPath.call(this,this.nextPoints);a[0][0]="L";var c=h.prototype.getGraphPath.call(this,b);a=a.slice(0,c.length);for(var f=a.length-1;0<=f;f--)c.push(a[f])}else c=h.prototype.getGraphPath.apply(this,arguments); return c},getValues:function(b,f){var e=f.period,g=f.periodTenkan;f=f.periodSenkouSpanB;var l=b.xData,q=b.yData,u=q&&q.length||0;b=c(b.xAxis);var d=[],k=[],m;if(!(l.length<=e)&&n(q[0])&&4===q[0].length){var x=l[0]-e*b;for(m=0;m<e;m++)k.push(x+m*b);for(m=0;m<u;m++){if(m>=g){var h=q.slice(m-g,m);h=a(h);h=(h.high+h.low)/2}if(m>=e){var r=q.slice(m-e,m);r=a(r);r=(r.high+r.low)/2;var C=(h+r)/2}if(m>=f){var w=q.slice(m-f,m);w=a(w);w=(w.high+w.low)/2}x=q[m][3];var t=l[m];d[m]===p&&(d[m]=[]);d[m+e]===p&&(d[m+ e]=[]);d[m+e][0]=h;d[m+e][1]=r;d[m+e][2]=p;d[m][2]=x;m<=e&&(d[m+e][3]=p,d[m+e][4]=p);d[m+2*e]===p&&(d[m+2*e]=[]);d[m+2*e][3]=C;d[m+2*e][4]=w;k.push(t)}for(m=1;m<=e;m++)k.push(t+m*b);return{values:d,xData:k,yData:d}}}});""});t(h,"Stock/Indicators/KeltnerChannelsIndicator.js",[h["Core/Globals.js"],h["Core/Utilities.js"],h["Mixins/MultipleLines.js"]],function(d,k,l){var g=k.correctFloat,e=k.merge;k=k.seriesType;var a=d.seriesTypes.sma,c=d.seriesTypes.ema,b=d.seriesTypes.atr;k("keltnerchannels","sma", {params:{period:20,periodATR:10,multiplierATR:2},bottomLine:{styles:{lineWidth:1,lineColor:void 0}},topLine:{styles:{lineWidth:1,lineColor:void 0}},tooltip:{pointFormat:'<span style="color:{point.color}">\u25cf</span><b> {series.name}</b><br/>Upper Channel: {point.top}<br/>EMA({series.options.params.period}): {point.middle}<br/>Lower Channel: {point.bottom}<br/>'},marker:{enabled:!1},dataGrouping:{approximation:"averages"},lineWidth:1},e(l,{pointArrayMap:["top","middle","bottom"],pointValKey:"middle", nameBase:"Keltner Channels",nameComponents:["period","periodATR","multiplierATR"],linesApiNames:["topLine","bottomLine"],requiredIndicators:["ema","atr"],init:function(){a.prototype.init.apply(this,arguments);this.options=e({topLine:{styles:{lineColor:this.color}},bottomLine:{styles:{lineColor:this.color}}},this.options)},getValues:function(a,e){var f=e.period,n=e.periodATR,l=e.multiplierATR,m=a.yData;m=m?m.length:0;var p=[];e=c.prototype.getValues(a,{period:f,index:e.index});var d=b.prototype.getValues(a, {period:n}),k=[],u=[],h;if(!(m<f)){for(h=f;h<=m;h++){var B=e.values[h-f];var z=d.values[h-n];var v=B[0];a=g(B[1]+l*z[1]);z=g(B[1]-l*z[1]);B=B[1];p.push([v,a,B,z]);k.push(v);u.push([a,B,z])}return{values:p,xData:k,yData:u}}}}));""});t(h,"Stock/Indicators/MACDIndicator.js",[h["Core/Globals.js"],h["Core/Utilities.js"]],function(d,k){var l=k.correctFloat,g=k.defined,e=k.merge;k=k.seriesType;var a=d.seriesTypes.sma,c=d.seriesTypes.ema;k("macd","sma",{params:{shortPeriod:12,longPeriod:26,signalPeriod:9, period:26},signalLine:{zones:[],styles:{lineWidth:1,lineColor:void 0}},macdLine:{zones:[],styles:{lineWidth:1,lineColor:void 0}},threshold:0,groupPadding:.1,pointPadding:.1,crisp:!1,states:{hover:{halo:{size:0}}},tooltip:{pointFormat:'<span style="color:{point.color}">\u25cf</span> <b> {series.name}</b><br/>Value: {point.MACD}<br/>Signal: {point.signal}<br/>Histogram: {point.y}<br/>'},dataGrouping:{approximation:"averages"},minPointLength:0},{nameComponents:["longPeriod","shortPeriod","signalPeriod"], requiredIndicators:["ema"],pointArrayMap:["y","signal","MACD"],parallelArrays:["x","y","signal","MACD"],pointValKey:"y",markerAttribs:d.noop,getColumnMetrics:d.seriesTypes.column.prototype.getColumnMetrics,crispCol:d.seriesTypes.column.prototype.crispCol,init:function(){a.prototype.init.apply(this,arguments);this.options&&(this.options=e({signalLine:{styles:{lineColor:this.color}},macdLine:{styles:{color:this.color}}},this.options),this.macdZones={zones:this.options.macdLine.zones,startIndex:0},this.signalZones= {zones:this.macdZones.zones.concat(this.options.signalLine.zones),startIndex:this.macdZones.zones.length},this.resetZones=!0)},toYData:function(b){return[b.y,b.signal,b.MACD]},translate:function(){var b=this,a=["plotSignal","plotMACD"];d.seriesTypes.column.prototype.translate.apply(b);b.points.forEach(function(c){[c.signal,c.MACD].forEach(function(f,e){null!==f&&(c[a[e]]=b.yAxis.toPixels(f,!0))})})},destroy:function(){this.graph=null;this.graphmacd=this.graphmacd&&this.graphmacd.destroy();this.graphsignal= this.graphsignal&&this.graphsignal.destroy();a.prototype.destroy.apply(this,arguments)},drawPoints:d.seriesTypes.column.prototype.drawPoints,drawGraph:function(){for(var b=this,c=b.points,l=c.length,d=b.options,n=b.zones,q={options:{gapSize:d.gapSize}},m=[[],[]],p;l--;)p=c[l],g(p.plotMACD)&&m[0].push({plotX:p.plotX,plotY:p.plotMACD,isNull:!g(p.plotMACD)}),g(p.plotSignal)&&m[1].push({plotX:p.plotX,plotY:p.plotSignal,isNull:!g(p.plotMACD)});["macd","signal"].forEach(function(c,f){b.points=m[f];b.options= e(d[c+"Line"].styles,q);b.graph=b["graph"+c];b.currentLineZone=c+"Zones";b.zones=b[b.currentLineZone].zones;a.prototype.drawGraph.call(b);b["graph"+c]=b.graph});b.points=c;b.options=d;b.zones=n;b.currentLineZone=null},getZonesGraphs:function(b){var c=a.prototype.getZonesGraphs.call(this,b),e=c;this.currentLineZone&&(e=c.splice(this[this.currentLineZone].startIndex+1),e.length?e.splice(0,0,b[0]):e=[b[0]]);return e},applyZones:function(){var b=this.zones;this.zones=this.signalZones.zones;a.prototype.applyZones.call(this); this.graphmacd&&this.options.macdLine.zones.length&&this.graphmacd.hide();this.zones=b},getValues:function(b,a){var e=0,f=[],n=[],d=[];if(!(b.xData.length<a.longPeriod+a.signalPeriod)){var m=c.prototype.getValues(b,{period:a.shortPeriod});var p=c.prototype.getValues(b,{period:a.longPeriod});m=m.values;p=p.values;for(b=1;b<=m.length;b++)g(p[b-1])&&g(p[b-1][1])&&g(m[b+a.shortPeriod+1])&&g(m[b+a.shortPeriod+1][0])&&f.push([m[b+a.shortPeriod+1][0],0,null,m[b+a.shortPeriod+1][1]-p[b-1][1]]);for(b=0;b< f.length;b++)n.push(f[b][0]),d.push([0,null,f[b][3]]);a=c.prototype.getValues({xData:n,yData:d},{period:a.signalPeriod,index:2});a=a.values;for(b=0;b<f.length;b++)f[b][0]>=a[0][0]&&(f[b][2]=a[e][1],d[b]=[0,a[e][1],f[b][3]],null===f[b][3]?(f[b][1]=0,d[b][0]=0):(f[b][1]=l(f[b][3]-a[e][1]),d[b][0]=l(f[b][3]-a[e][1])),e++);return{values:f,xData:n,yData:d}}}});""});t(h,"Stock/Indicators/MFIIndicator.js",[h["Core/Utilities.js"]],function(d){function k(a){return a.reduce(function(a,b){return a+b})}function l(a){return(a[1]+ a[2]+a[3])/3}var g=d.error,e=d.isArray;d=d.seriesType;d("mfi","sma",{params:{period:14,volumeSeriesID:"volume",decimals:4}},{nameBase:"Money Flow Index",getValues:function(a,c){var b=c.period,f=a.xData,d=a.yData,h=d?d.length:0,n=c.decimals,q=1,m=a.chart.get(c.volumeSeriesID),p=m&&m.yData,C=[],w=[],r=[],A=[],B=[];if(!m)g("Series "+c.volumeSeriesID+" not found! Check `volumeSeriesID`.",!0,a.chart);else if(!(f.length<=b)&&e(d[0])&&4===d[0].length&&p){for(a=l(d[q]);q<b+1;)c=a,a=l(d[q]),c=a>=c,m=a*p[q], A.push(c?m:0),B.push(c?0:m),q++;for(b=q-1;b<h;b++)b>q-1&&(A.shift(),B.shift(),c=a,a=l(d[b]),c=a>c,m=a*p[b],A.push(c?m:0),B.push(c?0:m)),c=k(B),m=k(A),c=m/c,c=parseFloat((100-100/(1+c)).toFixed(n)),C.push([f[b],c]),w.push(f[b]),r.push(c);return{values:C,xData:w,yData:r}}}});""});t(h,"Stock/Indicators/MomentumIndicator.js",[h["Core/Utilities.js"]],function(d){function k(g,e,a,c,b){a=a[c-1][3]-a[c-b-1][3];e=e[c-1];g.shift();return[e,a]}var l=d.isArray;d=d.seriesType;d("momentum","sma",{params:{period:14}}, {nameBase:"Momentum",getValues:function(g,e){e=e.period;var a=g.xData,c=(g=g.yData)?g.length:0,b=a[0],f=[],d=[],h=[];if(!(a.length<=e)&&l(g[0])){var n=g[0][3];n=[[b,n]];for(b=e+1;b<c;b++){var q=k(n,a,g,b,e,void 0);f.push(q);d.push(q[0]);h.push(q[1])}q=k(n,a,g,b,e,void 0);f.push(q);d.push(q[0]);h.push(q[1]);return{values:f,xData:d,yData:h}}}});""});t(h,"Stock/Indicators/NATRIndicator.js",[h["Core/Globals.js"],h["Core/Utilities.js"]],function(d,k){k=k.seriesType;var l=d.seriesTypes.atr;k("natr","sma", {tooltip:{valueSuffix:"%"}},{requiredIndicators:["atr"],getValues:function(g,e){var a=l.prototype.getValues.apply(this,arguments),c=a.values.length,b=e.period-1,f=g.yData,d=0;if(a){for(;d<c;d++)a.yData[d]=a.values[d][1]/f[b][3]*100,a.values[d][1]=a.yData[d],b++;return a}}});""});t(h,"Stock/Indicators/PivotPointsIndicator.js",[h["Core/Globals.js"],h["Core/Utilities.js"]],function(d,k){function l(c,b){var e=c.series.pointArrayMap,g=e.length;for(a.prototype.pointClass.prototype[b].call(c);g--;)b="dataLabel"+ e[g],c[b]&&c[b].element&&c[b].destroy(),c[b]=null}var g=k.defined,e=k.isArray;k=k.seriesType;var a=d.seriesTypes.sma;k("pivotpoints","sma",{params:{period:28,algorithm:"standard"},marker:{enabled:!1},enableMouseTracking:!1,dataLabels:{enabled:!0,format:"{point.pivotLine}"},dataGrouping:{approximation:"averages"}},{nameBase:"Pivot Points",pointArrayMap:"R4 R3 R2 R1 P S1 S2 S3 S4".split(" "),pointValKey:"P",toYData:function(a){return[a.P]},translate:function(){var c=this;a.prototype.translate.apply(c); c.points.forEach(function(b){c.pointArrayMap.forEach(function(a){g(b[a])&&(b["plot"+a]=c.yAxis.toPixels(b[a],!0))})});c.plotEndPoint=c.xAxis.toPixels(c.endPoint,!0)},getGraphPath:function(c){for(var b=this,e=c.length,d=[[],[],[],[],[],[],[],[],[]],l=[],n=b.plotEndPoint,k=b.pointArrayMap.length,m,p,h;e--;){p=c[e];for(h=0;h<k;h++)m=b.pointArrayMap[h],g(p[m])&&d[h].push({plotX:p.plotX,plotY:p["plot"+m],isNull:!1},{plotX:n,plotY:p["plot"+m],isNull:!1},{plotX:n,plotY:null,isNull:!0});n=p.plotX}d.forEach(function(c){l= l.concat(a.prototype.getGraphPath.call(b,c))});return l},drawDataLabels:function(){var c=this,b=c.pointArrayMap,e,g,d;if(c.options.dataLabels.enabled){var l=c.points.length;b.concat([!1]).forEach(function(f,n){for(d=l;d--;)g=c.points[d],f?(g.y=g[f],g.pivotLine=f,g.plotY=g["plot"+f],e=g["dataLabel"+f],n&&(g["dataLabel"+b[n-1]]=g.dataLabel),g.dataLabels||(g.dataLabels=[]),g.dataLabels[0]=g.dataLabel=e=e&&e.element?e:null):g["dataLabel"+b[n-1]]=g.dataLabel;a.prototype.drawDataLabels.apply(c,arguments)})}}, getValues:function(a,b){var c=b.period,g=a.xData,d=(a=a.yData)?a.length:0;b=this[b.algorithm+"Placement"];var l=[],k=[],m=[],p;if(!(g.length<c)&&e(a[0])&&4===a[0].length){for(p=c+1;p<=d+c;p+=c){var h=g.slice(p-c-1,p);var w=a.slice(p-c-1,p);var r=h.length;var A=h[r-1];w=this.getPivotAndHLC(w);w=b(w);w=l.push([A].concat(w));k.push(A);m.push(l[w-1].slice(1))}this.endPoint=h[0]+(A-h[0])/r*c;return{values:l,xData:k,yData:m}}},getPivotAndHLC:function(a){var b=-Infinity,c=Infinity,e=a[a.length-1][3];a.forEach(function(a){b= Math.max(b,a[1]);c=Math.min(c,a[2])});return[(b+c+e)/3,b,c,e]},standardPlacement:function(a){var b=a[1]-a[2];return[null,null,a[0]+b,2*a[0]-a[2],a[0],2*a[0]-a[1],a[0]-b,null,null]},camarillaPlacement:function(a){var b=a[1]-a[2];return[a[3]+1.5*b,a[3]+1.25*b,a[3]+1.1666*b,a[3]+1.0833*b,a[0],a[3]-1.0833*b,a[3]-1.1666*b,a[3]-1.25*b,a[3]-1.5*b]},fibonacciPlacement:function(a){var b=a[1]-a[2];return[null,a[0]+b,a[0]+.618*b,a[0]+.382*b,a[0],a[0]-.382*b,a[0]-.618*b,a[0]-b,null]}},{destroyElements:function(){l(this, "destroyElements")},destroy:function(){l(this,"destroyElements")}});""});t(h,"Stock/Indicators/PPOIndicator.js",[h["Core/Globals.js"],h["Core/Utilities.js"],h["Mixins/IndicatorRequired.js"]],function(d,k,l){var g=k.correctFloat,e=k.error;k=k.seriesType;var a=d.seriesTypes.ema;k("ppo","ema",{params:{periods:[12,26]}},{nameBase:"PPO",nameComponents:["periods"],init:function(){var c=arguments,b=this;l.isParentLoaded(a,"ema",b.type,function(a){a.prototype.init.apply(b,c)})},getValues:function(c,b){var f= b.periods,d=b.index;b=[];var l=[],n=[],k;if(2!==f.length||f[1]<=f[0])e('Error: "PPO requires two periods. Notice, first period should be lower than the second one."');else{var m=a.prototype.getValues.call(this,c,{index:d,period:f[0]});c=a.prototype.getValues.call(this,c,{index:d,period:f[1]});if(m&&c){f=f[1]-f[0];for(k=0;k<c.yData.length;k++)d=g((m.yData[k+f]-c.yData[k])/c.yData[k]*100),b.push([c.xData[k],d]),l.push(c.xData[k]),n.push(d);return{values:b,xData:l,yData:n}}}}});""});t(h,"Mixins/ReduceArray.js", [],function(){return{minInArray:function(d,k){return d.reduce(function(d,g){return Math.min(d,g[k])},Number.MAX_VALUE)},maxInArray:function(d,k){return d.reduce(function(d,g){return Math.max(d,g[k])},-Number.MAX_VALUE)},getArrayExtremes:function(d,k,l){return d.reduce(function(g,e){return[Math.min(g[0],e[k]),Math.max(g[1],e[l])]},[Number.MAX_VALUE,-Number.MAX_VALUE])}}});t(h,"Stock/Indicators/PCIndicator.js",[h["Core/Utilities.js"],h["Mixins/ReduceArray.js"],h["Mixins/MultipleLines.js"]],function(d, k,l){var g=d.merge;d=d.seriesType;var e=k.getArrayExtremes;d("pc","sma",{params:{period:20},lineWidth:1,topLine:{styles:{lineColor:"#90ed7d",lineWidth:1}},bottomLine:{styles:{lineColor:"#f45b5b",lineWidth:1}},dataGrouping:{approximation:"averages"}},g(l,{pointArrayMap:["top","middle","bottom"],pointValKey:"middle",nameBase:"Price Channel",nameComponents:["period"],linesApiNames:["topLine","bottomLine"],getValues:function(a,c){c=c.period;var b=a.xData,f=(a=a.yData)?a.length:0,g=[],d=[],l=[],k;if(!(f< c)){for(k=c;k<=f;k++){var m=b[k-1];var p=a.slice(k-c,k);var h=e(p,2,1);p=h[1];var w=h[0];h=(p+w)/2;g.push([m,p,h,w]);d.push(m);l.push([p,h,w])}return{values:g,xData:d,yData:l}}}}));""});t(h,"Stock/Indicators/PriceEnvelopesIndicator.js",[h["Core/Globals.js"],h["Core/Utilities.js"]],function(d,k){var l=k.isArray,g=k.merge;k=k.seriesType;var e=d.seriesTypes.sma;k("priceenvelopes","sma",{marker:{enabled:!1},tooltip:{pointFormat:'<span style="color:{point.color}">\u25cf</span><b> {series.name}</b><br/>Top: {point.top}<br/>Middle: {point.middle}<br/>Bottom: {point.bottom}<br/>'}, params:{period:20,topBand:.1,bottomBand:.1},bottomLine:{styles:{lineWidth:1,lineColor:void 0}},topLine:{styles:{lineWidth:1}},dataGrouping:{approximation:"averages"}},{nameComponents:["period","topBand","bottomBand"],nameBase:"Price envelopes",pointArrayMap:["top","middle","bottom"],parallelArrays:["x","y","top","bottom"],pointValKey:"middle",init:function(){e.prototype.init.apply(this,arguments);this.options=g({topLine:{styles:{lineColor:this.color}},bottomLine:{styles:{lineColor:this.color}}},this.options)}, toYData:function(a){return[a.top,a.middle,a.bottom]},translate:function(){var a=this,c=["plotTop","plotMiddle","plotBottom"];e.prototype.translate.apply(a);a.points.forEach(function(b){[b.top,b.middle,b.bottom].forEach(function(e,g){null!==e&&(b[c[g]]=a.yAxis.toPixels(e,!0))})})},drawGraph:function(){for(var a=this,c=a.points,b=c.length,f=a.options,d=a.graph,l={options:{gapSize:f.gapSize}},n=[[],[]],k;b--;)k=c[b],n[0].push({plotX:k.plotX,plotY:k.plotTop,isNull:k.isNull}),n[1].push({plotX:k.plotX, plotY:k.plotBottom,isNull:k.isNull});["topLine","bottomLine"].forEach(function(b,c){a.points=n[c];a.options=g(f[b].styles,l);a.graph=a["graph"+b];e.prototype.drawGraph.call(a);a["graph"+b]=a.graph});a.points=c;a.options=f;a.graph=d;e.prototype.drawGraph.call(a)},getValues:function(a,c){var b=c.period,f=c.topBand,g=c.bottomBand,d=a.xData,k=(a=a.yData)?a.length:0,h=[],m=[],p=[],C;if(!(d.length<b)&&l(a[0])&&4===a[0].length){for(C=b;C<=k;C++){var w=d.slice(C-b,C);var r=a.slice(C-b,C);r=e.prototype.getValues.call(this, {xData:w,yData:r},c);w=r.xData[0];r=r.yData[0];var A=r*(1+f);var B=r*(1-g);h.push([w,A,r,B]);m.push(w);p.push([A,r,B])}return{values:h,xData:m,yData:p}}}});""});t(h,"Stock/Indicators/PSARIndicator.js",[h["Core/Utilities.js"]],function(d){d=d.seriesType;d("psar","sma",{lineWidth:0,marker:{enabled:!0},states:{hover:{lineWidthPlus:0}},params:{initialAccelerationFactor:.02,maxAccelerationFactor:.2,increment:.02,index:2,decimals:4}},{nameComponents:!1,getValues:function(d,l){var g=d.xData;d=d.yData;var e= d[0][1],a=l.maxAccelerationFactor,c=l.increment,b=l.initialAccelerationFactor,f=d[0][2],k=l.decimals,h=l.index,n=[],q=[],m=[],p=1,C;if(!(h>=d.length)){for(C=0;C<h;C++)e=Math.max(d[C][1],e),f=Math.min(d[C][2],parseFloat(f.toFixed(k)));var w=d[C][1]>f?1:-1;l=l.initialAccelerationFactor;var r=l*(e-f);n.push([g[h],f]);q.push(g[h]);m.push(parseFloat(f.toFixed(k)));for(C=h+1;C<d.length;C++){h=d[C-1][2];var A=d[C-2][2];var B=d[C-1][1];var z=d[C-2][1];var v=d[C][1];var y=d[C][2];null!==A&&null!==z&&null!== h&&null!==B&&null!==v&&null!==y&&(f=w===p?1===w?f+r<Math.min(A,h)?f+r:Math.min(A,h):f+r>Math.max(z,B)?f+r:Math.max(z,B):e,h=1===w?v>e?v:e:y<e?y:e,v=1===p&&y>f||-1===p&&v>f?1:-1,p=v,r=h,y=c,A=a,B=b,l=p===w?1===p&&r>e?l===A?A:parseFloat((l+y).toFixed(2)):-1===p&&r<e?l===A?A:parseFloat((l+y).toFixed(2)):l:B,e=h-f,r=l*e,n.push([g[C],parseFloat(f.toFixed(k))]),q.push(g[C]),m.push(parseFloat(f.toFixed(k))),p=w,w=v,e=h)}return{values:n,xData:q,yData:m}}}});""});t(h,"Stock/Indicators/ROCIndicator.js",[h["Core/Utilities.js"]], function(d){var k=d.isArray;d=d.seriesType;d("roc","sma",{params:{index:3,period:9}},{nameBase:"Rate of Change",getValues:function(d,g){var e=g.period,a=d.xData,c=(d=d.yData)?d.length:0,b=[],f=[],l=[],h=-1;if(!(a.length<=e)){k(d[0])&&(h=g.index);for(g=e;g<c;g++){var n=0>h?(n=d[g-e])?(d[g]-n)/n*100:null:(n=d[g-e][h])?(d[g][h]-n)/n*100:null;n=[a[g],n];b.push(n);f.push(n[0]);l.push(n[1])}return{values:b,xData:f,yData:l}}}});""});t(h,"Stock/Indicators/RSIIndicator.js",[h["Core/Utilities.js"]],function(d){var k= d.isArray;d=d.seriesType;d("rsi","sma",{params:{period:14,decimals:4}},{getValues:function(d,g){var e=g.period,a=d.xData,c=(d=d.yData)?d.length:0;g=g.decimals;var b=1,f=[],l=[],h=[],n=0,q=0,m;if(!(a.length<e)&&k(d[0])&&4===d[0].length){for(;b<e;){var p=parseFloat((d[b][3]-d[b-1][3]).toFixed(g));0<p?n+=p:q+=Math.abs(p);b++}var C=parseFloat((n/(e-1)).toFixed(g));for(m=parseFloat((q/(e-1)).toFixed(g));b<c;b++)p=parseFloat((d[b][3]-d[b-1][3]).toFixed(g)),0<p?(n=p,q=0):(n=0,q=Math.abs(p)),C=parseFloat(((C* (e-1)+n)/e).toFixed(g)),m=parseFloat(((m*(e-1)+q)/e).toFixed(g)),n=0===m?100:0===C?0:parseFloat((100-100/(1+C/m)).toFixed(g)),f.push([a[b],n]),l.push(a[b]),h.push(n);return{values:f,xData:l,yData:h}}}});""});t(h,"Stock/Indicators/StochasticIndicator.js",[h["Core/Globals.js"],h["Core/Utilities.js"],h["Mixins/ReduceArray.js"],h["Mixins/MultipleLines.js"]],function(d,k,l,g){var e=k.isArray,a=k.merge;k=k.seriesType;var c=d.seriesTypes.sma,b=l.getArrayExtremes;k("stochastic","sma",{params:{periods:[14, 3]},marker:{enabled:!1},tooltip:{pointFormat:'<span style="color:{point.color}">\u25cf</span><b> {series.name}</b><br/>%K: {point.y}<br/>%D: {point.smoothed}<br/>'},smoothedLine:{styles:{lineWidth:1,lineColor:void 0}},dataGrouping:{approximation:"averages"}},a(g,{nameComponents:["periods"],nameBase:"Stochastic",pointArrayMap:["y","smoothed"],parallelArrays:["x","y","smoothed"],pointValKey:"y",linesApiNames:["smoothedLine"],init:function(){c.prototype.init.apply(this,arguments);this.options=a({smoothedLine:{styles:{lineColor:this.color}}}, this.options)},getValues:function(a,d){var f=d.periods[0];d=d.periods[1];var g=a.xData,l=(a=a.yData)?a.length:0,k=[],p=[],h=[],u=null,r;if(!(l<f)&&e(a[0])&&4===a[0].length){for(r=f-1;r<l;r++){var A=a.slice(r-f+1,r+1);var B=b(A,2,1);var z=B[0];A=a[r][3]-z;z=B[1]-z;A=A/z*100;p.push(g[r]);h.push([A,null]);r>=f-1+(d-1)&&(u=c.prototype.getValues.call(this,{xData:p.slice(-d),yData:h.slice(-d)},{period:d}),u=u.yData[0]);k.push([g[r],A,u]);h[h.length-1][1]=u}return{values:k,xData:p,yData:h}}}}));""});t(h, "Stock/Indicators/SlowStochasticIndicator.js",[h["Core/Globals.js"],h["Core/Utilities.js"],h["Mixins/IndicatorRequired.js"]],function(d,k,l){k=k.seriesType;var g=d.seriesTypes;k("slowstochastic","stochastic",{params:{periods:[14,3,3]}},{nameBase:"Slow Stochastic",init:function(){var e=arguments,a=this;l.isParentLoaded(d.seriesTypes.stochastic,"stochastic",a.type,function(c){c.prototype.init.apply(a,e)})},getValues:function(e,a){var c=a.periods,b=g.stochastic.prototype.getValues.call(this,e,a);e={values:[], xData:[],yData:[]};a=0;if(b){e.xData=b.xData.slice(c[1]-1);b=b.yData.slice(c[1]-1);var d=g.sma.prototype.getValues.call(this,{xData:e.xData,yData:b},{index:1,period:c[2]});if(d){for(var l=e.xData.length;a<l;a++)e.yData[a]=[b[a][1],d.yData[a-c[2]+1]||null],e.values[a]=[e.xData[a],b[a][1],d.yData[a-c[2]+1]||null];return e}}}});""});t(h,"Stock/Indicators/SupertrendIndicator.js",[h["Core/Globals.js"],h["Core/Utilities.js"]],function(d,k){function l(a,b,c){return{index:b,close:a.yData[b][c],x:a.xData[b]}} var g=k.correctFloat,e=k.merge,a=k.seriesType,c=k.isArray,b=k.objectEach,f=d.seriesTypes.atr,h=d.seriesTypes.sma;a("supertrend","sma",{params:{multiplier:3,period:10},risingTrendColor:"#06B535",fallingTrendColor:"#F21313",changeTrendLine:{styles:{lineWidth:1,lineColor:"#333333",dashStyle:"LongDash"}}},{nameBase:"Supertrend",nameComponents:["multiplier","period"],requiredIndicators:["atr"],init:function(){h.prototype.init.apply(this,arguments);var a=this.options;a.cropThreshold=this.linkedParent.options.cropThreshold- (a.params.period-1)},drawGraph:function(){var a=this,c=a.options,d=a.linkedParent,f=d?d.points:[],g=a.points,k=a.graph,u=g.length,r=f.length-u;r=0<r?r:0;for(var A={options:{gapSize:c.gapSize}},B={top:[],bottom:[],intersect:[]},z={top:{styles:{lineWidth:c.lineWidth,lineColor:c.fallingTrendColor||c.color,dashStyle:c.dashStyle}},bottom:{styles:{lineWidth:c.lineWidth,lineColor:c.risingTrendColor||c.color,dashStyle:c.dashStyle}},intersect:c.changeTrendLine},v,y,E,t,G,H,D,I;u--;)v=g[u],y=g[u-1],E=f[u-1+ r],t=f[u-2+r],G=f[u+r],H=f[u+r+1],D=v.options.color,I={x:v.x,plotX:v.plotX,plotY:v.plotY,isNull:!1},!t&&E&&d.yData[E.index-1]&&(t=l(d,E.index-1,3)),!H&&G&&d.yData[G.index+1]&&(H=l(d,G.index+1,3)),!E&&t&&d.yData[t.index+1]?E=l(d,t.index+1,3):!E&&G&&d.yData[G.index-1]&&(E=l(d,G.index-1,3)),v&&E&&G&&t&&v.x!==E.x&&(v.x===G.x?(t=E,E=G):v.x===t.x?(E=t,t={close:d.yData[E.index-1][3],x:d.xData[E.index-1]}):H&&v.x===H.x&&(E=H,t=G)),y&&t&&E?(G={x:y.x,plotX:y.plotX,plotY:y.plotY,isNull:!1},v.y>=E.close&&y.y>= t.close?(v.color=D||c.fallingTrendColor||c.color,B.top.push(I)):v.y<E.close&&y.y<t.close?(v.color=D||c.risingTrendColor||c.color,B.bottom.push(I)):(B.intersect.push(I),B.intersect.push(G),B.intersect.push(e(G,{isNull:!0})),v.y>=E.close&&y.y<t.close?(v.color=D||c.fallingTrendColor||c.color,y.color=D||c.risingTrendColor||c.color,B.top.push(I),B.top.push(e(G,{isNull:!0}))):v.y<E.close&&y.y>=t.close&&(v.color=D||c.risingTrendColor||c.color,y.color=D||c.fallingTrendColor||c.color,B.bottom.push(I),B.bottom.push(e(G, {isNull:!0}))))):E&&(v.y>=E.close?(v.color=D||c.fallingTrendColor||c.color,B.top.push(I)):(v.color=D||c.risingTrendColor||c.color,B.bottom.push(I)));b(B,function(b,c){a.points=b;a.options=e(z[c].styles,A);a.graph=a["graph"+c+"Line"];h.prototype.drawGraph.call(a);a["graph"+c+"Line"]=a.graph});a.points=g;a.options=c;a.graph=k},getValues:function(a,b){var e=b.period;b=b.multiplier;var d=a.xData,l=a.yData,k=[],h=[],n=[],u=0===e?0:e-1,x=[],z=[],v;if(!(d.length<=e||!c(l[0])||4!==l[0].length||0>e)){a=f.prototype.getValues.call(this, a,{period:e}).yData;for(v=0;v<a.length;v++){var y=l[u+v];var t=l[u+v-1]||[];var L=x[v-1];var G=z[v-1];var H=n[v-1];0===v&&(L=G=H=0);e=g((y[1]+y[2])/2+b*a[v]);var D=g((y[1]+y[2])/2-b*a[v]);x[v]=e<L||t[3]>L?e:L;z[v]=D>G||t[3]<G?D:G;if(H===L&&y[3]<x[v]||H===G&&y[3]<z[v])var I=x[v];else if(H===L&&y[3]>x[v]||H===G&&y[3]>z[v])I=z[v];k.push([d[u+v],I]);h.push(d[u+v]);n.push(I)}return{values:k,xData:h,yData:n}}}});""});t(h,"Stock/Indicators/VBPIndicator.js",[h["Core/Globals.js"],h["Core/Series/Point.js"], h["Core/Utilities.js"]],function(d,k,l){var g=l.addEvent,e=l.animObject,a=l.arrayMax,c=l.arrayMin,b=l.correctFloat,f=l.error,h=l.extend,x=l.isArray;l=l.seriesType;var n=Math.abs,q=d.noop,m=d.seriesTypes.column.prototype;l("vbp","sma",{params:{ranges:12,volumeSeriesID:"volume"},zoneLines:{enabled:!0,styles:{color:"#0A9AC9",dashStyle:"LongDash",lineWidth:1}},volumeDivision:{enabled:!0,styles:{positiveColor:"rgba(144, 237, 125, 0.8)",negativeColor:"rgba(244, 91, 91, 0.8)"}},animationLimit:1E3,enableMouseTracking:!1, pointPadding:0,zIndex:-1,crisp:!0,dataGrouping:{enabled:!1},dataLabels:{allowOverlap:!0,enabled:!0,format:"P: {point.volumePos:.2f} | N: {point.volumeNeg:.2f}",padding:0,style:{fontSize:"7px"},verticalAlign:"top"}},{nameBase:"Volume by Price",bindTo:{series:!1,eventName:"afterSetExtremes"},calculateOn:"render",markerAttribs:q,drawGraph:q,getColumnMetrics:m.getColumnMetrics,crispCol:m.crispCol,init:function(a){d.seriesTypes.sma.prototype.init.apply(this,arguments);var b=this.options.params;var c=this.linkedParent; b=a.get(b.volumeSeriesID);this.addCustomEvents(c,b);return this},addCustomEvents:function(a,b){function c(){e.chart.redraw();e.setData([]);e.zoneStarts=[];e.zoneLinesSVG&&(e.zoneLinesSVG.destroy(),delete e.zoneLinesSVG)}var e=this;e.dataEventsToUnbind.push(g(a,"remove",function(){c()}));b&&e.dataEventsToUnbind.push(g(b,"remove",function(){c()}));return e},animate:function(a){var b=this,c=b.chart.inverted,d=b.group,f={};!a&&d&&(a=c?"translateY":"translateX",c=c?b.yAxis.top:b.xAxis.left,d["forceAnimate:"+ a]=!0,f[a]=c,d.animate(f,h(e(b.options.animation),{step:function(a,c){b.group.attr({scaleX:Math.max(.001,c.pos)})}})))},drawPoints:function(){this.options.volumeDivision.enabled&&(this.posNegVolume(!0,!0),m.drawPoints.apply(this,arguments),this.posNegVolume(!1,!1));m.drawPoints.apply(this,arguments)},posNegVolume:function(a,b){var c=b?["positive","negative"]:["negative","positive"],e=this.options.volumeDivision,d=this.points.length,f=[],g=[],l=0,k;a?(this.posWidths=f,this.negWidths=g):(f=this.posWidths, g=this.negWidths);for(;l<d;l++){var h=this.points[l];h[c[0]+"Graphic"]=h.graphic;h.graphic=h[c[1]+"Graphic"];if(a){var m=h.shapeArgs.width;var p=this.priceZones[l];(k=p.wholeVolumeData)?(f.push(m/k*p.positiveVolumeData),g.push(m/k*p.negativeVolumeData)):(f.push(0),g.push(0))}h.color=b?e.styles.positiveColor:e.styles.negativeColor;h.shapeArgs.width=b?this.posWidths[l]:this.negWidths[l];h.shapeArgs.x=b?h.shapeArgs.x:this.posWidths[l]}},translate:function(){var c=this,e=c.options,d=c.chart,f=c.yAxis, g=f.min,l=c.options.zoneLines,k=c.priceZones,h=0,q,u,x;m.translate.apply(c);var t=c.points;if(t.length){var H=.5>e.pointPadding?e.pointPadding:.1;e=c.volumeDataArray;var D=a(e);var I=d.plotWidth/2;var N=d.plotTop;var J=n(f.toPixels(g)-f.toPixels(g+c.rangeStep));var M=n(f.toPixels(g)-f.toPixels(g+c.rangeStep));H&&(g=n(J*(1-2*H)),h=n((J-g)/2),J=n(g));t.forEach(function(a,e){u=a.barX=a.plotX=0;x=a.plotY=f.toPixels(k[e].start)-N-(f.reversed?J-M:J)-h;q=b(I*k[e].wholeVolumeData/D);a.pointWidth=q;a.shapeArgs= c.crispCol.apply(c,[u,x,q,J]);a.volumeNeg=k[e].negativeVolumeData;a.volumePos=k[e].positiveVolumeData;a.volumeAll=k[e].wholeVolumeData});l.enabled&&c.drawZones(d,f,c.zoneStarts,l.styles)}},getValues:function(a,b){var c=a.processedXData,e=a.processedYData,d=this.chart,g=b.ranges,l=[],k=[],h=[],m;if(a.chart)if(m=d.get(b.volumeSeriesID))if((b=x(e[0]))&&4!==e[0].length)f("Type of "+a.name+" series is different than line, OHLC or candlestick.",!0,d);else return(this.priceZones=this.specifyZones(b,c,e, g,m)).forEach(function(a,b){l.push([a.x,a.end]);k.push(l[b][0]);h.push(l[b][1])}),{values:l,xData:k,yData:h};else f("Series "+b.volumeSeriesID+" not found! Check `volumeSeriesID`.",!0,d);else f("Base series not found! In case it has been removed, add a new one.",!0,d)},specifyZones:function(e,d,f,g,l){if(e){var k=f.length;for(var h=f[0][3],m=h,n=1,p;n<k;n++)p=f[n][3],p<h&&(h=p),p>m&&(m=p);k={min:h,max:m}}else k=!1;k=(h=k)?h.min:c(f);p=h?h.max:a(f);h=this.zoneStarts=[];m=[];var q=0;n=1;if(!k||!p)return this.points.length&& (this.setData([]),this.zoneStarts=[],this.zoneLinesSVG.destroy()),[];var u=this.rangeStep=b(p-k)/g;for(h.push(k);q<g-1;q++)h.push(b(h[q]+u));h.push(p);for(g=h.length;n<g;n++)m.push({index:n-1,x:d[0],start:h[n-1],end:h[n]});return this.volumePerZone(e,m,l,d,f)},volumePerZone:function(a,b,c,e,d){var f=this,g=c.processedXData,l=c.processedYData,h=b.length-1,k=d.length;c=l.length;var m,p,q,u,r;n(k-c)&&(e[0]!==g[0]&&l.unshift(0),e[k-1]!==g[c-1]&&l.push(0));f.volumeDataArray=[];b.forEach(function(b){b.wholeVolumeData= 0;b.positiveVolumeData=0;for(r=b.negativeVolumeData=0;r<k;r++)q=p=!1,u=a?d[r][3]:d[r],m=r?a?d[r-1][3]:d[r-1]:u,u<=b.start&&0===b.index&&(p=!0),u>=b.end&&b.index===h&&(q=!0),(u>b.start||p)&&(u<b.end||q)&&(b.wholeVolumeData+=l[r],m>u?b.negativeVolumeData+=l[r]:b.positiveVolumeData+=l[r]);f.volumeDataArray.push(b.wholeVolumeData)});return b},drawZones:function(a,b,c,e){var d=a.renderer,f=this.zoneLinesSVG,g=[],l=a.plotWidth,h=a.plotTop,k;c.forEach(function(c){k=b.toPixels(c)-h;g=g.concat(a.renderer.crispLine([["M", 0,k],["L",l,k]],e.lineWidth))});f?f.animate({d:g}):f=this.zoneLinesSVG=d.path(g).attr({"stroke-width":e.lineWidth,stroke:e.color,dashstyle:e.dashStyle,zIndex:this.group.zIndex+.1}).add(this.group)}},{destroy:function(){this.negativeGraphic&&(this.negativeGraphic=this.negativeGraphic.destroy());return k.prototype.destroy.apply(this,arguments)}});""});t(h,"Stock/Indicators/VWAPIndicator.js",[h["Core/Utilities.js"]],function(d){var h=d.error,l=d.isArray;d=d.seriesType;d("vwap","sma",{params:{period:30, volumeSeriesID:"volume"}},{getValues:function(d,e){var a=d.chart,c=d.xData;d=d.yData;var b=e.period,f=!0,g;if(g=a.get(e.volumeSeriesID))return l(d[0])||(f=!1),this.calculateVWAPValues(f,c,d,g,b);h("Series "+e.volumeSeriesID+" not found! Check `volumeSeriesID`.",!0,a)},calculateVWAPValues:function(d,e,a,c,b){var f=c.yData,g=c.xData.length,l=e.length;c=[];var h=[],k=[],m=[],p=[],t;g=l<=g?l:g;for(t=l=0;l<g;l++){var w=d?(a[l][1]+a[l][2]+a[l][3])/3:a[l];w*=f[l];w=t?c[l-1]+w:w;var r=t?h[l-1]+f[l]:f[l]; c.push(w);h.push(r);p.push([e[l],w/r]);k.push(p[l][0]);m.push(p[l][1]);t++;t===b&&(t=0)}return{values:p,xData:k,yData:m}}});""});t(h,"Stock/Indicators/WilliamsRIndicator.js",[h["Core/Utilities.js"],h["Mixins/ReduceArray.js"]],function(d,h){var l=d.isArray;d=d.seriesType;var g=h.getArrayExtremes;d("williamsr","sma",{params:{period:14}},{nameBase:"Williams %R",getValues:function(e,a){a=a.period;var c=e.xData,b=(e=e.yData)?e.length:0,d=[],h=[],k=[],n;if(!(c.length<a)&&l(e[0])&&4===e[0].length){for(n= a-1;n<b;n++){var q=e.slice(n-a+1,n+1);var m=g(q,2,1);q=m[0];m=m[1];var p=e[n][3];q=(m-p)/(m-q)*-100;c[n]&&(d.push([c[n],q]),h.push(c[n]),k.push(q))}return{values:d,xData:h,yData:k}}}});""});t(h,"Stock/Indicators/WMAIndicator.js",[h["Core/Utilities.js"]],function(d){function h(e,a){a*=(a+1)/2;return e.reduce(function(a,b,e){return[null,a[1]+b[1]*(e+1)]})[1]/a}function l(e,a,c,b){c=h(e,e.length);a=a[b-1];e.shift();return[a,c]}var g=d.isArray;d=d.seriesType;d("wma","sma",{params:{index:3,period:9}}, {getValues:function(e,a){var c=a.period,b=e.xData,d=(e=e.yData)?e.length:0,h=1,k=b[0],n=e[0],q=[],m=[],p=[],t=-1;if(!(b.length<c)){g(e[0])&&(t=a.index,n=e[0][t]);for(a=[[k,n]];h!==c;)a.push([b[h],0>t?e[h]:e[h][t]]),h++;for(c=h;c<d;c++)h=l(a,b,e,c),q.push(h),m.push(h[0]),p.push(h[1]),a.push([b[c],0>t?e[c]:e[c][t]]);h=l(a,b,e,c);q.push(h);m.push(h[0]);p.push(h[1]);return{values:q,xData:m,yData:p}}}});""});t(h,"Stock/Indicators/ZigzagIndicator.js",[h["Core/Utilities.js"]],function(d){d=d.seriesType; d("zigzag","sma",{params:{lowIndex:2,highIndex:1,deviation:1}},{nameComponents:["deviation"],nameSuffixes:["%"],nameBase:"Zig Zag",getValues:function(d,h){var g=h.lowIndex,e=h.highIndex,a=h.deviation/100;h=1+a;var c=1-a;a=d.xData;var b=d.yData;d=b?b.length:0;var f=[],l=[],k=[],n,q,m=!1,p=!1;if(!(!a||1>=a.length||d&&(void 0===b[0][g]||void 0===b[0][e]))){var t=b[0][g];var w=b[0][e];for(n=1;n<d;n++){if(b[n][g]<=w*c){f.push([a[0],w]);var r=[a[n],b[n][g]];m=q=!0}else b[n][e]>=t*h&&(f.push([a[0],t]),r= [a[n],b[n][e]],q=!1,m=!0);if(m){l.push(f[0][0]);k.push(f[0][1]);var A=n++;n=d}}for(n=A;n<d;n++)q?(b[n][g]<=r[1]&&(r=[a[n],b[n][g]]),b[n][e]>=r[1]*h&&(p=e)):(b[n][e]>=r[1]&&(r=[a[n],b[n][e]]),b[n][g]<=r[1]*c&&(p=g)),!1!==p&&(f.push(r),l.push(r[0]),k.push(r[1]),r=[a[n],b[n][p]],q=!q,p=!1);g=f.length;0!==g&&f[g-1][0]<a[d-1]&&(f.push(r),l.push(r[0]),k.push(r[1]));return{values:f,xData:l,yData:k}}}});""});t(h,"Stock/Indicators/RegressionIndicators.js",[h["Core/Utilities.js"]],function(d){var h=d.isArray; d=d.seriesType;d("linearRegression","sma",{params:{xAxisUnit:void 0},tooltip:{valueDecimals:4}},{nameBase:"Linear Regression Indicator",getRegressionLineParameters:function(d,g){var e=this.options.params.index,a=function(a,b){return h(a)?a[b]:a},c=d.reduce(function(a,b){return b+a},0),b=g.reduce(function(b,c){return a(c,e)+b},0);c/=d.length;b/=g.length;var f=0,l=0,k;for(k=0;k<d.length;k++){var n=d[k]-c;var q=a(g[k],e)-b;f+=n*q;l+=Math.pow(n,2)}d=l?f/l:0;return{slope:d,intercept:b-d*c}},getEndPointY:function(d, g){return d.slope*g+d.intercept},transformXData:function(d,g){var e=d[0];return d.map(function(a){return(a-e)/g})},findClosestDistance:function(d){var g,e;for(e=1;e<d.length-1;e++){var a=d[e]-d[e-1];0<a&&("undefined"===typeof g||a<g)&&(g=a)}return g},getValues:function(d,g){var e=d.xData;d=d.yData;g=g.period;var a,c={xData:[],yData:[],values:[]},b=this.options.params.xAxisUnit||this.findClosestDistance(e);for(a=g-1;a<=e.length-1;a++){var f=a-g+1;var h=a+1;var l=e[a];var k=e.slice(f,h);f=d.slice(f, h);h=this.transformXData(k,b);k=this.getRegressionLineParameters(h,f);f=this.getEndPointY(k,h[h.length-1]);c.values.push({regressionLineParameters:k,x:l,y:f});c.xData.push(l);c.yData.push(f)}return c}});d("linearRegressionSlope","linearRegression",{},{nameBase:"Linear Regression Slope Indicator",getEndPointY:function(d){return d.slope}});d("linearRegressionIntercept","linearRegression",{},{nameBase:"Linear Regression Intercept Indicator",getEndPointY:function(d){return d.intercept}});d("linearRegressionAngle", "linearRegression",{tooltip:{pointFormat:'<span style="color:{point.color}">\u25cf</span>{series.name}: <b>{point.y}\u00b0</b><br/>'}},{nameBase:"Linear Regression Angle Indicator",slopeToAngle:function(d){return 180/Math.PI*Math.atan(d)},getEndPointY:function(d){return this.slopeToAngle(d.slope)}});""});t(h,"Stock/Indicators/ABIndicator.js",[h["Core/Globals.js"],h["Core/Utilities.js"],h["Mixins/MultipleLines.js"]],function(d,h,l){var g=h.correctFloat,e=h.merge;h=h.seriesType;var a=d.seriesTypes.sma; h("abands","sma",{params:{period:20,factor:.001,index:3},lineWidth:1,topLine:{styles:{lineWidth:1}},bottomLine:{styles:{lineWidth:1}},dataGrouping:{approximation:"averages"}},e(l,{pointArrayMap:["top","middle","bottom"],pointValKey:"middle",nameBase:"Acceleration Bands",nameComponents:["period","factor"],linesApiNames:["topLine","bottomLine"],getValues:function(c,b){var d=b.period,e=b.factor;b=b.index;var h=c.xData,k=(c=c.yData)?c.length:0,l=[],m=[],p=[],t=[],w=[],r;if(!(k<d)){for(r=0;r<=k;r++){if(r< k){var A=c[r][2];var B=c[r][1];var z=e;A=g(B-A)/(g(B+A)/2)*1E3*z;l.push(c[r][1]*g(1+2*A));m.push(c[r][2]*g(1-2*A))}if(r>=d){A=h.slice(r-d,r);var v=c.slice(r-d,r);z=a.prototype.getValues.call(this,{xData:A,yData:l.slice(r-d,r)},{period:d});B=a.prototype.getValues.call(this,{xData:A,yData:m.slice(r-d,r)},{period:d});v=a.prototype.getValues.call(this,{xData:A,yData:v},{period:d,index:b});A=v.xData[0];z=z.yData[0];B=B.yData[0];v=v.yData[0];p.push([A,z,v,B]);t.push(A);w.push([z,v,B])}}return{values:p, xData:t,yData:w}}}}));""});t(h,"Stock/Indicators/TrendLineIndicator.js",[h["Core/Utilities.js"]],function(d){var h=d.isArray;d=d.seriesType;d("trendline","sma",{params:{index:3}},{nameBase:"Trendline",nameComponents:!1,getValues:function(d,g){var e=d.xData,a=d.yData;d=[];var c=[],b=[],f=0,k=0,l=0,n=0,q=e.length,m=g.index;for(g=0;g<q;g++){var p=e[g];var t=h(a[g])?a[g][m]:a[g];f+=p;k+=t;l+=p*t;n+=p*p}a=(q*l-f*k)/(q*n-f*f);isNaN(a)&&(a=0);f=(k-a*f)/q;for(g=0;g<q;g++)p=e[g],t=a*p+f,d[g]=[p,t],c[g]=p, b[g]=t;return{xData:c,yData:b,values:d}}});""});t(h,"masters/indicators/indicators-all.src.js",[],function(){})}); //# sourceMappingURL=indicators-all.js.map
import cheerio from 'cheerio' import fetch from 'node-fetch' function scrapeProperties(html) { const $ = cheerio.load(html) const columnMap = { 'Style Element': 'subject', 'Outlook 2007/10/13 +': 'outlook', 'Outlook 03/Express/Mail': 'outlook-legacy', 'iPhone iOS 7/iPad': 'apple-ios', 'Outlook.com': 'outlook-web', 'Apple Mail 6.5': 'apple-mail', 'Yahoo! Mail': 'yahoo-mail', 'Google Gmail': 'gmail', 'Android 4 (Gmail) +': 'gmail-android', } const columnTitles = $('#clients td').map((idx, el) => $(el).text()).get() const columns = columnTitles.map((title) => { const col = columnMap[title] if (!col) { throw new Error('Unexpected table column encountered. Scraper out of date?') } return col }) const props = {} const propRe = /^[a-z-]+/ $('#csstable tbody tr:not(.short)').each((idx, el) => { let subject const data = {} $(el).find('td').each((tdIdx, tdEl) => { const columnName = columns[tdIdx] if (columnName === 'subject') { subject = $(tdEl).text() } else { const $successEl = $(tdEl).find('.success') if ($successEl.is('.info')) { data[columnName] = $successEl.attr('data-original-title') } else { data[columnName] = $successEl.is('.true') } } }) if (!subject) { throw new Error('Could not determine table row subject. Scraper out of date?') } const match = subject.match(propRe) const propName = match && match[0] if (!propName) { return } if (Object.prototype.hasOwnProperty.call(props, propName)) { if (propName === 'background') { // skip "CSS3" background property return } throw new Error('Unexpected duplicate property row.') } if (propName === 'border' || propName === 'padding' || propName === 'margin') { ['-left', '-right', '-top', '-bottom'].forEach((suffix) => { props[propName + suffix] = data }) } props[propName] = data }) // we take care of this in the default Email component props['font-size']['apple-ios'] = true return props } fetch('https://www.campaignmonitor.com/css/') .then(res => res.text()) .then((body) => { const props = scrapeProperties(body) const propsJSON = JSON.stringify(props) process.stdout.write(propsJSON) }) .catch((err) => { console.error(err) // eslint-disable-line no-console process.exit(1) })
var browserify = require('browserify'); var browserSync = require('browser-sync'); var source = require('vinyl-source-stream'); var paths = require('../config/paths.js'); var glob = require('glob'); var mochaPhantomJS = require('gulp-mocha-phantomjs'); var taskSignature = '<[ Browserify-Test-Task ]>'; /** * This module will take all the tests files and bundle * them using browserify so that can be loaded in one go. */ module.exports = function ( gulp ){ console.log( taskSignature ); // fetch the list of all tests files var testFiles = glob.sync(paths.TESTS_SRC); return browserify( { entries: testFiles }) .bundle() .on("error", function (err) { console.log(err.toString()); this.emit("end"); }) .pipe( source( paths.PHANTOM_RUNNER_TESTS_BUNDLED_FILE_NAME )) .pipe( gulp.dest( paths.PHANTOM_RUNNER_TESTING_LOCATION )) .pipe( browserSync.reload({stream:true })); };
/* */ "format global"; (function (tree) { tree.importVisitor = function(importer, finish, evalEnv) { this._visitor = new tree.visitor(this); this._importer = importer; this._finish = finish; this.env = evalEnv || new tree.evalEnv(); this.importCount = 0; }; tree.importVisitor.prototype = { isReplacing: true, run: function (root) { var error; try { // process the contents this._visitor.visit(root); } catch(e) { error = e; } this.isFinished = true; if (this.importCount === 0) { this._finish(error); } }, visitImport: function (importNode, visitArgs) { var importVisitor = this, evaldImportNode, inlineCSS = importNode.options.inline; if (!importNode.css || inlineCSS) { try { evaldImportNode = importNode.evalForImport(this.env); } catch(e){ if (!e.filename) { e.index = importNode.index; e.filename = importNode.currentFileInfo.filename; } // attempt to eval properly and treat as css importNode.css = true; // if that fails, this error will be thrown importNode.error = e; } if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) { importNode = evaldImportNode; this.importCount++; var env = new tree.evalEnv(this.env, this.env.frames.slice(0)); if (importNode.options.multiple) { env.importMultiple = true; } this._importer.push(importNode.getPath(), importNode.currentFileInfo, importNode.options, function (e, root, imported, fullPath) { if (e && !e.filename) { e.index = importNode.index; e.filename = importNode.currentFileInfo.filename; } if (imported && !env.importMultiple) { importNode.skip = imported; } var subFinish = function(e) { importVisitor.importCount--; if (importVisitor.importCount === 0 && importVisitor.isFinished) { importVisitor._finish(e); } }; if (root) { importNode.root = root; importNode.importedFilename = fullPath; if (!inlineCSS && !importNode.skip) { new(tree.importVisitor)(importVisitor._importer, subFinish, env) .run(root); return; } } subFinish(); }); } } visitArgs.visitDeeper = false; return importNode; }, visitRule: function (ruleNode, visitArgs) { visitArgs.visitDeeper = false; return ruleNode; }, visitDirective: function (directiveNode, visitArgs) { this.env.frames.unshift(directiveNode); return directiveNode; }, visitDirectiveOut: function (directiveNode) { this.env.frames.shift(); }, visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { this.env.frames.unshift(mixinDefinitionNode); return mixinDefinitionNode; }, visitMixinDefinitionOut: function (mixinDefinitionNode) { this.env.frames.shift(); }, visitRuleset: function (rulesetNode, visitArgs) { this.env.frames.unshift(rulesetNode); return rulesetNode; }, visitRulesetOut: function (rulesetNode) { this.env.frames.shift(); }, visitMedia: function (mediaNode, visitArgs) { this.env.frames.unshift(mediaNode.ruleset); return mediaNode; }, visitMediaOut: function (mediaNode) { this.env.frames.shift(); } }; })(require('./tree'));
import ownerDocument from '../ownerDocument'; import css from '../style'; function nodeName(node) { return node.nodeName && node.nodeName.toLowerCase(); } export default function offsetParent(node) { var doc = ownerDocument(node) , offsetParent = node && node.offsetParent; while (offsetParent && nodeName(node) !== 'html' && css(offsetParent, "position") === "static" ) { offsetParent = offsetParent.offsetParent; } return offsetParent || doc.documentElement; }
/////////////////////////////////////////////////////////////////////////// // Copyright © Esri. 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. /////////////////////////////////////////////////////////////////////////// define([ 'dojo/_base/declare', './_BasicServiceBrowser', 'dojo/_base/lang', 'dojo/_base/array', 'jimu/serviceBrowserRuleUtils' ], function(declare, _BasicServiceBrowser, lang, array, serviceBrowserRuleUtils) { return declare([_BasicServiceBrowser], { declaredClass: 'jimu.dijit.QueryableServiceBrowser', baseClass: 'jimu-queryable-service-browser', //This dijit will filter MapService,FeatureService and ImageService //options: url: '', multiple: false, //public methods: //setUrl //getSelectedItems return [{name,url,definition}] //test url: //base url: http://sampleserver6.arcgisonline.com/ArcGIS/rest/services //folder url1: http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics //folder url2: http://sampleserver6.arcgisonline.com/arcgis/rest/services/OsoLandslide //service url1: http://tryitlive.arcgis.com/arcgis/rest/services/GeneralPurpose/MapServer //service url2: http://sampleserver6.arcgisonline.com/arcgis/rest/services/Toronto/ImageServer //group layer url1: http://tryitlive.arcgis.com/arcgis/rest/services/GeneralPurpose/MapServer/0 //group layer url2: http://tryitlive.arcgis.com/arcgis/rest/services/GeneralPurpose/MapServer/1 //layer url: http://tryitlive.arcgis.com/arcgis/rest/services/GeneralPurpose/MapServer/2 postMixInProperties:function(){ this.inherited(arguments); this.rule = serviceBrowserRuleUtils.getQueryableServiceBrowserRule(); }, getSelectedItems: function(){ var items = this.inherited(arguments); items = array.map(items, lang.hitch(this, function(item){ return { name: item.name, url: item.url, definition: item.definition }; })); return items; } }); });
describe('uiGridFooterCell', function () { var grid, data, columnDefs, $scope, $compile, $document, recompile, uiGridConstants, $httpBackend; data = [ { name: 'Bob', age: 35 }, { name: 'Bill', age: 25 }, { name: 'Sam', age: 17 }, { name: 'Jane', age: 19 } ]; columnDefs = [ { name: 'name', footerCellClass: 'testClass' }, { name: 'age', footerCellClass: function(grid, row, col) { if ( col.colDef.noClass ) { return ''; } else { return 'funcCellClass'; } } } ]; beforeEach(module('ui.grid')); beforeEach(inject(function (_$compile_, $rootScope, _$document_, _uiGridConstants_, _$httpBackend_) { $scope = $rootScope; $compile = _$compile_; $document = _$document_; uiGridConstants = _uiGridConstants_; $httpBackend = _$httpBackend_; $scope.gridOpts = { showColumnFooter: true, columnDefs: columnDefs, data: data, onRegisterApi: function( gridApi ) { $scope.gridApi = gridApi; } }; $scope.extScope = 'test'; recompile = function () { grid = angular.element('<div style="width: 500px; height: 300px" ui-grid="gridOpts"></div>'); $compile(grid)($scope); $document[0].body.appendChild(grid[0]); $scope.$digest(); }; recompile(); })); afterEach(function() { grid.remove(); }); describe('footerCellClass', function () { var footerCell1, footerCell2; beforeEach(function () { footerCell1 = $(grid).find('.ui-grid-footer-cell:nth(0)'); footerCell2 = $(grid).find('.ui-grid-footer-cell:nth(1)'); }); it('should have the footerCellClass class, from string', inject(function () { expect(footerCell1.hasClass('testClass')).toBe(true); })); it('should get cellClass from function, and remove it when data changes', inject(function () { expect(footerCell2.hasClass('funcCellClass')).toBe(true); columnDefs[1].noClass = true; $scope.gridApi.core.notifyDataChange( uiGridConstants.dataChange.COLUMN ); expect(footerCell2.hasClass('funcCellClass')).toBe(false); })); }); describe('externalScope', function() { it('should be present', function () { var header = $(grid).find('.ui-grid-header-cell:nth(0)'); expect(header).toBeDefined(); expect(header.scope().grid.appScope).toBeDefined(); expect(header.scope().grid.appScope.extScope).toBe('test'); }); }); describe('should handle a URL-based template defined in headerCellTemplate', function () { it('should handle', function () { var el, url = 'http://www.a-really-fake-url.com/footerCellTemplate.html'; $scope.gridOpts.columnDefs[0].footerCellTemplate = url; $httpBackend.expectGET(url).respond('<div class="footerCellTemplate">footerCellTemplate content</div>'); recompile(); el = $(grid).find('.footerCellTemplate'); expect(el.text()).toEqual(''); $httpBackend.flush(); el = $(grid).find('.footerCellTemplate'); expect(el.text()).toEqual('footerCellTemplate content'); }); }); });
/*! * jquery.fancytree.menu.js * * Enable jQuery UI Menu as context menu for tree nodes. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * @see http://api.jqueryui.com/menu/ * * Copyright (c) 2008-2017, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.22.1 * @date 2017-04-21T05:55:46Z */ ;(function($, window, document, undefined) { "use strict"; // prevent duplicate loading // if ( $.ui.fancytree && $.ui.fancytree.version ) { // $.ui.fancytree.warn("Fancytree: duplicate include"); // return; // } $.ui.fancytree.registerExtension({ name: "menu", version: "0.0.1", // Default options for this extension. options: { enable: true, selector: null, // position: {}, // // Events: create: $.noop, // beforeOpen: $.noop, // open: $.noop, // focus: $.noop, // select: $.noop, // close: $.noop // }, // Override virtual methods for this extension. // `this` : is this extension object // `this._base` : the Fancytree instance // `this._super`: the virtual function that was overridden (member of prev. extension or Fancytree) treeInit: function(ctx){ var opts = ctx.options, tree = ctx.tree; this._superApply(arguments); // Prepare an object that will be passed with menu events tree.ext.menu.data = { tree: tree, node: null, $menu: null, menuId: null }; // tree.$container[0].oncontextmenu = function() {return false;}; // Replace the standard browser context menu with out own tree.$container.delegate("span.fancytree-node", "contextmenu", function(event) { var node = $.ui.fancytree.getNode(event), ctx = {node: node, tree: node.tree, originalEvent: event, options: tree.options}; tree.ext.menu._openMenu(ctx); return false; }); // Use jquery.ui.menu $(opts.menu.selector).menu({ create: function(event, ui){ tree.ext.menu.data.$menu = $(this).menu("widget"); var data = $.extend({}, tree.ext.menu.data); opts.menu.create.call(tree, event, data); }, focus: function(event, ui){ var data = $.extend({}, tree.ext.menu.data, { menuItem: ui.item, menuId: ui.item.find(">a").attr("href") }); opts.menu.focus.call(tree, event, data); }, select: function(event, ui){ var data = $.extend({}, tree.ext.menu.data, { menuItem: ui.item, menuId: ui.item.find(">a").attr("href") }); if( opts.menu.select.call(tree, event, data) !== false){ tree.ext.menu._closeMenu(ctx); } } }).hide(); }, treeDestroy: function(ctx){ this._superApply(arguments); }, _openMenu: function(ctx){ var data, tree = ctx.tree, opts = ctx.options, $menu = $(opts.menu.selector); tree.ext.menu.data.node = ctx.node; data = $.extend({}, tree.ext.menu.data); if( opts.menu.beforeOpen.call(tree, ctx.originalEvent, data) === false){ return; } $(document).bind("keydown.fancytree", function(event){ if( event.which === $.ui.keyCode.ESCAPE ){ tree.ext.menu._closeMenu(ctx); } }).bind("mousedown.fancytree", function(event){ // Close menu when clicked outside menu if( $(event.target).closest(".ui-menu-item").length === 0 ){ tree.ext.menu._closeMenu(ctx); } }); // $menu.position($.extend({my: "left top", at: "left bottom", of: event}, opts.menu.position)); $menu .css("position", "absolute") .show() .position({my: "left top", at: "right top", of: ctx.originalEvent, collision: "fit"}) .focus(); opts.menu.open.call(tree, ctx.originalEvent, data); }, _closeMenu: function(ctx){ var $menu, tree = ctx.tree, opts = ctx.options, data = $.extend({}, tree.ext.menu.data); if( opts.menu.close.call(tree, ctx.originalEvent, data) === false){ return; } $menu = $(opts.menu.selector); $(document).off("keydown.fancytree, mousedown.fancytree"); $menu.hide(); tree.ext.menu.data.node = null; } // , // nodeClick: function(ctx) { // var event = ctx.originalEvent; // if(event.which === 2 || (event.which === 1 && event.ctrlKey)){ // event.preventDefault(); // ctx.tree.ext.menu._openMenu(ctx); // return false; // } // this._superApply(arguments); // } }); }(jQuery, window, document));
/* global __PATH_PREFIX__ CMS_PUBLIC_PATH */ import netlifyIdentityWidget from "netlify-identity-widget" window.netlifyIdentity = netlifyIdentityWidget const addLoginListener = () => netlifyIdentityWidget.on(`login`, () => { document.location.href = `${__PATH_PREFIX__}/${CMS_PUBLIC_PATH}/` }) netlifyIdentityWidget.on(`init`, user => { if (!user) { addLoginListener() } else { netlifyIdentityWidget.on(`logout`, () => { addLoginListener() }) } }) netlifyIdentityWidget.init()
/**************************************************************************** Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ // ------------------------------- ClippingNode's WebGL render cmd ------------------------------ (function(){ cc.ClippingNode.WebGLRenderCmd = function(renderable){ cc.Node.WebGLRenderCmd.call(this, renderable); this._needDraw = false; this._beforeVisitCmd = new cc.CustomRenderCmd(this, this._onBeforeVisit); this._afterDrawStencilCmd = new cc.CustomRenderCmd(this, this._onAfterDrawStencil); this._afterVisitCmd = new cc.CustomRenderCmd(this, this._onAfterVisit); this._currentStencilEnabled = null; this._mask_layer_le = null; }; var proto = cc.ClippingNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); proto.constructor = cc.ClippingNode.WebGLRenderCmd; cc.ClippingNode.WebGLRenderCmd._init_once = null; cc.ClippingNode.WebGLRenderCmd._visit_once = null; cc.ClippingNode.WebGLRenderCmd._layer = -1; proto.initStencilBits = function(){ // get (only once) the number of bits of the stencil buffer cc.ClippingNode.WebGLRenderCmd._init_once = true; if (cc.ClippingNode.WebGLRenderCmd._init_once) { cc.stencilBits = cc._renderContext.getParameter(cc._renderContext.STENCIL_BITS); if (cc.stencilBits <= 0) cc.log("Stencil buffer is not enabled."); cc.ClippingNode.WebGLRenderCmd._init_once = false; } }; proto.transform = function(parentCmd, recursive){ var node = this._node; this.originTransform(parentCmd, recursive); if(node._stencil) { node._stencil._renderCmd.transform(this, recursive); } }; proto.visit = function(parentCmd){ var node = this._node; // quick return if not visible if (!node._visible) return; if( node._parent && node._parent._renderCmd) this._curLevel = node._parent._renderCmd._curLevel + 1; // if stencil buffer disabled if (cc.stencilBits < 1) { // draw everything, as if there were no stencil this.originVisit(parentCmd); return; } if (!node._stencil || !node._stencil.visible) { if (node.inverted) this.originVisit(parentCmd); // draw everything return; } if (cc.ClippingNode.WebGLRenderCmd._layer + 1 === cc.stencilBits) { cc.ClippingNode.WebGLRenderCmd._visit_once = true; if (cc.ClippingNode.WebGLRenderCmd._visit_once) { cc.log("Nesting more than " + cc.stencilBits + "stencils is not supported. Everything will be drawn without stencil for this node and its children."); cc.ClippingNode.WebGLRenderCmd._visit_once = false; } // draw everything, as if there were no stencil this.originVisit(parentCmd); return; } cc.renderer.pushRenderCommand(this._beforeVisitCmd); //optimize performance for javascript var currentStack = cc.current_stack; currentStack.stack.push(currentStack.top); this._syncStatus(parentCmd); currentStack.top = this._stackMatrix; // node._stencil._stackMatrix = node._stackMatrix; node._stencil._renderCmd.visit(this); cc.renderer.pushRenderCommand(this._afterDrawStencilCmd); // draw (according to the stencil test func) this node and its children var locChildren = node._children; if (locChildren && locChildren.length > 0) { var childLen = locChildren.length; node.sortAllChildren(); // draw children zOrder < 0 for (var i = 0; i < childLen; i++) { locChildren[i]._renderCmd.visit(this); } } cc.renderer.pushRenderCommand(this._afterVisitCmd); this._dirtyFlag = 0; //optimize performance for javascript currentStack.top = currentStack.stack.pop(); }; proto.setStencil = function(stencil){ var node = this._node; if(node._stencil) node._stencil._parent = null; node._stencil = stencil; if(node._stencil) node._stencil._parent = node; }; proto._onBeforeVisit = function(ctx){ var gl = ctx || cc._renderContext, node = this._node; cc.ClippingNode.WebGLRenderCmd._layer++; // mask of the current layer (ie: for layer 3: 00000100) var mask_layer = 0x1 << cc.ClippingNode.WebGLRenderCmd._layer; // mask of all layers less than the current (ie: for layer 3: 00000011) var mask_layer_l = mask_layer - 1; // mask of all layers less than or equal to the current (ie: for layer 3: 00000111) //var mask_layer_le = mask_layer | mask_layer_l; this._mask_layer_le = mask_layer | mask_layer_l; // manually save the stencil state this._currentStencilEnabled = gl.isEnabled(gl.STENCIL_TEST); gl.clear(gl.DEPTH_BUFFER_BIT); // enable stencil use gl.enable(gl.STENCIL_TEST); gl.depthMask(false); gl.stencilFunc(gl.NEVER, mask_layer, mask_layer); gl.stencilOp(gl.REPLACE, gl.KEEP, gl.KEEP); gl.stencilMask(mask_layer); gl.clear(gl.STENCIL_BUFFER_BIT); if (node.alphaThreshold < 1) { //TODO desktop var program = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLORALPHATEST); // set our alphaThreshold cc.glUseProgram(program.getProgram()); program.setUniformLocationWith1f(cc.UNIFORM_ALPHA_TEST_VALUE_S, node.alphaThreshold); program.setUniformLocationWithMatrix4fv(cc.UNIFORM_MVMATRIX_S, cc.renderer.mat4Identity.mat); cc.setProgram(node._stencil, program); } }; proto._onAfterDrawStencil = function(ctx){ var gl = ctx || cc._renderContext; gl.depthMask(true); gl.stencilFunc(!this._node.inverted ? gl.EQUAL : gl.NOTEQUAL, this._mask_layer_le, this._mask_layer_le); gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); }; proto._onAfterVisit = function(ctx){ var gl = ctx || cc._renderContext; cc.ClippingNode.WebGLRenderCmd._layer--; if (this._currentStencilEnabled) { var mask_layer = 0x1 << cc.ClippingNode.WebGLRenderCmd._layer; var mask_layer_l = mask_layer - 1; var mask_layer_le = mask_layer | mask_layer_l; gl.stencilMask(mask_layer); gl.stencilFunc(gl.EQUAL, mask_layer_le, mask_layer_le); } else { gl.disable(gl.STENCIL_TEST); } }; })();
/* */ "format cjs"; if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function(require, exports, module) { var SourceMapConsumer = require('../../lib/source-map/source-map-consumer').SourceMapConsumer; var SourceMapGenerator = require('../../lib/source-map/source-map-generator').SourceMapGenerator; exports['test eating our own dog food'] = function(assert, util) { var smg = new SourceMapGenerator({ file: 'testing.js', sourceRoot: '/wu/tang' }); smg.addMapping({ source: 'gza.coffee', original: { line: 1, column: 0 }, generated: { line: 2, column: 2 } }); smg.addMapping({ source: 'gza.coffee', original: { line: 2, column: 0 }, generated: { line: 3, column: 2 } }); smg.addMapping({ source: 'gza.coffee', original: { line: 3, column: 0 }, generated: { line: 4, column: 2 } }); smg.addMapping({ source: 'gza.coffee', original: { line: 4, column: 0 }, generated: { line: 5, column: 2 } }); var smc = new SourceMapConsumer(smg.toString()); util.assertMapping(2, 2, '/wu/tang/gza.coffee', 1, 0, null, smc, assert); util.assertMapping(3, 2, '/wu/tang/gza.coffee', 2, 0, null, smc, assert); util.assertMapping(4, 2, '/wu/tang/gza.coffee', 3, 0, null, smc, assert); util.assertMapping(5, 2, '/wu/tang/gza.coffee', 4, 0, null, smc, assert); util.assertMapping(2, 0, null, null, null, null, smc, assert, true); util.assertMapping(2, 9, '/wu/tang/gza.coffee', 1, 0, null, smc, assert, true); util.assertMapping(3, 0, '/wu/tang/gza.coffee', 1, 0, null, smc, assert, true); util.assertMapping(3, 9, '/wu/tang/gza.coffee', 2, 0, null, smc, assert, true); util.assertMapping(4, 0, '/wu/tang/gza.coffee', 2, 0, null, smc, assert, true); util.assertMapping(4, 9, '/wu/tang/gza.coffee', 3, 0, null, smc, assert, true); util.assertMapping(5, 0, '/wu/tang/gza.coffee', 3, 0, null, smc, assert, true); util.assertMapping(5, 9, '/wu/tang/gza.coffee', 4, 0, null, smc, assert, true); util.assertMapping(2, 2, '/wu/tang/gza.coffee', 1, 1, null, smc, assert, null, true); util.assertMapping(3, 2, '/wu/tang/gza.coffee', 2, 3, null, smc, assert, null, true); util.assertMapping(4, 2, '/wu/tang/gza.coffee', 3, 6, null, smc, assert, null, true); util.assertMapping(5, 2, '/wu/tang/gza.coffee', 4, 9, null, smc, assert, null, true); }; });
function meaningOfLife() { throw new Error(42); } function boom() { throw new Error('boom'); } function somethingElse() { throw new Error("somethign else"); } //# sourceMappingURL=foo/bad-link.map
/** * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'a11yhelp', 'ro', { title: 'Instrucțiuni de accesibilitate', contents: 'Cuprins. Pentru a închide acest dialog, apăsați tasta ESC.', legend: [ { name: 'General', items: [ { name: 'Editează bara.', legend: 'Press ${toolbarFocus} to navigate to the toolbar. Move to the next and previous toolbar group with TAB and SHIFT-TAB. Move to the next and previous toolbar button with RIGHT ARROW or LEFT ARROW. Press SPACE or ENTER to activate the toolbar button.' // MISSING }, { name: 'Dialog editor', legend: 'Inside a dialog, press TAB to navigate to next dialog field, press SHIFT + TAB to move to previous field, press ENTER to submit dialog, press ESC to cancel dialog. For dialogs that have multiple tab pages, press ALT + F10 to navigate to tab-list. Then move to next tab with TAB OR RIGTH ARROW. Move to previous tab with SHIFT + TAB or LEFT ARROW. Press SPACE or ENTER to select the tab page.' // MISSING }, { name: 'Editor meniu contextual', legend: 'Press ${contextMenu} or APPLICATION KEY to open context-menu. Then move to next menu option with TAB or DOWN ARROW. Move to previous option with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the menu option. Open sub-menu of current option with SPACE or ENTER or RIGHT ARROW. Go back to parent menu item with ESC or LEFT ARROW. Close context menu with ESC.' // MISSING }, { name: 'Editor List Box', // MISSING legend: 'Inside a list-box, move to next list item with TAB OR DOWN ARROW. Move to previous list item with SHIFT + TAB or UP ARROW. Press SPACE or ENTER to select the list option. Press ESC to close the list-box.' // MISSING }, { name: 'Editor Element Path Bar', // MISSING legend: 'Press ${elementsPathFocus} to navigate to the elements path bar. Move to next element button with TAB or RIGHT ARROW. Move to previous button with SHIFT+TAB or LEFT ARROW. Press SPACE or ENTER to select the element in editor.' // MISSING } ] }, { name: 'Commands', // MISSING items: [ { name: ' Undo command', // MISSING legend: 'Press ${undo}' // MISSING }, { name: ' Redo command', // MISSING legend: 'Press ${redo}' // MISSING }, { name: ' Bold command', // MISSING legend: 'Press ${bold}' // MISSING }, { name: ' Italic command', // MISSING legend: 'Press ${italic}' // MISSING }, { name: ' Underline command', // MISSING legend: 'Press ${underline}' // MISSING }, { name: ' Link command', // MISSING legend: 'Press ${link}' // MISSING }, { name: ' Toolbar Collapse command', // MISSING legend: 'Press ${toolbarCollapse}' // MISSING }, { name: ' Access previous focus space command', // MISSING legend: 'Press ${accessPreviousSpace} to access the closest unreachable focus space before the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces.' // MISSING }, { name: ' Access next focus space command', // MISSING legend: 'Press ${accessNextSpace} to access the closest unreachable focus space after the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces.' // MISSING }, { name: ' Accessibility Help', // MISSING legend: 'Press ${a11yHelp}' // MISSING } ] } ] });
import Ember from 'ember'; var DuplicateName = Ember.Object.extend({ hello: function() { console.log('hello'); } }); export default DuplicateName;
import React from "react"; import { Link } from "react-router-dom"; import { Block, Row, Inline } from "jsxstyle"; import { SMALL_SCREEN, LIGHT_GRAY } from "../../Theme.js"; import Logo from "../Logo.js"; import SmallScreen from "../SmallScreen.js"; function NavLink({ href, ...props }) { return <Block component="a" props={{ href }} margin="0 10px" {...props} />; } function Button({ to, small, ...props }) { return ( <Block component={Link} activeBoxShadow="2px 2px 4px rgba(0,0,0,.25)" activeTop="5px" background="white" borderRadius="100px" boxShadow={ small ? "0 5px 15px rgba(0, 0, 0, .25)" : "0 10px 30px rgba(0, 0, 0, .25)" } cursor="pointer" flex="1" fontSize="10px" fontWeight="bold" hoverBoxShadow={ small ? "0 5px 10px rgba(0, 0, 0, .25)" : "0 10px 25px rgba(0, 0, 0, .25)" } hoverTop="1px" marginRight={small ? "10px" : "20px"} padding={small ? "10px" : "15px 25px"} position="relative" props={{ to }} textAlign="center" textTransform="uppercase" top="0" userSelect="none" whiteSpace="nowrap" {...props} /> ); } function NavBar() { return ( <Row textTransform="uppercase" fontWeight="bold" width="100%"> <Block flex="1" fontSize="14px"> <Inline component="a" props={{ href: "https://reacttraining.com" }}> React Training </Inline> <Inline> / </Inline> <Inline component="a" props={{ href: "https://github.com/ReactTraining/react-router" }} color={LIGHT_GRAY} > React Router </Inline> </Block> <Row fontSize="12px"> <NavLink href="https://github.com/ReactTraining/react-router"> Github </NavLink> <NavLink href="https://www.npmjs.com/package/react-router">NPM</NavLink> <NavLink href="https://reacttraining.com" margin="0"> Get Training </NavLink> </Row> </Row> ); } function Banner() { return ( <SmallScreen> {isSmallScreen => ( <Row width="100%"> {!isSmallScreen && ( <Block flex="1"> <Logo /> </Block> )} <Block flex="1"> <Block lineHeight="1"> <Block textTransform="uppercase" fontSize={isSmallScreen ? "80%" : "120%"} fontWeight="bold" > Learn once, Route anywhere </Block> <Block component="h2" textTransform="uppercase" fontSize={isSmallScreen ? "200%" : "350%"} fontWeight="bold" > React Router </Block> </Block> <Block margin={`${isSmallScreen ? 20 : 20}px 0`} fontSize={isSmallScreen ? "80%" : null} > Components are the heart of React&apos;s powerful, declarative programming model. React Router is a collection of{" "} <b>navigational components</b> that compose declaratively with your application. Whether you want to have{" "} <b>bookmarkable URLs</b> for your web app or a composable way to navigate in <b>React Native</b>, React Router works wherever React is rendering--so take your pick! </Block> <Row> <Button to="/web" small={isSmallScreen}> Web </Button> <Button to="/native" small={isSmallScreen}> Native </Button> </Row> </Block> </Row> )} </SmallScreen> ); } export default function Header() { return ( <SmallScreen query={SMALL_SCREEN}> {isSmallScreen => ( <Block background="linear-gradient(125deg, #fff, #f3f3f3 41%, #ededed 0, #fff)"> <Block padding="20px" maxWidth="1000px" margin="auto"> {!isSmallScreen && <NavBar />} <Block height={isSmallScreen ? "20px" : "40px"} /> <Banner /> <Block height="20px" /> </Block> </Block> )} </SmallScreen> ); }
"use strict"; jest.mock("@lerna/child-process"); const childProcess = require("@lerna/child-process"); const { hasNpmVersion } = require("../lib/has-npm-version"); childProcess.execSync.mockReturnValue("5.6.0"); test("hasNpmVersion() returns boolean if range is satisfied by npm --version", () => { expect(hasNpmVersion(">=5")).toBe(true); expect(hasNpmVersion(">=6")).toBe(false); expect(childProcess.execSync).toHaveBeenLastCalledWith("npm", ["--version"]); });
/* * @name 웹캠을 사용한 셰이더 * @description 웹캠을 텍스처로서 셰이더에 보낼 수 있습니다. * <br> p5.js로 셰이더를 사용하는 방법에 대해 더 알고 싶다면: <a href="https://itp-xstory.github.io/p5js-shaders/">p5.js Shaders</a> */ // 이 변수는 셰이더 객체를 담습니다. let theShader; // 이 변수는 웹캠 비디오를 담습니다. let cam; function preload(){ // 셰이더 불러오기 theShader = loadShader('assets/webcam.vert', 'assets/webcam.frag'); } function setup() { // 셰이더 작동을 위해 WEBGL 모드가 필요합니다. createCanvas(710, 400, WEBGL); noStroke(); cam = createCapture(VIDEO); cam.size(710, 400); cam.hide(); } function draw() { // shader()는 활성화 셰이더를 theShader로 설정합니다. shader(theShader); // cam을 텍스처로 보내기 theShader.setUniform('tex0', cam); // rect()함수로 화면에 기하 추가하기 rect(0,0,width,height); }
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * Properties controlling TLS Certificate Validation. * */ class BackendTlsProperties { /** * Create a BackendTlsProperties. * @member {boolean} [validateCertificateChain] Flag indicating whether SSL * certificate chain validation should be done when using self-signed * certificates for this backend host. Default value: true . * @member {boolean} [validateCertificateName] Flag indicating whether SSL * certificate name validation should be done when using self-signed * certificates for this backend host. Default value: true . */ constructor() { } /** * Defines the metadata of BackendTlsProperties * * @returns {object} metadata of BackendTlsProperties * */ mapper() { return { required: false, serializedName: 'BackendTlsProperties', type: { name: 'Composite', className: 'BackendTlsProperties', modelProperties: { validateCertificateChain: { required: false, serializedName: 'validateCertificateChain', defaultValue: true, type: { name: 'Boolean' } }, validateCertificateName: { required: false, serializedName: 'validateCertificateName', defaultValue: true, type: { name: 'Boolean' } } } } }; } } module.exports = BackendTlsProperties;
"use strict"; const chalk = require("chalk"); const tempy = require("tempy"); const Tacks = require("tacks"); const { Project } = require("@lerna/project"); const { loggingOutput } = require("@lerna-test/logging-output"); const listable = require(".."); const { File, Dir } = Tacks; // keep snapshots stable cross-platform chalk.level = 0; // remove quotes around top-level strings expect.addSnapshotSerializer({ test(val) { return typeof val === "string"; }, serialize(val, config, indentation, depth) { // top-level strings don't need quotes, but nested ones do (object properties, etc) return depth ? `"${val}"` : val; }, }); // normalize temp directory paths in snapshots expect.addSnapshotSerializer(require("@lerna-test/serialize-windows-paths")); expect.addSnapshotSerializer(require("@lerna-test/serialize-tempdir")); describe("listable.format()", () => { let packages; const formatWithOptions = (opts) => listable.format(packages, Object.assign({ _: ["ls"] }, opts)); const fixture = new Tacks( Dir({ "lerna.json": File({ version: "independent", packages: ["pkgs/*"], }), "package.json": File({ name: "listable-format-test", }), pkgs: Dir({ "pkg-1": Dir({ "package.json": File({ name: "pkg-1", version: "1.0.0", dependencies: { "pkg-2": "file:../pkg-2" }, }), }), "pkg-2": Dir({ "package.json": File({ name: "pkg-2", // version: "2.0.0", devDependencies: { "pkg-3": "file:../pkg-3" }, }), }), "pkg-3": Dir({ "package.json": File({ name: "pkg-3", version: "3.0.0", dependencies: { "pkg-2": "file:../pkg-2" }, private: true, }), }), }), }) ); beforeAll(async () => { const cwd = tempy.directory(); fixture.create(cwd); process.chdir(cwd); packages = await Project.getPackages(cwd); }); describe("renders", () => { test("all output", () => { const { count, text } = formatWithOptions({ all: true }); expect(count).toBe(3); expect(text).toMatchInlineSnapshot(` pkg-1 pkg-2 pkg-3 (PRIVATE) `); }); test("long output", () => { const { count, text } = formatWithOptions({ long: true }); expect(count).toBe(2); expect(text).toMatchInlineSnapshot(` pkg-1 v1.0.0 pkgs/pkg-1 pkg-2 MISSING pkgs/pkg-2 `); }); test("all long output", () => { const { text } = formatWithOptions({ long: true, all: true }); expect(text).toMatchInlineSnapshot(` pkg-1 v1.0.0 pkgs/pkg-1 pkg-2 MISSING pkgs/pkg-2 pkg-3 v3.0.0 pkgs/pkg-3 (PRIVATE) `); }); test("JSON output", () => { const { text } = formatWithOptions({ json: true }); expect(text).toMatchInlineSnapshot(` [ { "name": "pkg-1", "version": "1.0.0", "private": false, "location": "__TEST_ROOTDIR__/pkgs/pkg-1" }, { "name": "pkg-2", "private": false, "location": "__TEST_ROOTDIR__/pkgs/pkg-2" } ] `); }); test("all JSON output", () => { const { text } = formatWithOptions({ json: true, all: true }); expect(text).toMatchInlineSnapshot(` [ { "name": "pkg-1", "version": "1.0.0", "private": false, "location": "__TEST_ROOTDIR__/pkgs/pkg-1" }, { "name": "pkg-2", "private": false, "location": "__TEST_ROOTDIR__/pkgs/pkg-2" }, { "name": "pkg-3", "version": "3.0.0", "private": true, "location": "__TEST_ROOTDIR__/pkgs/pkg-3" } ] `); }); test("NDJSON output", () => { const { text } = formatWithOptions({ ndjson: true, all: true }); expect(text).toMatchInlineSnapshot(` {"name":"pkg-1","version":"1.0.0","private":false,"location":"__TEST_ROOTDIR__/pkgs/pkg-1"} {"name":"pkg-2","private":false,"location":"__TEST_ROOTDIR__/pkgs/pkg-2"} {"name":"pkg-3","version":"3.0.0","private":true,"location":"__TEST_ROOTDIR__/pkgs/pkg-3"} `); }); test("graph output", () => { const { text } = formatWithOptions({ graph: true }); expect(text).toMatchInlineSnapshot(` { "pkg-1": [ "pkg-2" ], "pkg-2": [] } `); }); test("all graph output", () => { const { text } = formatWithOptions({ graph: true, all: true }); expect(text).toMatchInlineSnapshot(` { "pkg-1": [ "pkg-2" ], "pkg-2": [ "pkg-3" ], "pkg-3": [ "pkg-2" ] } `); }); test("parseable output", () => { const { text } = formatWithOptions({ parseable: true }); expect(text).toMatchInlineSnapshot(` __TEST_ROOTDIR__/pkgs/pkg-1 __TEST_ROOTDIR__/pkgs/pkg-2 `); }); test("all parseable output", () => { const { text } = formatWithOptions({ parseable: true, all: true }); expect(text).toMatchInlineSnapshot(` __TEST_ROOTDIR__/pkgs/pkg-1 __TEST_ROOTDIR__/pkgs/pkg-2 __TEST_ROOTDIR__/pkgs/pkg-3 `); }); test("long parseable output", () => { const { text } = formatWithOptions({ parseable: true, long: true }); expect(text).toMatchInlineSnapshot(` __TEST_ROOTDIR__/pkgs/pkg-1:pkg-1:1.0.0 __TEST_ROOTDIR__/pkgs/pkg-2:pkg-2:MISSING `); }); test("all long parseable output", () => { const { text } = formatWithOptions({ parseable: true, all: true, long: true }); expect(text).toMatchInlineSnapshot(` __TEST_ROOTDIR__/pkgs/pkg-1:pkg-1:1.0.0 __TEST_ROOTDIR__/pkgs/pkg-2:pkg-2:MISSING __TEST_ROOTDIR__/pkgs/pkg-3:pkg-3:3.0.0:PRIVATE `); }); }); describe("aliases", () => { test("la => ls -la", () => { const { text } = formatWithOptions({ _: ["la"] }); expect(text).toMatchInlineSnapshot(` pkg-1 v1.0.0 pkgs/pkg-1 pkg-2 MISSING pkgs/pkg-2 pkg-3 v3.0.0 pkgs/pkg-3 (PRIVATE) `); }); test("ll => ls -l", () => { const { text } = formatWithOptions({ _: ["ll"] }); expect(text).toMatchInlineSnapshot(` pkg-1 v1.0.0 pkgs/pkg-1 pkg-2 MISSING pkgs/pkg-2 `); }); }); describe("toposort", () => { test("output", () => { const { text } = formatWithOptions({ toposort: true }); expect(text).toMatchInlineSnapshot(` pkg-2 pkg-1 `); }); test("cycles", () => { const { text } = formatWithOptions({ toposort: true, all: true }); expect(loggingOutput("warn")).toContainEqual(expect.stringContaining("pkg-2 -> pkg-3 -> pkg-2")); expect(text).toMatchInlineSnapshot(` pkg-2 pkg-3 (PRIVATE) pkg-1 `); }); }); });
/*! * jQuery JavaScript Library v2.1.0 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseJSON,-ajax/parseXML,-ajax/script,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-dimensions,-effects,-effects/Tween,-effects/animatedSelector,-event-alias,-css/hiddenVisibleSelectors,-wrap * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-09-28T03:53Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ // var arr = []; var slice = arr.slice; var concat = arr.concat; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var trim = "".trim; var support = {}; var // Use the correct document accordingly with window argument (sandbox) document = window.document, version = "2.1.0 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseJSON,-ajax/parseXML,-ajax/script,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-dimensions,-effects,-effects/Tween,-effects/animatedSelector,-event-alias,-css/hiddenVisibleSelectors,-wrap", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return a 'clean' array ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return just the object slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN return obj - parseFloat( obj ) >= 0; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Support: Firefox <20 // The try/catch suppresses exceptions thrown when attempting to access // the "constructor" property of certain host objects, ie. |window.location| // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 try { if ( obj.constructor && !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } } catch ( e ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android < 4.0, iOS < 6 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, trim: function( text ) { return text == null ? "" : trim.call( text ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: Date.now, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } /* * Optional (non-Sizzle) selector module for custom builds. * * Note that this DOES NOT SUPPORT many documented jQuery * features in exchange for its smaller size: * * Attribute not equal selector * Positional selectors (:first; :eq(n); :odd; etc.) * Type selectors (:input; :checkbox; :button; etc.) * State-based selectors (:animated; :visible; :hidden; etc.) * :has(selector) * :not(complex selector) * custom selectors via Sizzle extensions * Leading combinators (e.g., $collection.find("> *")) * Reliable functionality on XML fragments * Requiring all parts of a selector to match elements under context * (e.g., $div.find("div > *") now matches children of $div) * Matching against non-elements * Reliable sorting of disconnected nodes * querySelectorAll bug fixes (e.g., unreliable :focus on WebKit) * * If any of these are unacceptable tradeoffs, either use Sizzle or * customize this stub for the project's specific needs. */ var docElem = window.document.documentElement, selector_hasDuplicate, matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector, selector_sortOrder = function( a, b ) { // Flag for duplicate removal if ( a === b ) { selector_hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 ) { // Choose the first element that is related to our document if ( a === document || jQuery.contains(document, a) ) { return -1; } if ( b === document || jQuery.contains(document, b) ) { return 1; } // Maintain original order return 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; }; jQuery.extend({ find: function( selector, context, results, seed ) { var elem, nodeType, i = 0; results = results || []; context = context || document; // Same basic safeguard as Sizzle if ( !selector || typeof selector !== "string" ) { return results; } // Early return if context is not an element or document if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( seed ) { while ( (elem = seed[i++]) ) { if ( jQuery.find.matchesSelector(elem, selector) ) { results.push( elem ); } } } else { jQuery.merge( results, context.querySelectorAll(selector) ); } return results; }, unique: function( results ) { var elem, duplicates = [], i = 0, j = 0; selector_hasDuplicate = false; results.sort( selector_sortOrder ); if ( selector_hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }, text: function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += jQuery.text( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements return elem.textContent; } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }, contains: function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && adown.contains(bup) ); }, isXMLDoc: function( elem ) { return (elem.ownerDocument || elem).documentElement.nodeName !== "HTML"; }, expr: { attrHandle: {}, match: { bool: /^(?:checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped)$/i, needsContext: /^[\x20\t\r\n\f]*[>+~]/ } } }); jQuery.extend( jQuery.find, { matches: function( expr, elements ) { return jQuery.find( expr, null, null, elements ); }, matchesSelector: function( elem, expr ) { return matches.call( elem, expr ); }, attr: function( elem, name ) { return elem.getAttribute( name ); } }); var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, len = this.length, ret = [], self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); jQuery.fn.extend({ has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); var rnotwhite = (/\S+/g); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } } }); /** * The ready event handler and self cleanup method */ function completed() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Kick off the DOM ready check even if the user does not jQuery.ready.promise(); // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : len ? fn( elems[0], key ) : emptyGet; }; /** * Determines whether an object can have data */ jQuery.acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any /* jshint -W018 */ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = jQuery.acceptData; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; var data_priv = new Data(); var data_user = new Data(); /* Implementation Summary 1. Enforce API surface and semantic compatibility with 1.9.x branch 2. Improve the module's maintainability by reducing the storage paths to a single mechanism. 3. Use the same single mechanism to support "private" and "user" data. 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) 5. Avoid exposing implementation details on user objects (eg. expando properties) 6. Provide a clear path for implementation upgrade to WeakMap in 2014 */ var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ); // #11217 - WebKit loses check when the name is after the checked attribute div.innerHTML = "<input type='radio' checked='checked' name='t'/>"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE9-IE11+ div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; })(); var strundefined = typeof undefined; support.focusinBubbles = "onfocusin" in window; var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || // Support: Android < 4.0 src.defaultPrevented === undefined && src.getPreventDefault && src.getPreventDefault() ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari if ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } data_priv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); data_priv.remove( doc, fix ); } else { data_priv.access( doc, fix, attaches ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, events, type, key, j, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( jQuery.acceptData( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { events = Object.keys( data.events || {} ); if ( events.length ) { for ( j = 0; (type = events[j]) !== undefined; j++ ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each(function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } }); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because push.apply(_, arraylike) throws push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle ? // Use of this method is a temporary fix (more like optmization) until something better comes along, // since it was removed from specification and supported only in FF window.getDefaultComputedStyle( elem[ 0 ] ).display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = iframe[ 0 ].contentDocument; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } var rmargin = (/^margin/); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); }; function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // Support: IE9 // getPropertyValue is only needed for .css('filter') in IE9, see #12537 if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; } if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // Support: iOS < 6 // A tribute to the "awesome hack by Dean Edwards" // iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due to missing dependency), // remove it. // Since there are no other hooks for marginRight, remove the whole object. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; } (function() { var pixelPositionVal, boxSizingReliableVal, // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;" + "-moz-box-sizing:content-box;box-sizing:content-box", docElem = document.documentElement, container = document.createElement( "div" ), div = document.createElement( "div" ); div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;" + "margin-top:1px"; container.appendChild( div ); // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computePixelPositionAndBoxSizingReliable() { // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" + "box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;" + "position:absolute;top:1%"; docElem.appendChild( container ); var divStyle = window.getComputedStyle( div, null ); pixelPositionVal = divStyle.top !== "1%"; boxSizingReliableVal = divStyle.width === "4px"; docElem.removeChild( container ); } // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { jQuery.extend(support, { pixelPosition: function() { // This test is executed only once but we still do memoizing // since we can use the boxSizingReliable pre-computing. // No need to check if the test was already performed, though. computePixelPositionAndBoxSizingReliable(); return pixelPositionVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computePixelPositionAndBoxSizingReliable(); } return boxSizingReliableVal; }, reliableMarginRight: function() { // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // This support function is only executed once so no memoizing is needed. var ret, marginDiv = div.appendChild( document.createElement( "div" ) ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; docElem.appendChild( container ); ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight ); docElem.removeChild( container ); // Clean up the div for other support tests. div.innerHTML = ""; return ret; } }); } })(); // A method for quickly swapping in/out CSS properties to get correct calculations. jQuery.swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name[0].toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = data_priv.get( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css(elem, "display") ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set. See: #7116 if ( value == null || value !== value ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifying setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Support: Chrome, Safari // Setting style to blank string required to delete "style: x !important;" style[ name ] = ""; style[ name ] = value; } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); // Support: Android 2.3 jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); jQuery.fn.extend({ css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }; (function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; })(); var nodeHook, boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend({ attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); } }); jQuery.extend({ attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName( elem, "input" ) ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle; if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ name ]; attrHandle[ name ] = ret; ret = getter( elem, name, isXML ) != null ? name.toLowerCase() : null; attrHandle[ name ] = handle; } return ret; }; }); var rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); } }); jQuery.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); var rclass = /[\t\r\n\f]/g; jQuery.fn.extend({ addClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = typeof value === "string" && value, i = 0, len = this.length; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = arguments.length === 0 || typeof value === "string" && value, i = 0, len = this.length; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // only assign if different to avoid unneeded rendering. finalValue = value ? jQuery.trim( cur ) : ""; if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; } }); var rreturn = /\r/g; jQuery.fn.extend({ val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE6-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); // Return jQuery for attributes-only inclusion jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); }) .map(function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; var docElem = window.document.documentElement; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -1; // Need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ offset: function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, elem = this[ 0 ], box = { top: 0, left: 0 }, doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // We assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : window.pageXOffset, top ? val : window.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); }); // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in // AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } return jQuery; }));
import 'classmentors/components/index.js'; import 'classmentors/components/ace/ace.specs.js'; import 'classmentors/components/admin/admin.specs.js'; import 'classmentors/components/classmentors/classmentors.specs.js'; import 'classmentors/components/service-card/service-card.specs.js'; // import 'classmentors/components/cohorts/cohorts.specs.js'; import 'classmentors/components/challenges/challenges.specs.js'; import 'classmentors/components/events/events.specs.js';
/** * Created by alexmadrzyk on 1/29/17. */ (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.adapter = 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){ /* eslint-env node */ 'use strict'; // SDP helpers. var SDPUtils = {}; // Generate an alphanumeric identifier for cname or mids. // TODO: use UUIDs instead? https://gist.github.com/jed/982883 SDPUtils.generateIdentifier = function() { return Math.random().toString(36).substr(2, 10); }; // The RTCP CNAME used by all peerconnections from the same JS. SDPUtils.localCName = SDPUtils.generateIdentifier(); // Splits SDP into lines, dealing with both CRLF and LF. SDPUtils.splitLines = function(blob) { return blob.trim().split('\n').map(function(line) { return line.trim(); }); }; // Splits SDP into sessionpart and mediasections. Ensures CRLF. SDPUtils.splitSections = function(blob) { var parts = blob.split('\nm='); return parts.map(function(part, index) { return (index > 0 ? 'm=' + part : part).trim() + '\r\n'; }); }; // Returns lines that start with a certain prefix. SDPUtils.matchPrefix = function(blob, prefix) { return SDPUtils.splitLines(blob).filter(function(line) { return line.indexOf(prefix) === 0; }); }; // Parses an ICE candidate line. Sample input: // candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8 // rport 55996" SDPUtils.parseCandidate = function(line) { var parts; // Parse both variants. if (line.indexOf('a=candidate:') === 0) { parts = line.substring(12).split(' '); } else { parts = line.substring(10).split(' '); } var candidate = { foundation: parts[0], component: parts[1], protocol: parts[2].toLowerCase(), priority: parseInt(parts[3], 10), ip: parts[4], port: parseInt(parts[5], 10), // skip parts[6] == 'typ' type: parts[7] }; for (var i = 8; i < parts.length; i += 2) { switch (parts[i]) { case 'raddr': candidate.relatedAddress = parts[i + 1]; break; case 'rport': candidate.relatedPort = parseInt(parts[i + 1], 10); break; case 'tcptype': candidate.tcpType = parts[i + 1]; break; default: // Unknown extensions are silently ignored. break; } } return candidate; }; // Translates a candidate object into SDP candidate attribute. SDPUtils.writeCandidate = function(candidate) { var sdp = []; sdp.push(candidate.foundation); sdp.push(candidate.component); sdp.push(candidate.protocol.toUpperCase()); sdp.push(candidate.priority); sdp.push(candidate.ip); sdp.push(candidate.port); var type = candidate.type; sdp.push('typ'); sdp.push(type); if (type !== 'host' && candidate.relatedAddress && candidate.relatedPort) { sdp.push('raddr'); sdp.push(candidate.relatedAddress); // was: relAddr sdp.push('rport'); sdp.push(candidate.relatedPort); // was: relPort } if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') { sdp.push('tcptype'); sdp.push(candidate.tcpType); } return 'candidate:' + sdp.join(' '); }; // Parses an rtpmap line, returns RTCRtpCoddecParameters. Sample input: // a=rtpmap:111 opus/48000/2 SDPUtils.parseRtpMap = function(line) { var parts = line.substr(9).split(' '); var parsed = { payloadType: parseInt(parts.shift(), 10) // was: id }; parts = parts[0].split('/'); parsed.name = parts[0]; parsed.clockRate = parseInt(parts[1], 10); // was: clockrate // was: channels parsed.numChannels = parts.length === 3 ? parseInt(parts[2], 10) : 1; return parsed; }; // Generate an a=rtpmap line from RTCRtpCodecCapability or // RTCRtpCodecParameters. SDPUtils.writeRtpMap = function(codec) { var pt = codec.payloadType; if (codec.preferredPayloadType !== undefined) { pt = codec.preferredPayloadType; } return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate + (codec.numChannels !== 1 ? '/' + codec.numChannels : '') + '\r\n'; }; // Parses an a=extmap line (headerextension from RFC 5285). Sample input: // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset SDPUtils.parseExtmap = function(line) { var parts = line.substr(9).split(' '); return { id: parseInt(parts[0], 10), uri: parts[1] }; }; // Generates a=extmap line from RTCRtpHeaderExtensionParameters or // RTCRtpHeaderExtension. SDPUtils.writeExtmap = function(headerExtension) { return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) + ' ' + headerExtension.uri + '\r\n'; }; // Parses an ftmp line, returns dictionary. Sample input: // a=fmtp:96 vbr=on;cng=on // Also deals with vbr=on; cng=on SDPUtils.parseFmtp = function(line) { var parsed = {}; var kv; var parts = line.substr(line.indexOf(' ') + 1).split(';'); for (var j = 0; j < parts.length; j++) { kv = parts[j].trim().split('='); parsed[kv[0].trim()] = kv[1]; } return parsed; }; // Generates an a=ftmp line from RTCRtpCodecCapability or RTCRtpCodecParameters. SDPUtils.writeFmtp = function(codec) { var line = ''; var pt = codec.payloadType; if (codec.preferredPayloadType !== undefined) { pt = codec.preferredPayloadType; } if (codec.parameters && Object.keys(codec.parameters).length) { var params = []; Object.keys(codec.parameters).forEach(function(param) { params.push(param + '=' + codec.parameters[param]); }); line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n'; } return line; }; // Parses an rtcp-fb line, returns RTCPRtcpFeedback object. Sample input: // a=rtcp-fb:98 nack rpsi SDPUtils.parseRtcpFb = function(line) { var parts = line.substr(line.indexOf(' ') + 1).split(' '); return { type: parts.shift(), parameter: parts.join(' ') }; }; // Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters. SDPUtils.writeRtcpFb = function(codec) { var lines = ''; var pt = codec.payloadType; if (codec.preferredPayloadType !== undefined) { pt = codec.preferredPayloadType; } if (codec.rtcpFeedback && codec.rtcpFeedback.length) { // FIXME: special handling for trr-int? codec.rtcpFeedback.forEach(function(fb) { lines += 'a=rtcp-fb:' + pt + ' ' + fb.type + (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') + '\r\n'; }); } return lines; }; // Parses an RFC 5576 ssrc media attribute. Sample input: // a=ssrc:3735928559 cname:something SDPUtils.parseSsrcMedia = function(line) { var sp = line.indexOf(' '); var parts = { ssrc: parseInt(line.substr(7, sp - 7), 10) }; var colon = line.indexOf(':', sp); if (colon > -1) { parts.attribute = line.substr(sp + 1, colon - sp - 1); parts.value = line.substr(colon + 1); } else { parts.attribute = line.substr(sp + 1); } return parts; }; // Extracts DTLS parameters from SDP media section or sessionpart. // FIXME: for consistency with other functions this should only // get the fingerprint line as input. See also getIceParameters. SDPUtils.getDtlsParameters = function(mediaSection, sessionpart) { var lines = SDPUtils.splitLines(mediaSection); // Search in session part, too. lines = lines.concat(SDPUtils.splitLines(sessionpart)); var fpLine = lines.filter(function(line) { return line.indexOf('a=fingerprint:') === 0; })[0].substr(14); // Note: a=setup line is ignored since we use the 'auto' role. var dtlsParameters = { role: 'auto', fingerprints: [{ algorithm: fpLine.split(' ')[0], value: fpLine.split(' ')[1] }] }; return dtlsParameters; }; // Serializes DTLS parameters to SDP. SDPUtils.writeDtlsParameters = function(params, setupType) { var sdp = 'a=setup:' + setupType + '\r\n'; params.fingerprints.forEach(function(fp) { sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n'; }); return sdp; }; // Parses ICE information from SDP media section or sessionpart. // FIXME: for consistency with other functions this should only // get the ice-ufrag and ice-pwd lines as input. SDPUtils.getIceParameters = function(mediaSection, sessionpart) { var lines = SDPUtils.splitLines(mediaSection); // Search in session part, too. lines = lines.concat(SDPUtils.splitLines(sessionpart)); var iceParameters = { usernameFragment: lines.filter(function(line) { return line.indexOf('a=ice-ufrag:') === 0; })[0].substr(12), password: lines.filter(function(line) { return line.indexOf('a=ice-pwd:') === 0; })[0].substr(10) }; return iceParameters; }; // Serializes ICE parameters to SDP. SDPUtils.writeIceParameters = function(params) { return 'a=ice-ufrag:' + params.usernameFragment + '\r\n' + 'a=ice-pwd:' + params.password + '\r\n'; }; // Parses the SDP media section and returns RTCRtpParameters. SDPUtils.parseRtpParameters = function(mediaSection) { var description = { codecs: [], headerExtensions: [], fecMechanisms: [], rtcp: [] }; var lines = SDPUtils.splitLines(mediaSection); var mline = lines[0].split(' '); for (var i = 3; i < mline.length; i++) { // find all codecs from mline[3..] var pt = mline[i]; var rtpmapline = SDPUtils.matchPrefix( mediaSection, 'a=rtpmap:' + pt + ' ')[0]; if (rtpmapline) { var codec = SDPUtils.parseRtpMap(rtpmapline); var fmtps = SDPUtils.matchPrefix( mediaSection, 'a=fmtp:' + pt + ' '); // Only the first a=fmtp:<pt> is considered. codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {}; codec.rtcpFeedback = SDPUtils.matchPrefix( mediaSection, 'a=rtcp-fb:' + pt + ' ') .map(SDPUtils.parseRtcpFb); description.codecs.push(codec); // parse FEC mechanisms from rtpmap lines. switch (codec.name.toUpperCase()) { case 'RED': case 'ULPFEC': description.fecMechanisms.push(codec.name.toUpperCase()); break; default: // only RED and ULPFEC are recognized as FEC mechanisms. break; } } } SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function(line) { description.headerExtensions.push(SDPUtils.parseExtmap(line)); }); // FIXME: parse rtcp. return description; }; // Generates parts of the SDP media section describing the capabilities / // parameters. SDPUtils.writeRtpDescription = function(kind, caps) { var sdp = ''; // Build the mline. sdp += 'm=' + kind + ' '; sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs. sdp += ' UDP/TLS/RTP/SAVPF '; sdp += caps.codecs.map(function(codec) { if (codec.preferredPayloadType !== undefined) { return codec.preferredPayloadType; } return codec.payloadType; }).join(' ') + '\r\n'; sdp += 'c=IN IP4 0.0.0.0\r\n'; sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n'; // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb. caps.codecs.forEach(function(codec) { sdp += SDPUtils.writeRtpMap(codec); sdp += SDPUtils.writeFmtp(codec); sdp += SDPUtils.writeRtcpFb(codec); }); sdp += 'a=rtcp-mux\r\n'; caps.headerExtensions.forEach(function(extension) { sdp += SDPUtils.writeExtmap(extension); }); // FIXME: write fecMechanisms. return sdp; }; // Parses the SDP media section and returns an array of // RTCRtpEncodingParameters. SDPUtils.parseRtpEncodingParameters = function(mediaSection) { var encodingParameters = []; var description = SDPUtils.parseRtpParameters(mediaSection); var hasRed = description.fecMechanisms.indexOf('RED') !== -1; var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1; // filter a=ssrc:... cname:, ignore PlanB-msid var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:') .map(function(line) { return SDPUtils.parseSsrcMedia(line); }) .filter(function(parts) { return parts.attribute === 'cname'; }); var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc; var secondarySsrc; var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID') .map(function(line) { var parts = line.split(' '); parts.shift(); return parts.map(function(part) { return parseInt(part, 10); }); }); if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) { secondarySsrc = flows[0][1]; } description.codecs.forEach(function(codec) { if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) { var encParam = { ssrc: primarySsrc, codecPayloadType: parseInt(codec.parameters.apt, 10), rtx: { payloadType: codec.payloadType, ssrc: secondarySsrc } }; encodingParameters.push(encParam); if (hasRed) { encParam = JSON.parse(JSON.stringify(encParam)); encParam.fec = { ssrc: secondarySsrc, mechanism: hasUlpfec ? 'red+ulpfec' : 'red' }; encodingParameters.push(encParam); } } }); if (encodingParameters.length === 0 && primarySsrc) { encodingParameters.push({ ssrc: primarySsrc }); } // we support both b=AS and b=TIAS but interpret AS as TIAS. var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b='); if (bandwidth.length) { if (bandwidth[0].indexOf('b=TIAS:') === 0) { bandwidth = parseInt(bandwidth[0].substr(7), 10); } else if (bandwidth[0].indexOf('b=AS:') === 0) { bandwidth = parseInt(bandwidth[0].substr(5), 10); } encodingParameters.forEach(function(params) { params.maxBitrate = bandwidth; }); } return encodingParameters; }; SDPUtils.writeSessionBoilerplate = function() { // FIXME: sess-id should be an NTP timestamp. return 'v=0\r\n' + 'o=thisisadapterortc 8169639915646943137 2 IN IP4 127.0.0.1\r\n' + 's=-\r\n' + 't=0 0\r\n'; }; SDPUtils.writeMediaSection = function(transceiver, caps, type, stream) { var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps); // Map ICE parameters (ufrag, pwd) to SDP. sdp += SDPUtils.writeIceParameters( transceiver.iceGatherer.getLocalParameters()); // Map DTLS parameters to SDP. sdp += SDPUtils.writeDtlsParameters( transceiver.dtlsTransport.getLocalParameters(), type === 'offer' ? 'actpass' : 'active'); sdp += 'a=mid:' + transceiver.mid + '\r\n'; if (transceiver.rtpSender && transceiver.rtpReceiver) { sdp += 'a=sendrecv\r\n'; } else if (transceiver.rtpSender) { sdp += 'a=sendonly\r\n'; } else if (transceiver.rtpReceiver) { sdp += 'a=recvonly\r\n'; } else { sdp += 'a=inactive\r\n'; } // FIXME: for RTX there might be multiple SSRCs. Not implemented in Edge yet. if (transceiver.rtpSender) { var msid = 'msid:' + stream.id + ' ' + transceiver.rtpSender.track.id + '\r\n'; sdp += 'a=' + msid; sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc + ' ' + msid; } // FIXME: this should be written by writeRtpDescription. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc + ' cname:' + SDPUtils.localCName + '\r\n'; return sdp; }; // Gets the direction from the mediaSection or the sessionpart. SDPUtils.getDirection = function(mediaSection, sessionpart) { // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv. var lines = SDPUtils.splitLines(mediaSection); for (var i = 0; i < lines.length; i++) { switch (lines[i]) { case 'a=sendrecv': case 'a=sendonly': case 'a=recvonly': case 'a=inactive': return lines[i].substr(2); default: // FIXME: What should happen here? } } if (sessionpart) { return SDPUtils.getDirection(sessionpart); } return 'sendrecv'; }; // Expose public methods. module.exports = SDPUtils; },{}],2:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; // Shimming starts here. (function() { // Utils. var utils = require('./utils'); var logging = utils.log; var browserDetails = utils.browserDetails; // Export to the adapter global object visible in the browser. module.exports.browserDetails = browserDetails; module.exports.extractVersion = utils.extractVersion; module.exports.disableLog = utils.disableLog; // Uncomment the line below if you want logging to occur, including logging // for the switch statement below. Can also be turned on in the browser via // adapter.disableLog(false), but then logging from the switch statement below // will not appear. // require('./utils').disableLog(false); // Browser shims. var chromeShim = require('./chrome/chrome_shim') || null; var edgeShim = require('./edge/edge_shim') || null; var firefoxShim = require('./firefox/firefox_shim') || null; var safariShim = require('./safari/safari_shim') || null; // Shim browser if found. switch (browserDetails.browser) { case 'opera': // fallthrough as it uses chrome shims case 'chrome': if (!chromeShim || !chromeShim.shimPeerConnection) { logging('Chrome shim is not included in this adapter release.'); return; } logging('adapter.js shimming chrome.'); // Export to the adapter global object visible in the browser. module.exports.browserShim = chromeShim; chromeShim.shimGetUserMedia(); chromeShim.shimMediaStream(); chromeShim.shimSourceObject(); utils.shimCreateObjectURL(); chromeShim.shimPeerConnection(); chromeShim.shimOnTrack(); break; case 'firefox': if (!firefoxShim || !firefoxShim.shimPeerConnection) { logging('Firefox shim is not included in this adapter release.'); return; } logging('adapter.js shimming firefox.'); // Export to the adapter global object visible in the browser. module.exports.browserShim = firefoxShim; firefoxShim.shimGetUserMedia(); utils.shimCreateObjectURL(); firefoxShim.shimSourceObject(); firefoxShim.shimPeerConnection(); firefoxShim.shimOnTrack(); break; case 'edge': if (!edgeShim || !edgeShim.shimPeerConnection) { logging('MS edge shim is not included in this adapter release.'); return; } logging('adapter.js shimming edge.'); // Export to the adapter global object visible in the browser. module.exports.browserShim = edgeShim; edgeShim.shimGetUserMedia(); utils.shimCreateObjectURL(); edgeShim.shimPeerConnection(); break; case 'safari': if (!safariShim) { logging('Safari shim is not included in this adapter release.'); return; } logging('adapter.js shimming safari.'); // Export to the adapter global object visible in the browser. module.exports.browserShim = safariShim; safariShim.shimGetUserMedia(); break; default: logging('Unsupported browser!'); } })(); },{"./chrome/chrome_shim":3,"./edge/edge_shim":5,"./firefox/firefox_shim":7,"./safari/safari_shim":9,"./utils":10}],3:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var logging = require('../utils.js').log; var browserDetails = require('../utils.js').browserDetails; var chromeShim = { shimMediaStream: function() { window.MediaStream = window.MediaStream || window.webkitMediaStream; }, shimOnTrack: function() { if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in window.RTCPeerConnection.prototype)) { Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', { get: function() { return this._ontrack; }, set: function(f) { var self = this; if (this._ontrack) { this.removeEventListener('track', this._ontrack); this.removeEventListener('addstream', this._ontrackpoly); } this.addEventListener('track', this._ontrack = f); this.addEventListener('addstream', this._ontrackpoly = function(e) { // onaddstream does not fire when a track is added to an existing // stream. But stream.onaddtrack is implemented so we use that. e.stream.addEventListener('addtrack', function(te) { var event = new Event('track'); event.track = te.track; event.receiver = {track: te.track}; event.streams = [e.stream]; self.dispatchEvent(event); }); e.stream.getTracks().forEach(function(track) { var event = new Event('track'); event.track = track; event.receiver = {track: track}; event.streams = [e.stream]; this.dispatchEvent(event); }.bind(this)); }.bind(this)); } }); } }, shimSourceObject: function() { if (typeof window === 'object') { if (window.HTMLMediaElement && !('srcObject' in window.HTMLMediaElement.prototype)) { // Shim the srcObject property, once, when HTMLMediaElement is found. Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', { get: function() { return this._srcObject; }, set: function(stream) { var self = this; // Use _srcObject as a private property for this shim this._srcObject = stream; if (this.src) { URL.revokeObjectURL(this.src); } if (!stream) { this.src = ''; return; } this.src = URL.createObjectURL(stream); // We need to recreate the blob url when a track is added or // removed. Doing it manually since we want to avoid a recursion. stream.addEventListener('addtrack', function() { if (self.src) { URL.revokeObjectURL(self.src); } self.src = URL.createObjectURL(stream); }); stream.addEventListener('removetrack', function() { if (self.src) { URL.revokeObjectURL(self.src); } self.src = URL.createObjectURL(stream); }); } }); } } }, shimPeerConnection: function() { // The RTCPeerConnection object. if (!window.RTCPeerConnection) { window.RTCPeerConnection = function(pcConfig, pcConstraints) { // Translate iceTransportPolicy to iceTransports, // see https://code.google.com/p/webrtc/issues/detail?id=4869 // this was fixed in M56 along with unprefixing RTCPeerConnection. logging('PeerConnection'); if (pcConfig && pcConfig.iceTransportPolicy) { pcConfig.iceTransports = pcConfig.iceTransportPolicy; } return new webkitRTCPeerConnection(pcConfig, pcConstraints); }; window.RTCPeerConnection.prototype = webkitRTCPeerConnection.prototype; // wrap static methods. Currently just generateCertificate. if (webkitRTCPeerConnection.generateCertificate) { Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', { get: function() { return webkitRTCPeerConnection.generateCertificate; } }); } } var origGetStats = RTCPeerConnection.prototype.getStats; RTCPeerConnection.prototype.getStats = function(selector, successCallback, errorCallback) { var self = this; var args = arguments; // If selector is a function then we are in the old style stats so just // pass back the original getStats format to avoid breaking old users. if (arguments.length > 0 && typeof selector === 'function') { return origGetStats.apply(this, arguments); } // When spec-style getStats is supported, return those. if (origGetStats.length === 0) { return origGetStats.apply(this, arguments); } var fixChromeStats_ = function(response) { var standardReport = {}; var reports = response.result(); reports.forEach(function(report) { var standardStats = { id: report.id, timestamp: report.timestamp, type: { localcandidate: 'local-candidate', remotecandidate: 'remote-candidate' }[report.type] || report.type }; report.names().forEach(function(name) { standardStats[name] = report.stat(name); }); standardReport[standardStats.id] = standardStats; }); return standardReport; }; // shim getStats with maplike support var makeMapStats = function(stats) { return new Map(Object.keys(stats).map(function(key) { return[key, stats[key]]; })); }; if (arguments.length >= 2) { var successCallbackWrapper_ = function(response) { args[1](makeMapStats(fixChromeStats_(response))); }; return origGetStats.apply(this, [successCallbackWrapper_, arguments[0]]); } // promise-support return new Promise(function(resolve, reject) { origGetStats.apply(self, [ function(response) { resolve(makeMapStats(fixChromeStats_(response))); }, reject]); }).then(successCallback, errorCallback); }; // add promise support -- natively available in Chrome 51 if (browserDetails.version < 51) { ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'] .forEach(function(method) { var nativeMethod = RTCPeerConnection.prototype[method]; RTCPeerConnection.prototype[method] = function() { var args = arguments; var self = this; var promise = new Promise(function(resolve, reject) { nativeMethod.apply(self, [args[0], resolve, reject]); }); if (args.length < 2) { return promise; } return promise.then(function() { args[1].apply(null, []); }, function(err) { if (args.length >= 3) { args[2].apply(null, [err]); } }); }; }); } // promise support for createOffer and createAnswer. Available (without // bugs) since M52: crbug/619289 if (browserDetails.version < 52) { ['createOffer', 'createAnswer'].forEach(function(method) { var nativeMethod = RTCPeerConnection.prototype[method]; RTCPeerConnection.prototype[method] = function() { var self = this; if (arguments.length < 1 || (arguments.length === 1 && typeof arguments[0] === 'object')) { var opts = arguments.length === 1 ? arguments[0] : undefined; return new Promise(function(resolve, reject) { nativeMethod.apply(self, [resolve, reject, opts]); }); } return nativeMethod.apply(this, arguments); }; }); } // shim implicit creation of RTCSessionDescription/RTCIceCandidate ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'] .forEach(function(method) { var nativeMethod = RTCPeerConnection.prototype[method]; RTCPeerConnection.prototype[method] = function() { arguments[0] = new ((method === 'addIceCandidate') ? RTCIceCandidate : RTCSessionDescription)(arguments[0]); return nativeMethod.apply(this, arguments); }; }); // support for addIceCandidate(null or undefined) var nativeAddIceCandidate = RTCPeerConnection.prototype.addIceCandidate; RTCPeerConnection.prototype.addIceCandidate = function() { if (!arguments[0]) { if (arguments[1]) { arguments[1].apply(null); } return Promise.resolve(); } return nativeAddIceCandidate.apply(this, arguments); }; } }; // Expose public methods. module.exports = { shimMediaStream: chromeShim.shimMediaStream, shimOnTrack: chromeShim.shimOnTrack, shimSourceObject: chromeShim.shimSourceObject, shimPeerConnection: chromeShim.shimPeerConnection, shimGetUserMedia: require('./getusermedia') }; },{"../utils.js":10,"./getusermedia":4}],4:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var logging = require('../utils.js').log; // Expose public methods. module.exports = function() { var constraintsToChrome_ = function(c) { if (typeof c !== 'object' || c.mandatory || c.optional) { return c; } var cc = {}; Object.keys(c).forEach(function(key) { if (key === 'require' || key === 'advanced' || key === 'mediaSource') { return; } var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]}; if (r.exact !== undefined && typeof r.exact === 'number') { r.min = r.max = r.exact; } var oldname_ = function(prefix, name) { if (prefix) { return prefix + name.charAt(0).toUpperCase() + name.slice(1); } return (name === 'deviceId') ? 'sourceId' : name; }; if (r.ideal !== undefined) { cc.optional = cc.optional || []; var oc = {}; if (typeof r.ideal === 'number') { oc[oldname_('min', key)] = r.ideal; cc.optional.push(oc); oc = {}; oc[oldname_('max', key)] = r.ideal; cc.optional.push(oc); } else { oc[oldname_('', key)] = r.ideal; cc.optional.push(oc); } } if (r.exact !== undefined && typeof r.exact !== 'number') { cc.mandatory = cc.mandatory || {}; cc.mandatory[oldname_('', key)] = r.exact; } else { ['min', 'max'].forEach(function(mix) { if (r[mix] !== undefined) { cc.mandatory = cc.mandatory || {}; cc.mandatory[oldname_(mix, key)] = r[mix]; } }); } }); if (c.advanced) { cc.optional = (cc.optional || []).concat(c.advanced); } return cc; }; var shimConstraints_ = function(constraints, func) { constraints = JSON.parse(JSON.stringify(constraints)); if (constraints && constraints.audio) { constraints.audio = constraintsToChrome_(constraints.audio); } if (constraints && typeof constraints.video === 'object') { // Shim facingMode for mobile, where it defaults to "user". var face = constraints.video.facingMode; face = face && ((typeof face === 'object') ? face : {ideal: face}); if ((face && (face.exact === 'user' || face.exact === 'environment' || face.ideal === 'user' || face.ideal === 'environment')) && !(navigator.mediaDevices.getSupportedConstraints && navigator.mediaDevices.getSupportedConstraints().facingMode)) { delete constraints.video.facingMode; if (face.exact === 'environment' || face.ideal === 'environment') { // Look for "back" in label, or use last cam (typically back cam). return navigator.mediaDevices.enumerateDevices() .then(function(devices) { devices = devices.filter(function(d) { return d.kind === 'videoinput'; }); var back = devices.find(function(d) { return d.label.toLowerCase().indexOf('back') !== -1; }) || (devices.length && devices[devices.length - 1]); if (back) { constraints.video.deviceId = face.exact ? {exact: back.deviceId} : {ideal: back.deviceId}; } constraints.video = constraintsToChrome_(constraints.video); logging('chrome: ' + JSON.stringify(constraints)); return func(constraints); }); } } constraints.video = constraintsToChrome_(constraints.video); } logging('chrome: ' + JSON.stringify(constraints)); return func(constraints); }; var shimError_ = function(e) { return { name: { PermissionDeniedError: 'NotAllowedError', ConstraintNotSatisfiedError: 'OverconstrainedError' }[e.name] || e.name, message: e.message, constraint: e.constraintName, toString: function() { return this.name + (this.message && ': ') + this.message; } }; }; var getUserMedia_ = function(constraints, onSuccess, onError) { shimConstraints_(constraints, function(c) { navigator.webkitGetUserMedia(c, onSuccess, function(e) { onError(shimError_(e)); }); }); }; navigator.getUserMedia = getUserMedia_; // Returns the result of getUserMedia as a Promise. var getUserMediaPromise_ = function(constraints) { return new Promise(function(resolve, reject) { navigator.getUserMedia(constraints, resolve, reject); }); }; if (!navigator.mediaDevices) { navigator.mediaDevices = { getUserMedia: getUserMediaPromise_, enumerateDevices: function() { return new Promise(function(resolve) { var kinds = {audio: 'audioinput', video: 'videoinput'}; return MediaStreamTrack.getSources(function(devices) { resolve(devices.map(function(device) { return {label: device.label, kind: kinds[device.kind], deviceId: device.id, groupId: ''}; })); }); }); } }; } // A shim for getUserMedia method on the mediaDevices object. // TODO(KaptenJansson) remove once implemented in Chrome stable. if (!navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia = function(constraints) { return getUserMediaPromise_(constraints); }; } else { // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia // function which returns a Promise, it does not accept spec-style // constraints. var origGetUserMedia = navigator.mediaDevices.getUserMedia. bind(navigator.mediaDevices); navigator.mediaDevices.getUserMedia = function(cs) { return shimConstraints_(cs, function(c) { return origGetUserMedia(c).then(function(stream) { if (c.audio && !stream.getAudioTracks().length || c.video && !stream.getVideoTracks().length) { stream.getTracks().forEach(function(track) { track.stop(); }); throw new DOMException('', 'NotFoundError'); } return stream; }, function(e) { return Promise.reject(shimError_(e)); }); }); }; } // Dummy devicechange event methods. // TODO(KaptenJansson) remove once implemented in Chrome stable. if (typeof navigator.mediaDevices.addEventListener === 'undefined') { navigator.mediaDevices.addEventListener = function() { logging('Dummy mediaDevices.addEventListener called.'); }; } if (typeof navigator.mediaDevices.removeEventListener === 'undefined') { navigator.mediaDevices.removeEventListener = function() { logging('Dummy mediaDevices.removeEventListener called.'); }; } }; },{"../utils.js":10}],5:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var SDPUtils = require('sdp'); var browserDetails = require('../utils').browserDetails; var edgeShim = { shimPeerConnection: function() { if (window.RTCIceGatherer) { // ORTC defines an RTCIceCandidate object but no constructor. // Not implemented in Edge. if (!window.RTCIceCandidate) { window.RTCIceCandidate = function(args) { return args; }; } // ORTC does not have a session description object but // other browsers (i.e. Chrome) that will support both PC and ORTC // in the future might have this defined already. if (!window.RTCSessionDescription) { window.RTCSessionDescription = function(args) { return args; }; } // this adds an additional event listener to MediaStrackTrack that signals // when a tracks enabled property was changed. var origMSTEnabled = Object.getOwnPropertyDescriptor( MediaStreamTrack.prototype, 'enabled'); Object.defineProperty(MediaStreamTrack.prototype, 'enabled', { set: function(value) { origMSTEnabled.set.call(this, value); var ev = new Event('enabled'); ev.enabled = value; this.dispatchEvent(ev); } }); } window.RTCPeerConnection = function(config) { var self = this; var _eventTarget = document.createDocumentFragment(); ['addEventListener', 'removeEventListener', 'dispatchEvent'] .forEach(function(method) { self[method] = _eventTarget[method].bind(_eventTarget); }); this.onicecandidate = null; this.onaddstream = null; this.ontrack = null; this.onremovestream = null; this.onsignalingstatechange = null; this.oniceconnectionstatechange = null; this.onnegotiationneeded = null; this.ondatachannel = null; this.localStreams = []; this.remoteStreams = []; this.getLocalStreams = function() { return self.localStreams; }; this.getRemoteStreams = function() { return self.remoteStreams; }; this.localDescription = new RTCSessionDescription({ type: '', sdp: '' }); this.remoteDescription = new RTCSessionDescription({ type: '', sdp: '' }); this.signalingState = 'stable'; this.iceConnectionState = 'new'; this.iceGatheringState = 'new'; this.iceOptions = { gatherPolicy: 'all', iceServers: [] }; if (config && config.iceTransportPolicy) { switch (config.iceTransportPolicy) { case 'all': case 'relay': this.iceOptions.gatherPolicy = config.iceTransportPolicy; break; case 'none': // FIXME: remove once implementation and spec have added this. throw new TypeError('iceTransportPolicy "none" not supported'); default: // don't set iceTransportPolicy. break; } } this.usingBundle = config && config.bundlePolicy === 'max-bundle'; if (config && config.iceServers) { // Edge does not like // 1) stun: // 2) turn: that does not have all of turn:host:port?transport=udp // 3) turn: with ipv6 addresses var iceServers = JSON.parse(JSON.stringify(config.iceServers)); this.iceOptions.iceServers = iceServers.filter(function(server) { if (server && server.urls) { var urls = server.urls; if (typeof urls === 'string') { urls = [urls]; } urls = urls.filter(function(url) { return (url.indexOf('turn:') === 0 && url.indexOf('transport=udp') !== -1 && url.indexOf('turn:[') === -1) || (url.indexOf('stun:') === 0 && browserDetails.version >= 14393); })[0]; return !!urls; } return false; }); } this._config = config; // per-track iceGathers, iceTransports, dtlsTransports, rtpSenders, ... // everything that is needed to describe a SDP m-line. this.transceivers = []; // since the iceGatherer is currently created in createOffer but we // must not emit candidates until after setLocalDescription we buffer // them in this array. this._localIceCandidatesBuffer = []; }; window.RTCPeerConnection.prototype._emitBufferedCandidates = function() { var self = this; var sections = SDPUtils.splitSections(self.localDescription.sdp); // FIXME: need to apply ice candidates in a way which is async but // in-order this._localIceCandidatesBuffer.forEach(function(event) { var end = !event.candidate || Object.keys(event.candidate).length === 0; if (end) { for (var j = 1; j < sections.length; j++) { if (sections[j].indexOf('\r\na=end-of-candidates\r\n') === -1) { sections[j] += 'a=end-of-candidates\r\n'; } } } else { sections[event.candidate.sdpMLineIndex + 1] += 'a=' + event.candidate.candidate + '\r\n'; } self.localDescription.sdp = sections.join(''); self.dispatchEvent(event); if (self.onicecandidate !== null) { self.onicecandidate(event); } if (!event.candidate && self.iceGatheringState !== 'complete') { var complete = self.transceivers.every(function(transceiver) { return transceiver.iceGatherer && transceiver.iceGatherer.state === 'completed'; }); if (complete) { self.iceGatheringState = 'complete'; } } }); this._localIceCandidatesBuffer = []; }; window.RTCPeerConnection.prototype.getConfiguration = function() { return this._config; }; window.RTCPeerConnection.prototype.addStream = function(stream) { // Clone is necessary for local demos mostly, attaching directly // to two different senders does not work (build 10547). var clonedStream = stream.clone(); stream.getTracks().forEach(function(track, idx) { var clonedTrack = clonedStream.getTracks()[idx]; track.addEventListener('enabled', function(event) { clonedTrack.enabled = event.enabled; }); }); this.localStreams.push(clonedStream); this._maybeFireNegotiationNeeded(); }; window.RTCPeerConnection.prototype.removeStream = function(stream) { var idx = this.localStreams.indexOf(stream); if (idx > -1) { this.localStreams.splice(idx, 1); this._maybeFireNegotiationNeeded(); } }; window.RTCPeerConnection.prototype.getSenders = function() { return this.transceivers.filter(function(transceiver) { return !!transceiver.rtpSender; }) .map(function(transceiver) { return transceiver.rtpSender; }); }; window.RTCPeerConnection.prototype.getReceivers = function() { return this.transceivers.filter(function(transceiver) { return !!transceiver.rtpReceiver; }) .map(function(transceiver) { return transceiver.rtpReceiver; }); }; // Determines the intersection of local and remote capabilities. window.RTCPeerConnection.prototype._getCommonCapabilities = function(localCapabilities, remoteCapabilities) { var commonCapabilities = { codecs: [], headerExtensions: [], fecMechanisms: [] }; localCapabilities.codecs.forEach(function(lCodec) { for (var i = 0; i < remoteCapabilities.codecs.length; i++) { var rCodec = remoteCapabilities.codecs[i]; if (lCodec.name.toLowerCase() === rCodec.name.toLowerCase() && lCodec.clockRate === rCodec.clockRate) { // number of channels is the highest common number of channels rCodec.numChannels = Math.min(lCodec.numChannels, rCodec.numChannels); // push rCodec so we reply with offerer payload type commonCapabilities.codecs.push(rCodec); // determine common feedback mechanisms rCodec.rtcpFeedback = rCodec.rtcpFeedback.filter(function(fb) { for (var j = 0; j < lCodec.rtcpFeedback.length; j++) { if (lCodec.rtcpFeedback[j].type === fb.type && lCodec.rtcpFeedback[j].parameter === fb.parameter) { return true; } } return false; }); // FIXME: also need to determine .parameters // see https://github.com/openpeer/ortc/issues/569 break; } } }); localCapabilities.headerExtensions .forEach(function(lHeaderExtension) { for (var i = 0; i < remoteCapabilities.headerExtensions.length; i++) { var rHeaderExtension = remoteCapabilities.headerExtensions[i]; if (lHeaderExtension.uri === rHeaderExtension.uri) { commonCapabilities.headerExtensions.push(rHeaderExtension); break; } } }); // FIXME: fecMechanisms return commonCapabilities; }; // Create ICE gatherer, ICE transport and DTLS transport. window.RTCPeerConnection.prototype._createIceAndDtlsTransports = function(mid, sdpMLineIndex) { var self = this; var iceGatherer = new RTCIceGatherer(self.iceOptions); var iceTransport = new RTCIceTransport(iceGatherer); iceGatherer.onlocalcandidate = function(evt) { var event = new Event('icecandidate'); event.candidate = {sdpMid: mid, sdpMLineIndex: sdpMLineIndex}; var cand = evt.candidate; var end = !cand || Object.keys(cand).length === 0; // Edge emits an empty object for RTCIceCandidateComplete‥ if (end) { // polyfill since RTCIceGatherer.state is not implemented in // Edge 10547 yet. if (iceGatherer.state === undefined) { iceGatherer.state = 'completed'; } } else { // RTCIceCandidate doesn't have a component, needs to be added cand.component = iceTransport.component === 'RTCP' ? 2 : 1; event.candidate.candidate = SDPUtils.writeCandidate(cand); } // update local description. var sections = SDPUtils.splitSections(self.localDescription.sdp); if (!end) { sections[event.candidate.sdpMLineIndex + 1] += 'a=' + event.candidate.candidate + '\r\n'; } else { sections[event.candidate.sdpMLineIndex + 1] += 'a=end-of-candidates\r\n'; } self.localDescription.sdp = sections.join(''); var transceivers = self._pendingOffer ? self._pendingOffer : self.transceivers; var complete = transceivers.every(function(transceiver) { return transceiver.iceGatherer && transceiver.iceGatherer.state === 'completed'; }); // Emit candidate if localDescription is set. // Also emits null candidate when all gatherers are complete. switch (self.iceGatheringState) { case 'new': if (!end) { self._localIceCandidatesBuffer.push(event); } if (end && complete) { self._localIceCandidatesBuffer.push( new Event('icecandidate')); } break; case 'gathering': self._emitBufferedCandidates(); if (!end) { self.dispatchEvent(event); if (self.onicecandidate !== null) { self.onicecandidate(event); } } if (complete) { self.dispatchEvent(new Event('icecandidate')); if (self.onicecandidate !== null) { self.onicecandidate(new Event('icecandidate')); } self.iceGatheringState = 'complete'; } break; case 'complete': // should not happen... currently! break; default: // no-op. break; } }; iceTransport.onicestatechange = function() { self._updateConnectionState(); }; var dtlsTransport = new RTCDtlsTransport(iceTransport); dtlsTransport.ondtlsstatechange = function() { self._updateConnectionState(); }; dtlsTransport.onerror = function() { // onerror does not set state to failed by itself. dtlsTransport.state = 'failed'; self._updateConnectionState(); }; return { iceGatherer: iceGatherer, iceTransport: iceTransport, dtlsTransport: dtlsTransport }; }; // Start the RTP Sender and Receiver for a transceiver. window.RTCPeerConnection.prototype._transceive = function(transceiver, send, recv) { var params = this._getCommonCapabilities(transceiver.localCapabilities, transceiver.remoteCapabilities); if (send && transceiver.rtpSender) { params.encodings = transceiver.sendEncodingParameters; params.rtcp = { cname: SDPUtils.localCName }; if (transceiver.recvEncodingParameters.length) { params.rtcp.ssrc = transceiver.recvEncodingParameters[0].ssrc; } transceiver.rtpSender.send(params); } if (recv && transceiver.rtpReceiver) { // remove RTX field in Edge 14942 if (transceiver.kind === 'video' && transceiver.recvEncodingParameters) { transceiver.recvEncodingParameters.forEach(function(p) { delete p.rtx; }); } params.encodings = transceiver.recvEncodingParameters; params.rtcp = { cname: transceiver.cname }; if (transceiver.sendEncodingParameters.length) { params.rtcp.ssrc = transceiver.sendEncodingParameters[0].ssrc; } transceiver.rtpReceiver.receive(params); } }; window.RTCPeerConnection.prototype.setLocalDescription = function(description) { var self = this; var sections; var sessionpart; if (description.type === 'offer') { // FIXME: What was the purpose of this empty if statement? // if (!this._pendingOffer) { // } else { if (this._pendingOffer) { // VERY limited support for SDP munging. Limited to: // * changing the order of codecs sections = SDPUtils.splitSections(description.sdp); sessionpart = sections.shift(); sections.forEach(function(mediaSection, sdpMLineIndex) { var caps = SDPUtils.parseRtpParameters(mediaSection); self._pendingOffer[sdpMLineIndex].localCapabilities = caps; }); this.transceivers = this._pendingOffer; delete this._pendingOffer; } } else if (description.type === 'answer') { sections = SDPUtils.splitSections(self.remoteDescription.sdp); sessionpart = sections.shift(); var isIceLite = SDPUtils.matchPrefix(sessionpart, 'a=ice-lite').length > 0; sections.forEach(function(mediaSection, sdpMLineIndex) { var transceiver = self.transceivers[sdpMLineIndex]; var iceGatherer = transceiver.iceGatherer; var iceTransport = transceiver.iceTransport; var dtlsTransport = transceiver.dtlsTransport; var localCapabilities = transceiver.localCapabilities; var remoteCapabilities = transceiver.remoteCapabilities; var rejected = mediaSection.split('\n', 1)[0] .split(' ', 2)[1] === '0'; if (!rejected && !transceiver.isDatachannel) { var remoteIceParameters = SDPUtils.getIceParameters( mediaSection, sessionpart); var remoteDtlsParameters = SDPUtils.getDtlsParameters( mediaSection, sessionpart); if (isIceLite) { remoteDtlsParameters.role = 'server'; } if (!self.usingBundle || sdpMLineIndex === 0) { iceTransport.start(iceGatherer, remoteIceParameters, isIceLite ? 'controlling' : 'controlled'); dtlsTransport.start(remoteDtlsParameters); } // Calculate intersection of capabilities. var params = self._getCommonCapabilities(localCapabilities, remoteCapabilities); // Start the RTCRtpSender. The RTCRtpReceiver for this // transceiver has already been started in setRemoteDescription. self._transceive(transceiver, params.codecs.length > 0, false); } }); } this.localDescription = { type: description.type, sdp: description.sdp }; switch (description.type) { case 'offer': this._updateSignalingState('have-local-offer'); break; case 'answer': this._updateSignalingState('stable'); break; default: throw new TypeError('unsupported type "' + description.type + '"'); } // If a success callback was provided, emit ICE candidates after it // has been executed. Otherwise, emit callback after the Promise is // resolved. var hasCallback = arguments.length > 1 && typeof arguments[1] === 'function'; if (hasCallback) { var cb = arguments[1]; window.setTimeout(function() { cb(); if (self.iceGatheringState === 'new') { self.iceGatheringState = 'gathering'; } self._emitBufferedCandidates(); }, 0); } var p = Promise.resolve(); p.then(function() { if (!hasCallback) { if (self.iceGatheringState === 'new') { self.iceGatheringState = 'gathering'; } // Usually candidates will be emitted earlier. window.setTimeout(self._emitBufferedCandidates.bind(self), 500); } }); return p; }; window.RTCPeerConnection.prototype.setRemoteDescription = function(description) { var self = this; var stream = new MediaStream(); var receiverList = []; var sections = SDPUtils.splitSections(description.sdp); var sessionpart = sections.shift(); var isIceLite = SDPUtils.matchPrefix(sessionpart, 'a=ice-lite').length > 0; this.usingBundle = SDPUtils.matchPrefix(sessionpart, 'a=group:BUNDLE ').length > 0; sections.forEach(function(mediaSection, sdpMLineIndex) { var lines = SDPUtils.splitLines(mediaSection); var mline = lines[0].substr(2).split(' '); var kind = mline[0]; var rejected = mline[1] === '0'; var direction = SDPUtils.getDirection(mediaSection, sessionpart); var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:'); if (mid.length) { mid = mid[0].substr(6); } else { mid = SDPUtils.generateIdentifier(); } // Reject datachannels which are not implemented yet. if (kind === 'application' && mline[2] === 'DTLS/SCTP') { self.transceivers[sdpMLineIndex] = { mid: mid, isDatachannel: true }; return; } var transceiver; var iceGatherer; var iceTransport; var dtlsTransport; var rtpSender; var rtpReceiver; var sendEncodingParameters; var recvEncodingParameters; var localCapabilities; var track; // FIXME: ensure the mediaSection has rtcp-mux set. var remoteCapabilities = SDPUtils.parseRtpParameters(mediaSection); var remoteIceParameters; var remoteDtlsParameters; if (!rejected) { remoteIceParameters = SDPUtils.getIceParameters(mediaSection, sessionpart); remoteDtlsParameters = SDPUtils.getDtlsParameters(mediaSection, sessionpart); remoteDtlsParameters.role = 'client'; } recvEncodingParameters = SDPUtils.parseRtpEncodingParameters(mediaSection); var cname; // Gets the first SSRC. Note that with RTX there might be multiple // SSRCs. var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:') .map(function(line) { return SDPUtils.parseSsrcMedia(line); }) .filter(function(obj) { return obj.attribute === 'cname'; })[0]; if (remoteSsrc) { cname = remoteSsrc.value; } var isComplete = SDPUtils.matchPrefix(mediaSection, 'a=end-of-candidates', sessionpart).length > 0; var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:') .map(function(cand) { return SDPUtils.parseCandidate(cand); }) .filter(function(cand) { return cand.component === '1'; }); if (description.type === 'offer' && !rejected) { var transports = self.usingBundle && sdpMLineIndex > 0 ? { iceGatherer: self.transceivers[0].iceGatherer, iceTransport: self.transceivers[0].iceTransport, dtlsTransport: self.transceivers[0].dtlsTransport } : self._createIceAndDtlsTransports(mid, sdpMLineIndex); if (isComplete && (!self.usingBundle || sdpMLineIndex === 0)) { transports.iceTransport.setRemoteCandidates(cands); } localCapabilities = RTCRtpReceiver.getCapabilities(kind); // filter RTX until additional stuff needed for RTX is implemented // in adapter.js localCapabilities.codecs = localCapabilities.codecs.filter( function(codec) { return codec.name !== 'rtx'; }); sendEncodingParameters = [{ ssrc: (2 * sdpMLineIndex + 2) * 1001 }]; rtpReceiver = new RTCRtpReceiver(transports.dtlsTransport, kind); track = rtpReceiver.track; receiverList.push([track, rtpReceiver]); // FIXME: not correct when there are multiple streams but that is // not currently supported in this shim. stream.addTrack(track); // FIXME: look at direction. if (self.localStreams.length > 0 && self.localStreams[0].getTracks().length >= sdpMLineIndex) { var localTrack; if (kind === 'audio') { localTrack = self.localStreams[0].getAudioTracks()[0]; } else if (kind === 'video') { localTrack = self.localStreams[0].getVideoTracks()[0]; } if (localTrack) { rtpSender = new RTCRtpSender(localTrack, transports.dtlsTransport); } } self.transceivers[sdpMLineIndex] = { iceGatherer: transports.iceGatherer, iceTransport: transports.iceTransport, dtlsTransport: transports.dtlsTransport, localCapabilities: localCapabilities, remoteCapabilities: remoteCapabilities, rtpSender: rtpSender, rtpReceiver: rtpReceiver, kind: kind, mid: mid, cname: cname, sendEncodingParameters: sendEncodingParameters, recvEncodingParameters: recvEncodingParameters }; // Start the RTCRtpReceiver now. The RTPSender is started in // setLocalDescription. self._transceive(self.transceivers[sdpMLineIndex], false, direction === 'sendrecv' || direction === 'sendonly'); } else if (description.type === 'answer' && !rejected) { transceiver = self.transceivers[sdpMLineIndex]; iceGatherer = transceiver.iceGatherer; iceTransport = transceiver.iceTransport; dtlsTransport = transceiver.dtlsTransport; rtpSender = transceiver.rtpSender; rtpReceiver = transceiver.rtpReceiver; sendEncodingParameters = transceiver.sendEncodingParameters; localCapabilities = transceiver.localCapabilities; self.transceivers[sdpMLineIndex].recvEncodingParameters = recvEncodingParameters; self.transceivers[sdpMLineIndex].remoteCapabilities = remoteCapabilities; self.transceivers[sdpMLineIndex].cname = cname; if ((isIceLite || isComplete) && cands.length) { iceTransport.setRemoteCandidates(cands); } if (!self.usingBundle || sdpMLineIndex === 0) { iceTransport.start(iceGatherer, remoteIceParameters, 'controlling'); dtlsTransport.start(remoteDtlsParameters); } self._transceive(transceiver, direction === 'sendrecv' || direction === 'recvonly', direction === 'sendrecv' || direction === 'sendonly'); if (rtpReceiver && (direction === 'sendrecv' || direction === 'sendonly')) { track = rtpReceiver.track; receiverList.push([track, rtpReceiver]); stream.addTrack(track); } else { // FIXME: actually the receiver should be created later. delete transceiver.rtpReceiver; } } }); this.remoteDescription = { type: description.type, sdp: description.sdp }; switch (description.type) { case 'offer': this._updateSignalingState('have-remote-offer'); break; case 'answer': this._updateSignalingState('stable'); break; default: throw new TypeError('unsupported type "' + description.type + '"'); } if (stream.getTracks().length) { self.remoteStreams.push(stream); window.setTimeout(function() { var event = new Event('addstream'); event.stream = stream; self.dispatchEvent(event); if (self.onaddstream !== null) { window.setTimeout(function() { self.onaddstream(event); }, 0); } receiverList.forEach(function(item) { var track = item[0]; var receiver = item[1]; var trackEvent = new Event('track'); trackEvent.track = track; trackEvent.receiver = receiver; trackEvent.streams = [stream]; self.dispatchEvent(trackEvent); if (self.ontrack !== null) { window.setTimeout(function() { self.ontrack(trackEvent); }, 0); } }); }, 0); } if (arguments.length > 1 && typeof arguments[1] === 'function') { window.setTimeout(arguments[1], 0); } return Promise.resolve(); }; window.RTCPeerConnection.prototype.close = function() { this.transceivers.forEach(function(transceiver) { /* not yet if (transceiver.iceGatherer) { transceiver.iceGatherer.close(); } */ if (transceiver.iceTransport) { transceiver.iceTransport.stop(); } if (transceiver.dtlsTransport) { transceiver.dtlsTransport.stop(); } if (transceiver.rtpSender) { transceiver.rtpSender.stop(); } if (transceiver.rtpReceiver) { transceiver.rtpReceiver.stop(); } }); // FIXME: clean up tracks, local streams, remote streams, etc this._updateSignalingState('closed'); }; // Update the signaling state. window.RTCPeerConnection.prototype._updateSignalingState = function(newState) { this.signalingState = newState; var event = new Event('signalingstatechange'); this.dispatchEvent(event); if (this.onsignalingstatechange !== null) { this.onsignalingstatechange(event); } }; // Determine whether to fire the negotiationneeded event. window.RTCPeerConnection.prototype._maybeFireNegotiationNeeded = function() { // Fire away (for now). var event = new Event('negotiationneeded'); this.dispatchEvent(event); if (this.onnegotiationneeded !== null) { this.onnegotiationneeded(event); } }; // Update the connection state. window.RTCPeerConnection.prototype._updateConnectionState = function() { var self = this; var newState; var states = { 'new': 0, closed: 0, connecting: 0, checking: 0, connected: 0, completed: 0, failed: 0 }; this.transceivers.forEach(function(transceiver) { states[transceiver.iceTransport.state]++; states[transceiver.dtlsTransport.state]++; }); // ICETransport.completed and connected are the same for this purpose. states.connected += states.completed; newState = 'new'; if (states.failed > 0) { newState = 'failed'; } else if (states.connecting > 0 || states.checking > 0) { newState = 'connecting'; } else if (states.disconnected > 0) { newState = 'disconnected'; } else if (states.new > 0) { newState = 'new'; } else if (states.connected > 0 || states.completed > 0) { newState = 'connected'; } if (newState !== self.iceConnectionState) { self.iceConnectionState = newState; var event = new Event('iceconnectionstatechange'); this.dispatchEvent(event); if (this.oniceconnectionstatechange !== null) { this.oniceconnectionstatechange(event); } } }; window.RTCPeerConnection.prototype.createOffer = function() { var self = this; if (this._pendingOffer) { throw new Error('createOffer called while there is a pending offer.'); } var offerOptions; if (arguments.length === 1 && typeof arguments[0] !== 'function') { offerOptions = arguments[0]; } else if (arguments.length === 3) { offerOptions = arguments[2]; } var tracks = []; var numAudioTracks = 0; var numVideoTracks = 0; // Default to sendrecv. if (this.localStreams.length) { numAudioTracks = this.localStreams[0].getAudioTracks().length; numVideoTracks = this.localStreams[0].getVideoTracks().length; } // Determine number of audio and video tracks we need to send/recv. if (offerOptions) { // Reject Chrome legacy constraints. if (offerOptions.mandatory || offerOptions.optional) { throw new TypeError( 'Legacy mandatory/optional constraints not supported.'); } if (offerOptions.offerToReceiveAudio !== undefined) { numAudioTracks = offerOptions.offerToReceiveAudio; } if (offerOptions.offerToReceiveVideo !== undefined) { numVideoTracks = offerOptions.offerToReceiveVideo; } } if (this.localStreams.length) { // Push local streams. this.localStreams[0].getTracks().forEach(function(track) { tracks.push({ kind: track.kind, track: track, wantReceive: track.kind === 'audio' ? numAudioTracks > 0 : numVideoTracks > 0 }); if (track.kind === 'audio') { numAudioTracks--; } else if (track.kind === 'video') { numVideoTracks--; } }); } // Create M-lines for recvonly streams. while (numAudioTracks > 0 || numVideoTracks > 0) { if (numAudioTracks > 0) { tracks.push({ kind: 'audio', wantReceive: true }); numAudioTracks--; } if (numVideoTracks > 0) { tracks.push({ kind: 'video', wantReceive: true }); numVideoTracks--; } } var sdp = SDPUtils.writeSessionBoilerplate(); var transceivers = []; tracks.forEach(function(mline, sdpMLineIndex) { // For each track, create an ice gatherer, ice transport, // dtls transport, potentially rtpsender and rtpreceiver. var track = mline.track; var kind = mline.kind; var mid = SDPUtils.generateIdentifier(); var transports = self.usingBundle && sdpMLineIndex > 0 ? { iceGatherer: transceivers[0].iceGatherer, iceTransport: transceivers[0].iceTransport, dtlsTransport: transceivers[0].dtlsTransport } : self._createIceAndDtlsTransports(mid, sdpMLineIndex); var localCapabilities = RTCRtpSender.getCapabilities(kind); // filter RTX until additional stuff needed for RTX is implemented // in adapter.js localCapabilities.codecs = localCapabilities.codecs.filter( function(codec) { return codec.name !== 'rtx'; }); localCapabilities.codecs.forEach(function(codec) { // work around https://bugs.chromium.org/p/webrtc/issues/detail?id=6552 // by adding level-asymmetry-allowed=1 if (codec.name === 'H264' && codec.parameters['level-asymmetry-allowed'] === undefined) { codec.parameters['level-asymmetry-allowed'] = '1'; } }); var rtpSender; var rtpReceiver; // generate an ssrc now, to be used later in rtpSender.send var sendEncodingParameters = [{ ssrc: (2 * sdpMLineIndex + 1) * 1001 }]; if (track) { rtpSender = new RTCRtpSender(track, transports.dtlsTransport); } if (mline.wantReceive) { rtpReceiver = new RTCRtpReceiver(transports.dtlsTransport, kind); } transceivers[sdpMLineIndex] = { iceGatherer: transports.iceGatherer, iceTransport: transports.iceTransport, dtlsTransport: transports.dtlsTransport, localCapabilities: localCapabilities, remoteCapabilities: null, rtpSender: rtpSender, rtpReceiver: rtpReceiver, kind: kind, mid: mid, sendEncodingParameters: sendEncodingParameters, recvEncodingParameters: null }; }); if (this.usingBundle) { sdp += 'a=group:BUNDLE ' + transceivers.map(function(t) { return t.mid; }).join(' ') + '\r\n'; } tracks.forEach(function(mline, sdpMLineIndex) { var transceiver = transceivers[sdpMLineIndex]; sdp += SDPUtils.writeMediaSection(transceiver, transceiver.localCapabilities, 'offer', self.localStreams[0]); }); this._pendingOffer = transceivers; var desc = new RTCSessionDescription({ type: 'offer', sdp: sdp }); if (arguments.length && typeof arguments[0] === 'function') { window.setTimeout(arguments[0], 0, desc); } return Promise.resolve(desc); }; window.RTCPeerConnection.prototype.createAnswer = function() { var self = this; var sdp = SDPUtils.writeSessionBoilerplate(); if (this.usingBundle) { sdp += 'a=group:BUNDLE ' + this.transceivers.map(function(t) { return t.mid; }).join(' ') + '\r\n'; } this.transceivers.forEach(function(transceiver) { if (transceiver.isDatachannel) { sdp += 'm=application 0 DTLS/SCTP 5000\r\n' + 'c=IN IP4 0.0.0.0\r\n' + 'a=mid:' + transceiver.mid + '\r\n'; return; } // Calculate intersection of capabilities. var commonCapabilities = self._getCommonCapabilities( transceiver.localCapabilities, transceiver.remoteCapabilities); sdp += SDPUtils.writeMediaSection(transceiver, commonCapabilities, 'answer', self.localStreams[0]); }); var desc = new RTCSessionDescription({ type: 'answer', sdp: sdp }); if (arguments.length && typeof arguments[0] === 'function') { window.setTimeout(arguments[0], 0, desc); } return Promise.resolve(desc); }; window.RTCPeerConnection.prototype.addIceCandidate = function(candidate) { if (!candidate) { for (var j = 0; j < this.transceivers.length; j++) { this.transceivers[j].iceTransport.addRemoteCandidate({}); if (this.usingBundle) { return; } } } else { var mLineIndex = candidate.sdpMLineIndex; if (candidate.sdpMid) { for (var i = 0; i < this.transceivers.length; i++) { if (this.transceivers[i].mid === candidate.sdpMid) { mLineIndex = i; break; } } } var transceiver = this.transceivers[mLineIndex]; if (transceiver) { var cand = Object.keys(candidate.candidate).length > 0 ? SDPUtils.parseCandidate(candidate.candidate) : {}; // Ignore Chrome's invalid candidates since Edge does not like them. if (cand.protocol === 'tcp' && (cand.port === 0 || cand.port === 9)) { return; } // Ignore RTCP candidates, we assume RTCP-MUX. if (cand.component !== '1') { return; } transceiver.iceTransport.addRemoteCandidate(cand); // update the remoteDescription. var sections = SDPUtils.splitSections(this.remoteDescription.sdp); sections[mLineIndex + 1] += (cand.type ? candidate.candidate.trim() : 'a=end-of-candidates') + '\r\n'; this.remoteDescription.sdp = sections.join(''); } } if (arguments.length > 1 && typeof arguments[1] === 'function') { window.setTimeout(arguments[1], 0); } return Promise.resolve(); }; window.RTCPeerConnection.prototype.getStats = function() { var promises = []; this.transceivers.forEach(function(transceiver) { ['rtpSender', 'rtpReceiver', 'iceGatherer', 'iceTransport', 'dtlsTransport'].forEach(function(method) { if (transceiver[method]) { promises.push(transceiver[method].getStats()); } }); }); var cb = arguments.length > 1 && typeof arguments[1] === 'function' && arguments[1]; var fixStatsType = function(stat) { stat.type = { inboundrtp: 'inbound-rtp', outboundrtp: 'outbound-rtp', candidatepair: 'candidate-pair', localcandidate: 'local-candidate', remotecandidate: 'remote-candidate' }[stat.type] || stat.type; return stat; }; return new Promise(function(resolve) { // shim getStats with maplike support var results = new Map(); Promise.all(promises).then(function(res) { res.forEach(function(result) { Object.keys(result).forEach(function(id) { result[id].type = fixStatsType(result[id]); results.set(id, result[id]); }); }); if (cb) { window.setTimeout(cb, 0, results); } resolve(results); }); }); }; } }; // Expose public methods. module.exports = { shimPeerConnection: edgeShim.shimPeerConnection, shimGetUserMedia: require('./getusermedia') }; },{"../utils":10,"./getusermedia":6,"sdp":1}],6:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; // Expose public methods. module.exports = function() { var shimError_ = function(e) { return { name: {PermissionDeniedError: 'NotAllowedError'}[e.name] || e.name, message: e.message, constraint: e.constraint, toString: function() { return this.name; } }; }; // getUserMedia error shim. var origGetUserMedia = navigator.mediaDevices.getUserMedia. bind(navigator.mediaDevices); navigator.mediaDevices.getUserMedia = function(c) { return origGetUserMedia(c).catch(function(e) { return Promise.reject(shimError_(e)); }); }; }; },{}],7:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var browserDetails = require('../utils').browserDetails; var firefoxShim = { shimOnTrack: function() { if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in window.RTCPeerConnection.prototype)) { Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', { get: function() { return this._ontrack; }, set: function(f) { if (this._ontrack) { this.removeEventListener('track', this._ontrack); this.removeEventListener('addstream', this._ontrackpoly); } this.addEventListener('track', this._ontrack = f); this.addEventListener('addstream', this._ontrackpoly = function(e) { e.stream.getTracks().forEach(function(track) { var event = new Event('track'); event.track = track; event.receiver = {track: track}; event.streams = [e.stream]; this.dispatchEvent(event); }.bind(this)); }.bind(this)); } }); } }, shimSourceObject: function() { // Firefox has supported mozSrcObject since FF22, unprefixed in 42. if (typeof window === 'object') { if (window.HTMLMediaElement && !('srcObject' in window.HTMLMediaElement.prototype)) { // Shim the srcObject property, once, when HTMLMediaElement is found. Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', { get: function() { return this.mozSrcObject; }, set: function(stream) { this.mozSrcObject = stream; } }); } } }, shimPeerConnection: function() { if (typeof window !== 'object' || !(window.RTCPeerConnection || window.mozRTCPeerConnection)) { return; // probably media.peerconnection.enabled=false in about:config } // The RTCPeerConnection object. if (!window.RTCPeerConnection) { window.RTCPeerConnection = function(pcConfig, pcConstraints) { if (browserDetails.version < 38) { // .urls is not supported in FF < 38. // create RTCIceServers with a single url. if (pcConfig && pcConfig.iceServers) { var newIceServers = []; for (var i = 0; i < pcConfig.iceServers.length; i++) { var server = pcConfig.iceServers[i]; if (server.hasOwnProperty('urls')) { for (var j = 0; j < server.urls.length; j++) { var newServer = { url: server.urls[j] }; if (server.urls[j].indexOf('turn') === 0) { newServer.username = server.username; newServer.credential = server.credential; } newIceServers.push(newServer); } } else { newIceServers.push(pcConfig.iceServers[i]); } } pcConfig.iceServers = newIceServers; } } return new mozRTCPeerConnection(pcConfig, pcConstraints); }; window.RTCPeerConnection.prototype = mozRTCPeerConnection.prototype; // wrap static methods. Currently just generateCertificate. if (mozRTCPeerConnection.generateCertificate) { Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', { get: function() { return mozRTCPeerConnection.generateCertificate; } }); } window.RTCSessionDescription = mozRTCSessionDescription; window.RTCIceCandidate = mozRTCIceCandidate; } // shim away need for obsolete RTCIceCandidate/RTCSessionDescription. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'] .forEach(function(method) { var nativeMethod = RTCPeerConnection.prototype[method]; RTCPeerConnection.prototype[method] = function() { arguments[0] = new ((method === 'addIceCandidate') ? RTCIceCandidate : RTCSessionDescription)(arguments[0]); return nativeMethod.apply(this, arguments); }; }); // support for addIceCandidate(null or undefined) var nativeAddIceCandidate = RTCPeerConnection.prototype.addIceCandidate; RTCPeerConnection.prototype.addIceCandidate = function() { if (!arguments[0]) { if (arguments[1]) { arguments[1].apply(null); } return Promise.resolve(); } return nativeAddIceCandidate.apply(this, arguments); }; // shim getStats with maplike support var makeMapStats = function(stats) { var map = new Map(); Object.keys(stats).forEach(function(key) { map.set(key, stats[key]); map[key] = stats[key]; }); return map; }; var modernStatsTypes = { inboundrtp: 'inbound-rtp', outboundrtp: 'outbound-rtp', candidatepair: 'candidate-pair', localcandidate: 'local-candidate', remotecandidate: 'remote-candidate' }; var nativeGetStats = RTCPeerConnection.prototype.getStats; RTCPeerConnection.prototype.getStats = function(selector, onSucc, onErr) { return nativeGetStats.apply(this, [selector || null]) .then(function(stats) { if (browserDetails.version < 48) { stats = makeMapStats(stats); } if (browserDetails.version < 53 && !onSucc) { // Shim only promise getStats with spec-hyphens in type names // Leave callback version alone; misc old uses of forEach before Map stats.forEach(function(stat) { stat.type = modernStatsTypes[stat.type] || stat.type; }); } return stats; }) .then(onSucc, onErr); }; } }; // Expose public methods. module.exports = { shimOnTrack: firefoxShim.shimOnTrack, shimSourceObject: firefoxShim.shimSourceObject, shimPeerConnection: firefoxShim.shimPeerConnection, shimGetUserMedia: require('./getusermedia') }; },{"../utils":10,"./getusermedia":8}],8:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var logging = require('../utils').log; var browserDetails = require('../utils').browserDetails; // Expose public methods. module.exports = function() { var shimError_ = function(e) { return { name: { SecurityError: 'NotAllowedError', PermissionDeniedError: 'NotAllowedError' }[e.name] || e.name, message: { 'The operation is insecure.': 'The request is not allowed by the ' + 'user agent or the platform in the current context.' }[e.message] || e.message, constraint: e.constraint, toString: function() { return this.name + (this.message && ': ') + this.message; } }; }; // getUserMedia constraints shim. var getUserMedia_ = function(constraints, onSuccess, onError) { var constraintsToFF37_ = function(c) { if (typeof c !== 'object' || c.require) { return c; } var require = []; Object.keys(c).forEach(function(key) { if (key === 'require' || key === 'advanced' || key === 'mediaSource') { return; } var r = c[key] = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]}; if (r.min !== undefined || r.max !== undefined || r.exact !== undefined) { require.push(key); } if (r.exact !== undefined) { if (typeof r.exact === 'number') { r. min = r.max = r.exact; } else { c[key] = r.exact; } delete r.exact; } if (r.ideal !== undefined) { c.advanced = c.advanced || []; var oc = {}; if (typeof r.ideal === 'number') { oc[key] = {min: r.ideal, max: r.ideal}; } else { oc[key] = r.ideal; } c.advanced.push(oc); delete r.ideal; if (!Object.keys(r).length) { delete c[key]; } } }); if (require.length) { c.require = require; } return c; }; constraints = JSON.parse(JSON.stringify(constraints)); if (browserDetails.version < 38) { logging('spec: ' + JSON.stringify(constraints)); if (constraints.audio) { constraints.audio = constraintsToFF37_(constraints.audio); } if (constraints.video) { constraints.video = constraintsToFF37_(constraints.video); } logging('ff37: ' + JSON.stringify(constraints)); } return navigator.mozGetUserMedia(constraints, onSuccess, function(e) { onError(shimError_(e)); }); }; // Returns the result of getUserMedia as a Promise. var getUserMediaPromise_ = function(constraints) { return new Promise(function(resolve, reject) { getUserMedia_(constraints, resolve, reject); }); }; // Shim for mediaDevices on older versions. if (!navigator.mediaDevices) { navigator.mediaDevices = {getUserMedia: getUserMediaPromise_, addEventListener: function() { }, removeEventListener: function() { } }; } navigator.mediaDevices.enumerateDevices = navigator.mediaDevices.enumerateDevices || function() { return new Promise(function(resolve) { var infos = [ {kind: 'audioinput', deviceId: 'default', label: '', groupId: ''}, {kind: 'videoinput', deviceId: 'default', label: '', groupId: ''} ]; resolve(infos); }); }; if (browserDetails.version < 41) { // Work around http://bugzil.la/1169665 var orgEnumerateDevices = navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices); navigator.mediaDevices.enumerateDevices = function() { return orgEnumerateDevices().then(undefined, function(e) { if (e.name === 'NotFoundError') { return []; } throw e; }); }; } if (browserDetails.version < 49) { var origGetUserMedia = navigator.mediaDevices.getUserMedia. bind(navigator.mediaDevices); navigator.mediaDevices.getUserMedia = function(c) { return origGetUserMedia(c).then(function(stream) { // Work around https://bugzil.la/802326 if (c.audio && !stream.getAudioTracks().length || c.video && !stream.getVideoTracks().length) { stream.getTracks().forEach(function(track) { track.stop(); }); throw new DOMException('The object can not be found here.', 'NotFoundError'); } return stream; }, function(e) { return Promise.reject(shimError_(e)); }); }; } navigator.getUserMedia = function(constraints, onSuccess, onError) { if (browserDetails.version < 44) { return getUserMedia_(constraints, onSuccess, onError); } // Replace Firefox 44+'s deprecation warning with unprefixed version. console.warn('navigator.getUserMedia has been replaced by ' + 'navigator.mediaDevices.getUserMedia'); navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError); }; }; },{"../utils":10}],9:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ 'use strict'; var safariShim = { // TODO: DrAlex, should be here, double check against LayoutTests // shimOnTrack: function() { }, // TODO: once the back-end for the mac port is done, add. // TODO: check for webkitGTK+ // shimPeerConnection: function() { }, shimGetUserMedia: function() { navigator.getUserMedia = navigator.webkitGetUserMedia; } }; // Expose public methods. module.exports = { shimGetUserMedia: safariShim.shimGetUserMedia // TODO // shimOnTrack: safariShim.shimOnTrack, // shimPeerConnection: safariShim.shimPeerConnection }; },{}],10:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var logDisabled_ = true; // Utility methods. var utils = { disableLog: function(bool) { if (typeof bool !== 'boolean') { return new Error('Argument type: ' + typeof bool + '. Please use a boolean.'); } logDisabled_ = bool; return (bool) ? 'adapter.js logging disabled' : 'adapter.js logging enabled'; }, log: function() { if (typeof window === 'object') { if (logDisabled_) { return; } if (typeof console !== 'undefined' && typeof console.log === 'function') { console.log.apply(console, arguments); } } }, /** * Extract browser version out of the provided user agent string. * * @param {!string} uastring userAgent string. * @param {!string} expr Regular expression used as match criteria. * @param {!number} pos position in the version string to be returned. * @return {!number} browser version. */ extractVersion: function(uastring, expr, pos) { var match = uastring.match(expr); return match && match.length >= pos && parseInt(match[pos], 10); }, /** * Browser detector. * * @return {object} result containing browser and version * properties. */ detectBrowser: function() { // Returned result object. var result = {}; result.browser = null; result.version = null; // Fail early if it's not a browser if (typeof window === 'undefined' || !window.navigator) { result.browser = 'Not a browser.'; return result; } // Firefox. if (navigator.mozGetUserMedia) { result.browser = 'firefox'; result.version = this.extractVersion(navigator.userAgent, /Firefox\/([0-9]+)\./, 1); // all webkit-based browsers } else if (navigator.webkitGetUserMedia) { // Chrome, Chromium, Webview, Opera, all use the chrome shim for now if (window.webkitRTCPeerConnection) { result.browser = 'chrome'; result.version = this.extractVersion(navigator.userAgent, /Chrom(e|ium)\/([0-9]+)\./, 2); // Safari or unknown webkit-based // for the time being Safari has support for MediaStreams but not webRTC } else { // Safari UA substrings of interest for reference: // - webkit version: AppleWebKit/602.1.25 (also used in Op,Cr) // - safari UI version: Version/9.0.3 (unique to Safari) // - safari UI webkit version: Safari/601.4.4 (also used in Op,Cr) // // if the webkit version and safari UI webkit versions are equals, // ... this is a stable version. // // only the internal webkit version is important today to know if // media streams are supported // if (navigator.userAgent.match(/Version\/(\d+).(\d+)/)) { result.browser = 'safari'; result.version = this.extractVersion(navigator.userAgent, /AppleWebKit\/([0-9]+)\./, 1); // unknown webkit-based browser } else { result.browser = 'Unsupported webkit-based browser ' + 'with GUM support but no WebRTC support.'; return result; } } // Edge. } else if (navigator.mediaDevices && navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) { result.browser = 'edge'; result.version = this.extractVersion(navigator.userAgent, /Edge\/(\d+).(\d+)$/, 2); // Default fallthrough: not supported. } else { result.browser = 'Not a supported browser.'; return result; } return result; }, shimCreateObjectURL: function() { var nativeCreateObjectURL = URL.createObjectURL.bind(URL); var nativeRevokeObjectURL = URL.revokeObjectURL.bind(URL); var streams = new Map(), newId = 0; URL.createObjectURL = function(stream) { if ('getTracks' in stream) { var url = 'polyblob:' + (++newId); streams.set(url, stream); console.log('URL.createObjectURL(stream) is deprecated! ' + 'Use elem.srcObject = stream instead!'); return url; } return nativeCreateObjectURL(stream); }; URL.revokeObjectURL = function(url) { nativeRevokeObjectURL(url); streams.delete(url); }; var dsc = Object.getOwnPropertyDescriptor(window.HTMLMediaElement.prototype, 'src'); Object.defineProperty(window.HTMLMediaElement.prototype, 'src', { get: function() { return dsc.get.apply(this); }, set: function(url) { this.srcObject = streams.get(url) || null; return dsc.set.apply(this, [url]); } }); } }; // Export. module.exports = { log: utils.log, disableLog: utils.disableLog, browserDetails: utils.detectBrowser(), extractVersion: utils.extractVersion, shimCreateObjectURL: utils.shimCreateObjectURL }; },{}]},{},[2])(2) });
/*! * FileInput Hungarian Translations * * This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or * any HTML markup tags in the messages must not be converted or translated. * * @see http://github.com/kartik-v/bootstrap-fileinput * * NOTE: this file must be saved in UTF-8 encoding. */ (function ($) { "use strict"; $.fn.fileinputLocales['hu'] = { fileSingle: 'fájl', filePlural: 'fájlok', browseLabel: 'Tallóz &hellip;', removeLabel: 'Eltávolít', removeTitle: 'Kijelölt fájlok törlése', cancelLabel: 'Mégse', cancelTitle: 'Feltöltés megszakítása', uploadLabel: 'Feltöltés', uploadTitle: 'Kijelölt fájlok feltöltése', msgNo: 'Nem', msgNoFilesSelected: 'Nincs fájl kiválasztva', msgCancelled: 'Megszakítva', msgZoomModalHeading: 'Részletes Előnézet', msgFileRequired: 'Kötelező fájlt kiválasztani a feltöltéshez.', msgSizeTooSmall: 'A fájl: "{name}" (<b>{size} KB</b>) mérete túl kicsi, nagyobbnak kell lennie, mint <b>{minSize} KB</b>.', msgSizeTooLarge: '"{name}" fájl (<b>{size} KB</b>) mérete nagyobb a megengedettnél <b>{maxSize} KB</b>.', msgFilesTooLess: 'Legalább <b>{n}</b> {files} ki kell választania a feltöltéshez.', msgFilesTooMany: 'A feltölteni kívánt fájlok száma <b>({n})</b> elérte a megengedett maximumot <b>{m}</b>.', msgFileNotFound: '"{name}" fájl nem található!', msgFileSecured: 'Biztonsági beállítások nem engedik olvasni a fájlt "{name}".', msgFileNotReadable: '"{name}" fájl nem olvasható.', msgFilePreviewAborted: '"{name}" fájl feltöltése megszakítva.', msgFilePreviewError: 'Hiba lépett fel a "{name}" fájl olvasása közben.', msgInvalidFileName: 'Hibás vagy nem támogatott karakterek a fájl nevében "{name}".', msgInvalidFileType: 'Nem megengedett fájl "{name}". Csak a "{types}" fájl típusok támogatottak.', msgInvalidFileExtension: 'Nem megengedett kiterjesztés / fájltípus "{name}". Csak a "{extensions}" kiterjesztés(ek) / fájltípus(ok) támogatottak.', msgFileTypes: { 'image': 'image', 'html': 'HTML', 'text': 'text', 'video': 'video', 'audio': 'audio', 'flash': 'flash', 'pdf': 'PDF', 'object': 'object' }, msgUploadAborted: 'A fájl feltöltés megszakítva', msgUploadThreshold: 'Folyamatban...', msgUploadBegin: 'Inicializálás...', msgUploadEnd: 'Kész', msgUploadEmpty: 'Nincs érvényes adat a feltöltéshez.', msgUploadError: 'Error', msgValidationError: 'Érvényesítés hiba', msgLoading: '{index} / {files} töltése &hellip;', msgProgress: 'Feltöltés: {index} / {files} - {name} - {percent}% kész.', msgSelected: '{n} {files} kiválasztva.', msgFoldersNotAllowed: 'Csak fájlokat húzzon ide! Kihagyva {n} könyvtár.', msgImageWidthSmall: 'A kép szélességének "{name}" legalább {size} pixelnek kell lennie.', msgImageHeightSmall: 'A kép magasságának "{name}" legalább {size} pixelnek kell lennie.', msgImageWidthLarge: 'A kép szélessége "{name}" nem haladhatja meg a {size} pixelt.', msgImageHeightLarge: 'A kép magassága "{name}" nem haladhatja meg a {size} pixelt.', msgImageResizeError: 'Nem lehet megállapítani a kép méreteit az átméretezéshez.', msgImageResizeException: 'Hiba történt a méretezés közben.<pre>{errors}</pre>', msgAjaxError: 'Hiba történt a művelet közben ({operation}). Kérjük, próbálja később!', msgAjaxProgressError: 'Hiba! ({operation})', ajaxOperations: { deleteThumb: 'fájl törlés', uploadThumb: 'fájl feltöltés', uploadBatch: 'csoportos fájl feltöltés', uploadExtra: 'űrlap adat feltöltés' }, dropZoneTitle: 'Húzzon ide fájlokat &hellip;', dropZoneClickTitle: '<br>(vagy kattintson ide a {files} tallózásához...)', fileActionSettings: { removeTitle: 'A fájl eltávolítása', uploadTitle: 'fájl feltöltése', uploadRetryTitle: 'Retry upload', downloadTitle: 'Download file', zoomTitle: 'Részletek megtekintése', dragTitle: 'Mozgatás / Átrendezés', indicatorNewTitle: 'Nem feltöltött', indicatorSuccessTitle: 'Feltöltött', indicatorErrorTitle: 'Feltöltés hiba', indicatorLoadingTitle: 'Feltöltés ...' }, previewZoomButtonTitles: { prev: 'Elöző fájl megnézése', next: 'Következő fájl megnézése', toggleheader: 'Fejléc mutatása', fullscreen: 'Teljes képernyős mód bekapcsolása', borderless: 'Keret nélküli ablak mód bekapcsolása', close: 'Részletes előnézet bezárása' } }; })(window.jQuery);
var searchData= [ ['nome',['Nome',['../class_nome.html',1,'']]] ];
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "a.\u00a0m.", "p.\u00a0m." ], "DAY": [ "domingo", "lunes", "martes", "mi\u00e9rcoles", "jueves", "viernes", "s\u00e1bado" ], "FIRSTDAYOFWEEK": 6, "MONTH": [ "enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "setiembre", "octubre", "noviembre", "diciembre" ], "SHORTDAY": [ "dom.", "lun.", "mar.", "mi\u00e9.", "jue.", "vie.", "s\u00e1b." ], "SHORTMONTH": [ "ene.", "feb.", "mar.", "abr.", "may.", "jun.", "jul.", "ago.", "set.", "oct.", "nov.", "dic." ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d 'de' MMMM 'de' y", "longDate": "d 'de' MMMM 'de' y", "medium": "d 'de' MMM 'de' y h:mm:ss a", "mediumDate": "d 'de' MMM 'de' 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": "es-do", "pluralCat": function(n, opt_precision) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
export {default as ActionAccessibility} from './action/accessibility'; export {default as ActionAccessible} from './action/accessible'; export {default as ActionAccountBalanceWallet} from './action/account-balance-wallet'; export {default as ActionAccountBalance} from './action/account-balance'; export {default as ActionAccountBox} from './action/account-box'; export {default as ActionAccountCircle} from './action/account-circle'; export {default as ActionAddShoppingCart} from './action/add-shopping-cart'; export {default as ActionAlarmAdd} from './action/alarm-add'; export {default as ActionAlarmOff} from './action/alarm-off'; export {default as ActionAlarmOn} from './action/alarm-on'; export {default as ActionAlarm} from './action/alarm'; export {default as ActionAllOut} from './action/all-out'; export {default as ActionAndroid} from './action/android'; export {default as ActionAnnouncement} from './action/announcement'; export {default as ActionAspectRatio} from './action/aspect-ratio'; export {default as ActionAssessment} from './action/assessment'; export {default as ActionAssignmentInd} from './action/assignment-ind'; export {default as ActionAssignmentLate} from './action/assignment-late'; export {default as ActionAssignmentReturn} from './action/assignment-return'; export {default as ActionAssignmentReturned} from './action/assignment-returned'; export {default as ActionAssignmentTurnedIn} from './action/assignment-turned-in'; export {default as ActionAssignment} from './action/assignment'; export {default as ActionAutorenew} from './action/autorenew'; export {default as ActionBackup} from './action/backup'; export {default as ActionBook} from './action/book'; export {default as ActionBookmarkBorder} from './action/bookmark-border'; export {default as ActionBookmark} from './action/bookmark'; export {default as ActionBugReport} from './action/bug-report'; export {default as ActionBuild} from './action/build'; export {default as ActionCached} from './action/cached'; export {default as ActionCameraEnhance} from './action/camera-enhance'; export {default as ActionCardGiftcard} from './action/card-giftcard'; export {default as ActionCardMembership} from './action/card-membership'; export {default as ActionCardTravel} from './action/card-travel'; export {default as ActionChangeHistory} from './action/change-history'; export {default as ActionCheckCircle} from './action/check-circle'; export {default as ActionChromeReaderMode} from './action/chrome-reader-mode'; export {default as ActionClass} from './action/class'; export {default as ActionCode} from './action/code'; export {default as ActionCompareArrows} from './action/compare-arrows'; export {default as ActionCopyright} from './action/copyright'; export {default as ActionCreditCard} from './action/credit-card'; export {default as ActionDashboard} from './action/dashboard'; export {default as ActionDateRange} from './action/date-range'; export {default as ActionDelete} from './action/delete'; export {default as ActionDescription} from './action/description'; export {default as ActionDns} from './action/dns'; export {default as ActionDoneAll} from './action/done-all'; export {default as ActionDone} from './action/done'; export {default as ActionDonutLarge} from './action/donut-large'; export {default as ActionDonutSmall} from './action/donut-small'; export {default as ActionEject} from './action/eject'; export {default as ActionEventSeat} from './action/event-seat'; export {default as ActionEvent} from './action/event'; export {default as ActionExitToApp} from './action/exit-to-app'; export {default as ActionExplore} from './action/explore'; export {default as ActionExtension} from './action/extension'; export {default as ActionFace} from './action/face'; export {default as ActionFavoriteBorder} from './action/favorite-border'; export {default as ActionFavorite} from './action/favorite'; export {default as ActionFeedback} from './action/feedback'; export {default as ActionFindInPage} from './action/find-in-page'; export {default as ActionFindReplace} from './action/find-replace'; export {default as ActionFingerprint} from './action/fingerprint'; export {default as ActionFlightLand} from './action/flight-land'; export {default as ActionFlightTakeoff} from './action/flight-takeoff'; export {default as ActionFlipToBack} from './action/flip-to-back'; export {default as ActionFlipToFront} from './action/flip-to-front'; export {default as ActionGavel} from './action/gavel'; export {default as ActionGetApp} from './action/get-app'; export {default as ActionGif} from './action/gif'; export {default as ActionGrade} from './action/grade'; export {default as ActionGroupWork} from './action/group-work'; export {default as ActionHelpOutline} from './action/help-outline'; export {default as ActionHelp} from './action/help'; export {default as ActionHighlightOff} from './action/highlight-off'; export {default as ActionHistory} from './action/history'; export {default as ActionHome} from './action/home'; export {default as ActionHourglassEmpty} from './action/hourglass-empty'; export {default as ActionHourglassFull} from './action/hourglass-full'; export {default as ActionHttp} from './action/http'; export {default as ActionHttps} from './action/https'; export {default as ActionImportantDevices} from './action/important-devices'; export {default as ActionInfoOutline} from './action/info-outline'; export {default as ActionInfo} from './action/info'; export {default as ActionInput} from './action/input'; export {default as ActionInvertColors} from './action/invert-colors'; export {default as ActionLabelOutline} from './action/label-outline'; export {default as ActionLabel} from './action/label'; export {default as ActionLanguage} from './action/language'; export {default as ActionLaunch} from './action/launch'; export {default as ActionLightbulbOutline} from './action/lightbulb-outline'; export {default as ActionLineStyle} from './action/line-style'; export {default as ActionLineWeight} from './action/line-weight'; export {default as ActionList} from './action/list'; export {default as ActionLockOpen} from './action/lock-open'; export {default as ActionLockOutline} from './action/lock-outline'; export {default as ActionLock} from './action/lock'; export {default as ActionLoyalty} from './action/loyalty'; export {default as ActionMarkunreadMailbox} from './action/markunread-mailbox'; export {default as ActionMotorcycle} from './action/motorcycle'; export {default as ActionNoteAdd} from './action/note-add'; export {default as ActionOfflinePin} from './action/offline-pin'; export {default as ActionOpacity} from './action/opacity'; export {default as ActionOpenInBrowser} from './action/open-in-browser'; export {default as ActionOpenInNew} from './action/open-in-new'; export {default as ActionOpenWith} from './action/open-with'; export {default as ActionPageview} from './action/pageview'; export {default as ActionPanTool} from './action/pan-tool'; export {default as ActionPayment} from './action/payment'; export {default as ActionPermCameraMic} from './action/perm-camera-mic'; export {default as ActionPermContactCalendar} from './action/perm-contact-calendar'; export {default as ActionPermDataSetting} from './action/perm-data-setting'; export {default as ActionPermDeviceInformation} from './action/perm-device-information'; export {default as ActionPermIdentity} from './action/perm-identity'; export {default as ActionPermMedia} from './action/perm-media'; export {default as ActionPermPhoneMsg} from './action/perm-phone-msg'; export {default as ActionPermScanWifi} from './action/perm-scan-wifi'; export {default as ActionPets} from './action/pets'; export {default as ActionPictureInPictureAlt} from './action/picture-in-picture-alt'; export {default as ActionPictureInPicture} from './action/picture-in-picture'; export {default as ActionPlayForWork} from './action/play-for-work'; export {default as ActionPolymer} from './action/polymer'; export {default as ActionPowerSettingsNew} from './action/power-settings-new'; export {default as ActionPregnantWoman} from './action/pregnant-woman'; export {default as ActionPrint} from './action/print'; export {default as ActionQueryBuilder} from './action/query-builder'; export {default as ActionQuestionAnswer} from './action/question-answer'; export {default as ActionReceipt} from './action/receipt'; export {default as ActionRecordVoiceOver} from './action/record-voice-over'; export {default as ActionRedeem} from './action/redeem'; export {default as ActionReorder} from './action/reorder'; export {default as ActionReportProblem} from './action/report-problem'; export {default as ActionRestore} from './action/restore'; export {default as ActionRoom} from './action/room'; export {default as ActionRoundedCorner} from './action/rounded-corner'; export {default as ActionRowing} from './action/rowing'; export {default as ActionSchedule} from './action/schedule'; export {default as ActionSearch} from './action/search'; export {default as ActionSettingsApplications} from './action/settings-applications'; export {default as ActionSettingsBackupRestore} from './action/settings-backup-restore'; export {default as ActionSettingsBluetooth} from './action/settings-bluetooth'; export {default as ActionSettingsBrightness} from './action/settings-brightness'; export {default as ActionSettingsCell} from './action/settings-cell'; export {default as ActionSettingsEthernet} from './action/settings-ethernet'; export {default as ActionSettingsInputAntenna} from './action/settings-input-antenna'; export {default as ActionSettingsInputComponent} from './action/settings-input-component'; export {default as ActionSettingsInputComposite} from './action/settings-input-composite'; export {default as ActionSettingsInputHdmi} from './action/settings-input-hdmi'; export {default as ActionSettingsInputSvideo} from './action/settings-input-svideo'; export {default as ActionSettingsOverscan} from './action/settings-overscan'; export {default as ActionSettingsPhone} from './action/settings-phone'; export {default as ActionSettingsPower} from './action/settings-power'; export {default as ActionSettingsRemote} from './action/settings-remote'; export {default as ActionSettingsVoice} from './action/settings-voice'; export {default as ActionSettings} from './action/settings'; export {default as ActionShopTwo} from './action/shop-two'; export {default as ActionShop} from './action/shop'; export {default as ActionShoppingBasket} from './action/shopping-basket'; export {default as ActionShoppingCart} from './action/shopping-cart'; export {default as ActionSpeakerNotes} from './action/speaker-notes'; export {default as ActionSpellcheck} from './action/spellcheck'; export {default as ActionStars} from './action/stars'; export {default as ActionStore} from './action/store'; export {default as ActionSubject} from './action/subject'; export {default as ActionSupervisorAccount} from './action/supervisor-account'; export {default as ActionSwapHoriz} from './action/swap-horiz'; export {default as ActionSwapVert} from './action/swap-vert'; export {default as ActionSwapVerticalCircle} from './action/swap-vertical-circle'; export {default as ActionSystemUpdateAlt} from './action/system-update-alt'; export {default as ActionTabUnselected} from './action/tab-unselected'; export {default as ActionTab} from './action/tab'; export {default as ActionTheaters} from './action/theaters'; export {default as ActionThreeDRotation} from './action/three-d-rotation'; export {default as ActionThumbDown} from './action/thumb-down'; export {default as ActionThumbUp} from './action/thumb-up'; export {default as ActionThumbsUpDown} from './action/thumbs-up-down'; export {default as ActionTimeline} from './action/timeline'; export {default as ActionToc} from './action/toc'; export {default as ActionToday} from './action/today'; export {default as ActionToll} from './action/toll'; export {default as ActionTouchApp} from './action/touch-app'; export {default as ActionTrackChanges} from './action/track-changes'; export {default as ActionTranslate} from './action/translate'; export {default as ActionTrendingDown} from './action/trending-down'; export {default as ActionTrendingFlat} from './action/trending-flat'; export {default as ActionTrendingUp} from './action/trending-up'; export {default as ActionTurnedInNot} from './action/turned-in-not'; export {default as ActionTurnedIn} from './action/turned-in'; export {default as ActionUpdate} from './action/update'; export {default as ActionVerifiedUser} from './action/verified-user'; export {default as ActionViewAgenda} from './action/view-agenda'; export {default as ActionViewArray} from './action/view-array'; export {default as ActionViewCarousel} from './action/view-carousel'; export {default as ActionViewColumn} from './action/view-column'; export {default as ActionViewDay} from './action/view-day'; export {default as ActionViewHeadline} from './action/view-headline'; export {default as ActionViewList} from './action/view-list'; export {default as ActionViewModule} from './action/view-module'; export {default as ActionViewQuilt} from './action/view-quilt'; export {default as ActionViewStream} from './action/view-stream'; export {default as ActionViewWeek} from './action/view-week'; export {default as ActionVisibilityOff} from './action/visibility-off'; export {default as ActionVisibility} from './action/visibility'; export {default as ActionWatchLater} from './action/watch-later'; export {default as ActionWork} from './action/work'; export {default as ActionYoutubeSearchedFor} from './action/youtube-searched-for'; export {default as ActionZoomIn} from './action/zoom-in'; export {default as ActionZoomOut} from './action/zoom-out'; export {default as AlertAddAlert} from './alert/add-alert'; export {default as AlertErrorOutline} from './alert/error-outline'; export {default as AlertError} from './alert/error'; export {default as AlertWarning} from './alert/warning'; export {default as AvAddToQueue} from './av/add-to-queue'; export {default as AvAirplay} from './av/airplay'; export {default as AvAlbum} from './av/album'; export {default as AvArtTrack} from './av/art-track'; export {default as AvAvTimer} from './av/av-timer'; export {default as AvClosedCaption} from './av/closed-caption'; export {default as AvEqualizer} from './av/equalizer'; export {default as AvExplicit} from './av/explicit'; export {default as AvFastForward} from './av/fast-forward'; export {default as AvFastRewind} from './av/fast-rewind'; export {default as AvFiberDvr} from './av/fiber-dvr'; export {default as AvFiberManualRecord} from './av/fiber-manual-record'; export {default as AvFiberNew} from './av/fiber-new'; export {default as AvFiberPin} from './av/fiber-pin'; export {default as AvFiberSmartRecord} from './av/fiber-smart-record'; export {default as AvForward10} from './av/forward-10'; export {default as AvForward30} from './av/forward-30'; export {default as AvForward5} from './av/forward-5'; export {default as AvGames} from './av/games'; export {default as AvHd} from './av/hd'; export {default as AvHearing} from './av/hearing'; export {default as AvHighQuality} from './av/high-quality'; export {default as AvLibraryAdd} from './av/library-add'; export {default as AvLibraryBooks} from './av/library-books'; export {default as AvLibraryMusic} from './av/library-music'; export {default as AvLoop} from './av/loop'; export {default as AvMicNone} from './av/mic-none'; export {default as AvMicOff} from './av/mic-off'; export {default as AvMic} from './av/mic'; export {default as AvMovie} from './av/movie'; export {default as AvMusicVideo} from './av/music-video'; export {default as AvNewReleases} from './av/new-releases'; export {default as AvNotInterested} from './av/not-interested'; export {default as AvPauseCircleFilled} from './av/pause-circle-filled'; export {default as AvPauseCircleOutline} from './av/pause-circle-outline'; export {default as AvPause} from './av/pause'; export {default as AvPlayArrow} from './av/play-arrow'; export {default as AvPlayCircleFilled} from './av/play-circle-filled'; export {default as AvPlayCircleOutline} from './av/play-circle-outline'; export {default as AvPlaylistAddCheck} from './av/playlist-add-check'; export {default as AvPlaylistAdd} from './av/playlist-add'; export {default as AvPlaylistPlay} from './av/playlist-play'; export {default as AvQueueMusic} from './av/queue-music'; export {default as AvQueuePlayNext} from './av/queue-play-next'; export {default as AvQueue} from './av/queue'; export {default as AvRadio} from './av/radio'; export {default as AvRecentActors} from './av/recent-actors'; export {default as AvRemoveFromQueue} from './av/remove-from-queue'; export {default as AvRepeatOne} from './av/repeat-one'; export {default as AvRepeat} from './av/repeat'; export {default as AvReplay10} from './av/replay-10'; export {default as AvReplay30} from './av/replay-30'; export {default as AvReplay5} from './av/replay-5'; export {default as AvReplay} from './av/replay'; export {default as AvShuffle} from './av/shuffle'; export {default as AvSkipNext} from './av/skip-next'; export {default as AvSkipPrevious} from './av/skip-previous'; export {default as AvSlowMotionVideo} from './av/slow-motion-video'; export {default as AvSnooze} from './av/snooze'; export {default as AvSortByAlpha} from './av/sort-by-alpha'; export {default as AvStop} from './av/stop'; export {default as AvSubscriptions} from './av/subscriptions'; export {default as AvSubtitles} from './av/subtitles'; export {default as AvSurroundSound} from './av/surround-sound'; export {default as AvVideoLibrary} from './av/video-library'; export {default as AvVideocamOff} from './av/videocam-off'; export {default as AvVideocam} from './av/videocam'; export {default as AvVolumeDown} from './av/volume-down'; export {default as AvVolumeMute} from './av/volume-mute'; export {default as AvVolumeOff} from './av/volume-off'; export {default as AvVolumeUp} from './av/volume-up'; export {default as AvWebAsset} from './av/web-asset'; export {default as AvWeb} from './av/web'; export {default as CommunicationBusiness} from './communication/business'; export {default as CommunicationCallEnd} from './communication/call-end'; export {default as CommunicationCallMade} from './communication/call-made'; export {default as CommunicationCallMerge} from './communication/call-merge'; export {default as CommunicationCallMissedOutgoing} from './communication/call-missed-outgoing'; export {default as CommunicationCallMissed} from './communication/call-missed'; export {default as CommunicationCallReceived} from './communication/call-received'; export {default as CommunicationCallSplit} from './communication/call-split'; export {default as CommunicationCall} from './communication/call'; export {default as CommunicationChatBubbleOutline} from './communication/chat-bubble-outline'; export {default as CommunicationChatBubble} from './communication/chat-bubble'; export {default as CommunicationChat} from './communication/chat'; export {default as CommunicationClearAll} from './communication/clear-all'; export {default as CommunicationComment} from './communication/comment'; export {default as CommunicationContactMail} from './communication/contact-mail'; export {default as CommunicationContactPhone} from './communication/contact-phone'; export {default as CommunicationContacts} from './communication/contacts'; export {default as CommunicationDialerSip} from './communication/dialer-sip'; export {default as CommunicationDialpad} from './communication/dialpad'; export {default as CommunicationEmail} from './communication/email'; export {default as CommunicationForum} from './communication/forum'; export {default as CommunicationImportContacts} from './communication/import-contacts'; export {default as CommunicationImportExport} from './communication/import-export'; export {default as CommunicationInvertColorsOff} from './communication/invert-colors-off'; export {default as CommunicationLiveHelp} from './communication/live-help'; export {default as CommunicationLocationOff} from './communication/location-off'; export {default as CommunicationLocationOn} from './communication/location-on'; export {default as CommunicationMailOutline} from './communication/mail-outline'; export {default as CommunicationMessage} from './communication/message'; export {default as CommunicationNoSim} from './communication/no-sim'; export {default as CommunicationPhone} from './communication/phone'; export {default as CommunicationPhonelinkErase} from './communication/phonelink-erase'; export {default as CommunicationPhonelinkLock} from './communication/phonelink-lock'; export {default as CommunicationPhonelinkRing} from './communication/phonelink-ring'; export {default as CommunicationPhonelinkSetup} from './communication/phonelink-setup'; export {default as CommunicationPortableWifiOff} from './communication/portable-wifi-off'; export {default as CommunicationPresentToAll} from './communication/present-to-all'; export {default as CommunicationRingVolume} from './communication/ring-volume'; export {default as CommunicationScreenShare} from './communication/screen-share'; export {default as CommunicationSpeakerPhone} from './communication/speaker-phone'; export {default as CommunicationStayCurrentLandscape} from './communication/stay-current-landscape'; export {default as CommunicationStayCurrentPortrait} from './communication/stay-current-portrait'; export {default as CommunicationStayPrimaryLandscape} from './communication/stay-primary-landscape'; export {default as CommunicationStayPrimaryPortrait} from './communication/stay-primary-portrait'; export {default as CommunicationStopScreenShare} from './communication/stop-screen-share'; export {default as CommunicationSwapCalls} from './communication/swap-calls'; export {default as CommunicationTactMail} from './communication/tact-mail'; export {default as CommunicationTextsms} from './communication/textsms'; export {default as CommunicationVoicemail} from './communication/voicemail'; export {default as CommunicationVpnKey} from './communication/vpn-key'; export {default as ContentAddBox} from './content/add-box'; export {default as ContentAddCircleOutline} from './content/add-circle-outline'; export {default as ContentAddCircle} from './content/add-circle'; export {default as ContentAdd} from './content/add'; export {default as ContentArchive} from './content/archive'; export {default as ContentBackspace} from './content/backspace'; export {default as ContentBlock} from './content/block'; export {default as ContentClear} from './content/clear'; export {default as ContentContentCopy} from './content/content-copy'; export {default as ContentContentCut} from './content/content-cut'; export {default as ContentContentPaste} from './content/content-paste'; export {default as ContentCreate} from './content/create'; export {default as ContentDrafts} from './content/drafts'; export {default as ContentFilterList} from './content/filter-list'; export {default as ContentFlag} from './content/flag'; export {default as ContentFontDownload} from './content/font-download'; export {default as ContentForward} from './content/forward'; export {default as ContentGesture} from './content/gesture'; export {default as ContentInbox} from './content/inbox'; export {default as ContentLink} from './content/link'; export {default as ContentMail} from './content/mail'; export {default as ContentMarkunread} from './content/markunread'; export {default as ContentMoveToInbox} from './content/move-to-inbox'; export {default as ContentNextWeek} from './content/next-week'; export {default as ContentRedo} from './content/redo'; export {default as ContentRemoveCircleOutline} from './content/remove-circle-outline'; export {default as ContentRemoveCircle} from './content/remove-circle'; export {default as ContentRemove} from './content/remove'; export {default as ContentReplyAll} from './content/reply-all'; export {default as ContentReply} from './content/reply'; export {default as ContentReport} from './content/report'; export {default as ContentSave} from './content/save'; export {default as ContentSelectAll} from './content/select-all'; export {default as ContentSend} from './content/send'; export {default as ContentSort} from './content/sort'; export {default as ContentTextFormat} from './content/text-format'; export {default as ContentUnarchive} from './content/unarchive'; export {default as ContentUndo} from './content/undo'; export {default as ContentWeekend} from './content/weekend'; export {default as DeviceAccessAlarm} from './device/access-alarm'; export {default as DeviceAccessAlarms} from './device/access-alarms'; export {default as DeviceAccessTime} from './device/access-time'; export {default as DeviceAddAlarm} from './device/add-alarm'; export {default as DeviceAirplanemodeActive} from './device/airplanemode-active'; export {default as DeviceAirplanemodeInactive} from './device/airplanemode-inactive'; export {default as DeviceBattery20} from './device/battery-20'; export {default as DeviceBattery30} from './device/battery-30'; export {default as DeviceBattery50} from './device/battery-50'; export {default as DeviceBattery60} from './device/battery-60'; export {default as DeviceBattery80} from './device/battery-80'; export {default as DeviceBattery90} from './device/battery-90'; export {default as DeviceBatteryAlert} from './device/battery-alert'; export {default as DeviceBatteryCharging20} from './device/battery-charging-20'; export {default as DeviceBatteryCharging30} from './device/battery-charging-30'; export {default as DeviceBatteryCharging50} from './device/battery-charging-50'; export {default as DeviceBatteryCharging60} from './device/battery-charging-60'; export {default as DeviceBatteryCharging80} from './device/battery-charging-80'; export {default as DeviceBatteryCharging90} from './device/battery-charging-90'; export {default as DeviceBatteryChargingFull} from './device/battery-charging-full'; export {default as DeviceBatteryFull} from './device/battery-full'; export {default as DeviceBatteryStd} from './device/battery-std'; export {default as DeviceBatteryUnknown} from './device/battery-unknown'; export {default as DeviceBluetoothConnected} from './device/bluetooth-connected'; export {default as DeviceBluetoothDisabled} from './device/bluetooth-disabled'; export {default as DeviceBluetoothSearching} from './device/bluetooth-searching'; export {default as DeviceBluetooth} from './device/bluetooth'; export {default as DeviceBrightnessAuto} from './device/brightness-auto'; export {default as DeviceBrightnessHigh} from './device/brightness-high'; export {default as DeviceBrightnessLow} from './device/brightness-low'; export {default as DeviceBrightnessMedium} from './device/brightness-medium'; export {default as DeviceDataUsage} from './device/data-usage'; export {default as DeviceDeveloperMode} from './device/developer-mode'; export {default as DeviceDevices} from './device/devices'; export {default as DeviceDvr} from './device/dvr'; export {default as DeviceGpsFixed} from './device/gps-fixed'; export {default as DeviceGpsNotFixed} from './device/gps-not-fixed'; export {default as DeviceGpsOff} from './device/gps-off'; export {default as DeviceGraphicEq} from './device/graphic-eq'; export {default as DeviceLocationDisabled} from './device/location-disabled'; export {default as DeviceLocationSearching} from './device/location-searching'; export {default as DeviceNetworkCell} from './device/network-cell'; export {default as DeviceNetworkWifi} from './device/network-wifi'; export {default as DeviceNfc} from './device/nfc'; export {default as DeviceScreenLockLandscape} from './device/screen-lock-landscape'; export {default as DeviceScreenLockPortrait} from './device/screen-lock-portrait'; export {default as DeviceScreenLockRotation} from './device/screen-lock-rotation'; export {default as DeviceScreenRotation} from './device/screen-rotation'; export {default as DeviceSdStorage} from './device/sd-storage'; export {default as DeviceSettingsSystemDaydream} from './device/settings-system-daydream'; export {default as DeviceSignalCellular0Bar} from './device/signal-cellular-0-bar'; export {default as DeviceSignalCellular1Bar} from './device/signal-cellular-1-bar'; export {default as DeviceSignalCellular2Bar} from './device/signal-cellular-2-bar'; export {default as DeviceSignalCellular3Bar} from './device/signal-cellular-3-bar'; export {default as DeviceSignalCellular4Bar} from './device/signal-cellular-4-bar'; export {default as DeviceSignalCellularConnectedNoInternet0Bar} from './device/signal-cellular-connected-no-internet-0-bar'; export {default as DeviceSignalCellularConnectedNoInternet1Bar} from './device/signal-cellular-connected-no-internet-1-bar'; export {default as DeviceSignalCellularConnectedNoInternet2Bar} from './device/signal-cellular-connected-no-internet-2-bar'; export {default as DeviceSignalCellularConnectedNoInternet3Bar} from './device/signal-cellular-connected-no-internet-3-bar'; export {default as DeviceSignalCellularConnectedNoInternet4Bar} from './device/signal-cellular-connected-no-internet-4-bar'; export {default as DeviceSignalCellularNoSim} from './device/signal-cellular-no-sim'; export {default as DeviceSignalCellularNull} from './device/signal-cellular-null'; export {default as DeviceSignalCellularOff} from './device/signal-cellular-off'; export {default as DeviceSignalWifi0Bar} from './device/signal-wifi-0-bar'; export {default as DeviceSignalWifi1BarLock} from './device/signal-wifi-1-bar-lock'; export {default as DeviceSignalWifi1Bar} from './device/signal-wifi-1-bar'; export {default as DeviceSignalWifi2BarLock} from './device/signal-wifi-2-bar-lock'; export {default as DeviceSignalWifi2Bar} from './device/signal-wifi-2-bar'; export {default as DeviceSignalWifi3BarLock} from './device/signal-wifi-3-bar-lock'; export {default as DeviceSignalWifi3Bar} from './device/signal-wifi-3-bar'; export {default as DeviceSignalWifi4BarLock} from './device/signal-wifi-4-bar-lock'; export {default as DeviceSignalWifi4Bar} from './device/signal-wifi-4-bar'; export {default as DeviceSignalWifiOff} from './device/signal-wifi-off'; export {default as DeviceStorage} from './device/storage'; export {default as DeviceUsb} from './device/usb'; export {default as DeviceWallpaper} from './device/wallpaper'; export {default as DeviceWidgets} from './device/widgets'; export {default as DeviceWifiLock} from './device/wifi-lock'; export {default as DeviceWifiTethering} from './device/wifi-tethering'; export {default as EditorAttachFile} from './editor/attach-file'; export {default as EditorAttachMoney} from './editor/attach-money'; export {default as EditorBorderAll} from './editor/border-all'; export {default as EditorBorderBottom} from './editor/border-bottom'; export {default as EditorBorderClear} from './editor/border-clear'; export {default as EditorBorderColor} from './editor/border-color'; export {default as EditorBorderHorizontal} from './editor/border-horizontal'; export {default as EditorBorderInner} from './editor/border-inner'; export {default as EditorBorderLeft} from './editor/border-left'; export {default as EditorBorderOuter} from './editor/border-outer'; export {default as EditorBorderRight} from './editor/border-right'; export {default as EditorBorderStyle} from './editor/border-style'; export {default as EditorBorderTop} from './editor/border-top'; export {default as EditorBorderVertical} from './editor/border-vertical'; export {default as EditorDragHandle} from './editor/drag-handle'; export {default as EditorFormatAlignCenter} from './editor/format-align-center'; export {default as EditorFormatAlignJustify} from './editor/format-align-justify'; export {default as EditorFormatAlignLeft} from './editor/format-align-left'; export {default as EditorFormatAlignRight} from './editor/format-align-right'; export {default as EditorFormatBold} from './editor/format-bold'; export {default as EditorFormatClear} from './editor/format-clear'; export {default as EditorFormatColorFill} from './editor/format-color-fill'; export {default as EditorFormatColorReset} from './editor/format-color-reset'; export {default as EditorFormatColorText} from './editor/format-color-text'; export {default as EditorFormatIndentDecrease} from './editor/format-indent-decrease'; export {default as EditorFormatIndentIncrease} from './editor/format-indent-increase'; export {default as EditorFormatItalic} from './editor/format-italic'; export {default as EditorFormatLineSpacing} from './editor/format-line-spacing'; export {default as EditorFormatListBulleted} from './editor/format-list-bulleted'; export {default as EditorFormatListNumbered} from './editor/format-list-numbered'; export {default as EditorFormatPaint} from './editor/format-paint'; export {default as EditorFormatQuote} from './editor/format-quote'; export {default as EditorFormatShapes} from './editor/format-shapes'; export {default as EditorFormatSize} from './editor/format-size'; export {default as EditorFormatStrikethrough} from './editor/format-strikethrough'; export {default as EditorFormatTextdirectionLToR} from './editor/format-textdirection-l-to-r'; export {default as EditorFormatTextdirectionRToL} from './editor/format-textdirection-r-to-l'; export {default as EditorFormatUnderlined} from './editor/format-underlined'; export {default as EditorFunctions} from './editor/functions'; export {default as EditorHighlight} from './editor/highlight'; export {default as EditorInsertChart} from './editor/insert-chart'; export {default as EditorInsertComment} from './editor/insert-comment'; export {default as EditorInsertDriveFile} from './editor/insert-drive-file'; export {default as EditorInsertEmoticon} from './editor/insert-emoticon'; export {default as EditorInsertInvitation} from './editor/insert-invitation'; export {default as EditorInsertLink} from './editor/insert-link'; export {default as EditorInsertPhoto} from './editor/insert-photo'; export {default as EditorLinearScale} from './editor/linear-scale'; export {default as EditorMergeType} from './editor/merge-type'; export {default as EditorModeComment} from './editor/mode-comment'; export {default as EditorModeEdit} from './editor/mode-edit'; export {default as EditorMoneyOff} from './editor/money-off'; export {default as EditorPublish} from './editor/publish'; export {default as EditorShortText} from './editor/short-text'; export {default as EditorSpaceBar} from './editor/space-bar'; export {default as EditorStrikethroughS} from './editor/strikethrough-s'; export {default as EditorTextFields} from './editor/text-fields'; export {default as EditorVerticalAlignBottom} from './editor/vertical-align-bottom'; export {default as EditorVerticalAlignCenter} from './editor/vertical-align-center'; export {default as EditorVerticalAlignTop} from './editor/vertical-align-top'; export {default as EditorWrapText} from './editor/wrap-text'; export {default as FileAttachment} from './file/attachment'; export {default as FileCloudCircle} from './file/cloud-circle'; export {default as FileCloudDone} from './file/cloud-done'; export {default as FileCloudDownload} from './file/cloud-download'; export {default as FileCloudOff} from './file/cloud-off'; export {default as FileCloudQueue} from './file/cloud-queue'; export {default as FileCloudUpload} from './file/cloud-upload'; export {default as FileCloud} from './file/cloud'; export {default as FileCreateNewFolder} from './file/create-new-folder'; export {default as FileFileDownload} from './file/file-download'; export {default as FileFileUpload} from './file/file-upload'; export {default as FileFolderOpen} from './file/folder-open'; export {default as FileFolderShared} from './file/folder-shared'; export {default as FileFolder} from './file/folder'; export {default as HardwareCastConnected} from './hardware/cast-connected'; export {default as HardwareCast} from './hardware/cast'; export {default as HardwareComputer} from './hardware/computer'; export {default as HardwareDesktopMac} from './hardware/desktop-mac'; export {default as HardwareDesktopWindows} from './hardware/desktop-windows'; export {default as HardwareDeveloperBoard} from './hardware/developer-board'; export {default as HardwareDeviceHub} from './hardware/device-hub'; export {default as HardwareDevicesOther} from './hardware/devices-other'; export {default as HardwareDock} from './hardware/dock'; export {default as HardwareGamepad} from './hardware/gamepad'; export {default as HardwareHeadsetMic} from './hardware/headset-mic'; export {default as HardwareHeadset} from './hardware/headset'; export {default as HardwareKeyboardArrowDown} from './hardware/keyboard-arrow-down'; export {default as HardwareKeyboardArrowLeft} from './hardware/keyboard-arrow-left'; export {default as HardwareKeyboardArrowRight} from './hardware/keyboard-arrow-right'; export {default as HardwareKeyboardArrowUp} from './hardware/keyboard-arrow-up'; export {default as HardwareKeyboardBackspace} from './hardware/keyboard-backspace'; export {default as HardwareKeyboardCapslock} from './hardware/keyboard-capslock'; export {default as HardwareKeyboardHide} from './hardware/keyboard-hide'; export {default as HardwareKeyboardReturn} from './hardware/keyboard-return'; export {default as HardwareKeyboardTab} from './hardware/keyboard-tab'; export {default as HardwareKeyboardVoice} from './hardware/keyboard-voice'; export {default as HardwareKeyboard} from './hardware/keyboard'; export {default as HardwareLaptopChromebook} from './hardware/laptop-chromebook'; export {default as HardwareLaptopMac} from './hardware/laptop-mac'; export {default as HardwareLaptopWindows} from './hardware/laptop-windows'; export {default as HardwareLaptop} from './hardware/laptop'; export {default as HardwareMemory} from './hardware/memory'; export {default as HardwareMouse} from './hardware/mouse'; export {default as HardwarePhoneAndroid} from './hardware/phone-android'; export {default as HardwarePhoneIphone} from './hardware/phone-iphone'; export {default as HardwarePhonelinkOff} from './hardware/phonelink-off'; export {default as HardwarePhonelink} from './hardware/phonelink'; export {default as HardwarePowerInput} from './hardware/power-input'; export {default as HardwareRouter} from './hardware/router'; export {default as HardwareScanner} from './hardware/scanner'; export {default as HardwareSecurity} from './hardware/security'; export {default as HardwareSimCard} from './hardware/sim-card'; export {default as HardwareSmartphone} from './hardware/smartphone'; export {default as HardwareSpeakerGroup} from './hardware/speaker-group'; export {default as HardwareSpeaker} from './hardware/speaker'; export {default as HardwareTabletAndroid} from './hardware/tablet-android'; export {default as HardwareTabletMac} from './hardware/tablet-mac'; export {default as HardwareTablet} from './hardware/tablet'; export {default as HardwareToys} from './hardware/toys'; export {default as HardwareTv} from './hardware/tv'; export {default as HardwareVideogameAsset} from './hardware/videogame-asset'; export {default as HardwareWatch} from './hardware/watch'; export {default as ImageAddAPhoto} from './image/add-a-photo'; export {default as ImageAddToPhotos} from './image/add-to-photos'; export {default as ImageAdjust} from './image/adjust'; export {default as ImageAssistantPhoto} from './image/assistant-photo'; export {default as ImageAssistant} from './image/assistant'; export {default as ImageAudiotrack} from './image/audiotrack'; export {default as ImageBlurCircular} from './image/blur-circular'; export {default as ImageBlurLinear} from './image/blur-linear'; export {default as ImageBlurOff} from './image/blur-off'; export {default as ImageBlurOn} from './image/blur-on'; export {default as ImageBrightness1} from './image/brightness-1'; export {default as ImageBrightness2} from './image/brightness-2'; export {default as ImageBrightness3} from './image/brightness-3'; export {default as ImageBrightness4} from './image/brightness-4'; export {default as ImageBrightness5} from './image/brightness-5'; export {default as ImageBrightness6} from './image/brightness-6'; export {default as ImageBrightness7} from './image/brightness-7'; export {default as ImageBrokenImage} from './image/broken-image'; export {default as ImageBrush} from './image/brush'; export {default as ImageCameraAlt} from './image/camera-alt'; export {default as ImageCameraFront} from './image/camera-front'; export {default as ImageCameraRear} from './image/camera-rear'; export {default as ImageCameraRoll} from './image/camera-roll'; export {default as ImageCamera} from './image/camera'; export {default as ImageCenterFocusStrong} from './image/center-focus-strong'; export {default as ImageCenterFocusWeak} from './image/center-focus-weak'; export {default as ImageCollectionsBookmark} from './image/collections-bookmark'; export {default as ImageCollections} from './image/collections'; export {default as ImageColorLens} from './image/color-lens'; export {default as ImageColorize} from './image/colorize'; export {default as ImageCompare} from './image/compare'; export {default as ImageControlPointDuplicate} from './image/control-point-duplicate'; export {default as ImageControlPoint} from './image/control-point'; export {default as ImageCrop169} from './image/crop-16-9'; export {default as ImageCrop32} from './image/crop-3-2'; export {default as ImageCrop54} from './image/crop-5-4'; export {default as ImageCrop75} from './image/crop-7-5'; export {default as ImageCropDin} from './image/crop-din'; export {default as ImageCropFree} from './image/crop-free'; export {default as ImageCropLandscape} from './image/crop-landscape'; export {default as ImageCropOriginal} from './image/crop-original'; export {default as ImageCropPortrait} from './image/crop-portrait'; export {default as ImageCropRotate} from './image/crop-rotate'; export {default as ImageCropSquare} from './image/crop-square'; export {default as ImageCrop} from './image/crop'; export {default as ImageDehaze} from './image/dehaze'; export {default as ImageDetails} from './image/details'; export {default as ImageEdit} from './image/edit'; export {default as ImageExposureNeg1} from './image/exposure-neg-1'; export {default as ImageExposureNeg2} from './image/exposure-neg-2'; export {default as ImageExposurePlus1} from './image/exposure-plus-1'; export {default as ImageExposurePlus2} from './image/exposure-plus-2'; export {default as ImageExposureZero} from './image/exposure-zero'; export {default as ImageExposure} from './image/exposure'; export {default as ImageFilter1} from './image/filter-1'; export {default as ImageFilter2} from './image/filter-2'; export {default as ImageFilter3} from './image/filter-3'; export {default as ImageFilter4} from './image/filter-4'; export {default as ImageFilter5} from './image/filter-5'; export {default as ImageFilter6} from './image/filter-6'; export {default as ImageFilter7} from './image/filter-7'; export {default as ImageFilter8} from './image/filter-8'; export {default as ImageFilter9Plus} from './image/filter-9-plus'; export {default as ImageFilter9} from './image/filter-9'; export {default as ImageFilterBAndW} from './image/filter-b-and-w'; export {default as ImageFilterCenterFocus} from './image/filter-center-focus'; export {default as ImageFilterDrama} from './image/filter-drama'; export {default as ImageFilterFrames} from './image/filter-frames'; export {default as ImageFilterHdr} from './image/filter-hdr'; export {default as ImageFilterNone} from './image/filter-none'; export {default as ImageFilterTiltShift} from './image/filter-tilt-shift'; export {default as ImageFilterVintage} from './image/filter-vintage'; export {default as ImageFilter} from './image/filter'; export {default as ImageFlare} from './image/flare'; export {default as ImageFlashAuto} from './image/flash-auto'; export {default as ImageFlashOff} from './image/flash-off'; export {default as ImageFlashOn} from './image/flash-on'; export {default as ImageFlip} from './image/flip'; export {default as ImageGradient} from './image/gradient'; export {default as ImageGrain} from './image/grain'; export {default as ImageGridOff} from './image/grid-off'; export {default as ImageGridOn} from './image/grid-on'; export {default as ImageHdrOff} from './image/hdr-off'; export {default as ImageHdrOn} from './image/hdr-on'; export {default as ImageHdrStrong} from './image/hdr-strong'; export {default as ImageHdrWeak} from './image/hdr-weak'; export {default as ImageHealing} from './image/healing'; export {default as ImageImageAspectRatio} from './image/image-aspect-ratio'; export {default as ImageImage} from './image/image'; export {default as ImageIso} from './image/iso'; export {default as ImageLandscape} from './image/landscape'; export {default as ImageLeakAdd} from './image/leak-add'; export {default as ImageLeakRemove} from './image/leak-remove'; export {default as ImageLens} from './image/lens'; export {default as ImageLinkedCamera} from './image/linked-camera'; export {default as ImageLooks3} from './image/looks-3'; export {default as ImageLooks4} from './image/looks-4'; export {default as ImageLooks5} from './image/looks-5'; export {default as ImageLooks6} from './image/looks-6'; export {default as ImageLooksOne} from './image/looks-one'; export {default as ImageLooksTwo} from './image/looks-two'; export {default as ImageLooks} from './image/looks'; export {default as ImageLoupe} from './image/loupe'; export {default as ImageMonochromePhotos} from './image/monochrome-photos'; export {default as ImageMovieCreation} from './image/movie-creation'; export {default as ImageMovieFilter} from './image/movie-filter'; export {default as ImageMusicNote} from './image/music-note'; export {default as ImageNaturePeople} from './image/nature-people'; export {default as ImageNature} from './image/nature'; export {default as ImageNavigateBefore} from './image/navigate-before'; export {default as ImageNavigateNext} from './image/navigate-next'; export {default as ImagePalette} from './image/palette'; export {default as ImagePanoramaFishEye} from './image/panorama-fish-eye'; export {default as ImagePanoramaHorizontal} from './image/panorama-horizontal'; export {default as ImagePanoramaVertical} from './image/panorama-vertical'; export {default as ImagePanoramaWideAngle} from './image/panorama-wide-angle'; export {default as ImagePanorama} from './image/panorama'; export {default as ImagePhotoAlbum} from './image/photo-album'; export {default as ImagePhotoCamera} from './image/photo-camera'; export {default as ImagePhotoFilter} from './image/photo-filter'; export {default as ImagePhotoLibrary} from './image/photo-library'; export {default as ImagePhotoSizeSelectActual} from './image/photo-size-select-actual'; export {default as ImagePhotoSizeSelectLarge} from './image/photo-size-select-large'; export {default as ImagePhotoSizeSelectSmall} from './image/photo-size-select-small'; export {default as ImagePhoto} from './image/photo'; export {default as ImagePictureAsPdf} from './image/picture-as-pdf'; export {default as ImagePortrait} from './image/portrait'; export {default as ImageRemoveRedEye} from './image/remove-red-eye'; export {default as ImageRotate90DegreesCcw} from './image/rotate-90-degrees-ccw'; export {default as ImageRotateLeft} from './image/rotate-left'; export {default as ImageRotateRight} from './image/rotate-right'; export {default as ImageSlideshow} from './image/slideshow'; export {default as ImageStraighten} from './image/straighten'; export {default as ImageStyle} from './image/style'; export {default as ImageSwitchCamera} from './image/switch-camera'; export {default as ImageSwitchVideo} from './image/switch-video'; export {default as ImageTagFaces} from './image/tag-faces'; export {default as ImageTexture} from './image/texture'; export {default as ImageTimelapse} from './image/timelapse'; export {default as ImageTimer10} from './image/timer-10'; export {default as ImageTimer3} from './image/timer-3'; export {default as ImageTimerOff} from './image/timer-off'; export {default as ImageTimer} from './image/timer'; export {default as ImageTonality} from './image/tonality'; export {default as ImageTransform} from './image/transform'; export {default as ImageTune} from './image/tune'; export {default as ImageViewComfy} from './image/view-comfy'; export {default as ImageViewCompact} from './image/view-compact'; export {default as ImageVignette} from './image/vignette'; export {default as ImageWbAuto} from './image/wb-auto'; export {default as ImageWbCloudy} from './image/wb-cloudy'; export {default as ImageWbIncandescent} from './image/wb-incandescent'; export {default as ImageWbIridescent} from './image/wb-iridescent'; export {default as ImageWbSunny} from './image/wb-sunny'; export {default as MapsAddLocation} from './maps/add-location'; export {default as MapsBeenhere} from './maps/beenhere'; export {default as MapsDirectionsBike} from './maps/directions-bike'; export {default as MapsDirectionsBoat} from './maps/directions-boat'; export {default as MapsDirectionsBus} from './maps/directions-bus'; export {default as MapsDirectionsCar} from './maps/directions-car'; export {default as MapsDirectionsRailway} from './maps/directions-railway'; export {default as MapsDirectionsRun} from './maps/directions-run'; export {default as MapsDirectionsSubway} from './maps/directions-subway'; export {default as MapsDirectionsTransit} from './maps/directions-transit'; export {default as MapsDirectionsWalk} from './maps/directions-walk'; export {default as MapsDirections} from './maps/directions'; export {default as MapsEditLocation} from './maps/edit-location'; export {default as MapsFlight} from './maps/flight'; export {default as MapsHotel} from './maps/hotel'; export {default as MapsLayersClear} from './maps/layers-clear'; export {default as MapsLayers} from './maps/layers'; export {default as MapsLocalActivity} from './maps/local-activity'; export {default as MapsLocalAirport} from './maps/local-airport'; export {default as MapsLocalAtm} from './maps/local-atm'; export {default as MapsLocalBar} from './maps/local-bar'; export {default as MapsLocalCafe} from './maps/local-cafe'; export {default as MapsLocalCarWash} from './maps/local-car-wash'; export {default as MapsLocalConvenienceStore} from './maps/local-convenience-store'; export {default as MapsLocalDining} from './maps/local-dining'; export {default as MapsLocalDrink} from './maps/local-drink'; export {default as MapsLocalFlorist} from './maps/local-florist'; export {default as MapsLocalGasStation} from './maps/local-gas-station'; export {default as MapsLocalGroceryStore} from './maps/local-grocery-store'; export {default as MapsLocalHospital} from './maps/local-hospital'; export {default as MapsLocalHotel} from './maps/local-hotel'; export {default as MapsLocalLaundryService} from './maps/local-laundry-service'; export {default as MapsLocalLibrary} from './maps/local-library'; export {default as MapsLocalMall} from './maps/local-mall'; export {default as MapsLocalMovies} from './maps/local-movies'; export {default as MapsLocalOffer} from './maps/local-offer'; export {default as MapsLocalParking} from './maps/local-parking'; export {default as MapsLocalPharmacy} from './maps/local-pharmacy'; export {default as MapsLocalPhone} from './maps/local-phone'; export {default as MapsLocalPizza} from './maps/local-pizza'; export {default as MapsLocalPlay} from './maps/local-play'; export {default as MapsLocalPostOffice} from './maps/local-post-office'; export {default as MapsLocalPrintshop} from './maps/local-printshop'; export {default as MapsLocalSee} from './maps/local-see'; export {default as MapsLocalShipping} from './maps/local-shipping'; export {default as MapsLocalTaxi} from './maps/local-taxi'; export {default as MapsMap} from './maps/map'; export {default as MapsMyLocation} from './maps/my-location'; export {default as MapsNavigation} from './maps/navigation'; export {default as MapsNearMe} from './maps/near-me'; export {default as MapsPersonPinCircle} from './maps/person-pin-circle'; export {default as MapsPersonPin} from './maps/person-pin'; export {default as MapsPinDrop} from './maps/pin-drop'; export {default as MapsPlace} from './maps/place'; export {default as MapsRateReview} from './maps/rate-review'; export {default as MapsRestaurantMenu} from './maps/restaurant-menu'; export {default as MapsSatellite} from './maps/satellite'; export {default as MapsStoreMallDirectory} from './maps/store-mall-directory'; export {default as MapsTerrain} from './maps/terrain'; export {default as MapsTraffic} from './maps/traffic'; export {default as MapsZoomOutMap} from './maps/zoom-out-map'; export {default as NavigationApps} from './navigation/apps'; export {default as NavigationArrowBack} from './navigation/arrow-back'; export {default as NavigationArrowDownward} from './navigation/arrow-downward'; export {default as NavigationArrowDropDownCircle} from './navigation/arrow-drop-down-circle'; export {default as NavigationArrowDropDown} from './navigation/arrow-drop-down'; export {default as NavigationArrowDropUp} from './navigation/arrow-drop-up'; export {default as NavigationArrowForward} from './navigation/arrow-forward'; export {default as NavigationArrowUpward} from './navigation/arrow-upward'; export {default as NavigationCancel} from './navigation/cancel'; export {default as NavigationCheck} from './navigation/check'; export {default as NavigationChevronLeft} from './navigation/chevron-left'; export {default as NavigationChevronRight} from './navigation/chevron-right'; export {default as NavigationClose} from './navigation/close'; export {default as NavigationExpandLess} from './navigation/expand-less'; export {default as NavigationExpandMore} from './navigation/expand-more'; export {default as NavigationFullscreenExit} from './navigation/fullscreen-exit'; export {default as NavigationFullscreen} from './navigation/fullscreen'; export {default as NavigationMenu} from './navigation/menu'; export {default as NavigationMoreHoriz} from './navigation/more-horiz'; export {default as NavigationMoreVert} from './navigation/more-vert'; export {default as NavigationRefresh} from './navigation/refresh'; export {default as NavigationSubdirectoryArrowLeft} from './navigation/subdirectory-arrow-left'; export {default as NavigationSubdirectoryArrowRight} from './navigation/subdirectory-arrow-right'; export {default as NavigationUnfoldLess} from './navigation/unfold-less'; export {default as NavigationUnfoldMore} from './navigation/unfold-more'; export {default as NavigationArrowDropRight} from './navigation-arrow-drop-right'; export {default as NotificationAdb} from './notification/adb'; export {default as NotificationAirlineSeatFlatAngled} from './notification/airline-seat-flat-angled'; export {default as NotificationAirlineSeatFlat} from './notification/airline-seat-flat'; export {default as NotificationAirlineSeatIndividualSuite} from './notification/airline-seat-individual-suite'; export {default as NotificationAirlineSeatLegroomExtra} from './notification/airline-seat-legroom-extra'; export {default as NotificationAirlineSeatLegroomNormal} from './notification/airline-seat-legroom-normal'; export {default as NotificationAirlineSeatLegroomReduced} from './notification/airline-seat-legroom-reduced'; export {default as NotificationAirlineSeatReclineExtra} from './notification/airline-seat-recline-extra'; export {default as NotificationAirlineSeatReclineNormal} from './notification/airline-seat-recline-normal'; export {default as NotificationBluetoothAudio} from './notification/bluetooth-audio'; export {default as NotificationConfirmationNumber} from './notification/confirmation-number'; export {default as NotificationDiscFull} from './notification/disc-full'; export {default as NotificationDoNotDisturbAlt} from './notification/do-not-disturb-alt'; export {default as NotificationDoNotDisturb} from './notification/do-not-disturb'; export {default as NotificationDriveEta} from './notification/drive-eta'; export {default as NotificationEnhancedEncryption} from './notification/enhanced-encryption'; export {default as NotificationEventAvailable} from './notification/event-available'; export {default as NotificationEventBusy} from './notification/event-busy'; export {default as NotificationEventNote} from './notification/event-note'; export {default as NotificationFolderSpecial} from './notification/folder-special'; export {default as NotificationLiveTv} from './notification/live-tv'; export {default as NotificationMms} from './notification/mms'; export {default as NotificationMore} from './notification/more'; export {default as NotificationNetworkCheck} from './notification/network-check'; export {default as NotificationNetworkLocked} from './notification/network-locked'; export {default as NotificationNoEncryption} from './notification/no-encryption'; export {default as NotificationOndemandVideo} from './notification/ondemand-video'; export {default as NotificationPersonalVideo} from './notification/personal-video'; export {default as NotificationPhoneBluetoothSpeaker} from './notification/phone-bluetooth-speaker'; export {default as NotificationPhoneForwarded} from './notification/phone-forwarded'; export {default as NotificationPhoneInTalk} from './notification/phone-in-talk'; export {default as NotificationPhoneLocked} from './notification/phone-locked'; export {default as NotificationPhoneMissed} from './notification/phone-missed'; export {default as NotificationPhonePaused} from './notification/phone-paused'; export {default as NotificationPower} from './notification/power'; export {default as NotificationRvHookup} from './notification/rv-hookup'; export {default as NotificationSdCard} from './notification/sd-card'; export {default as NotificationSimCardAlert} from './notification/sim-card-alert'; export {default as NotificationSmsFailed} from './notification/sms-failed'; export {default as NotificationSms} from './notification/sms'; export {default as NotificationSyncDisabled} from './notification/sync-disabled'; export {default as NotificationSyncProblem} from './notification/sync-problem'; export {default as NotificationSync} from './notification/sync'; export {default as NotificationSystemUpdate} from './notification/system-update'; export {default as NotificationTapAndPlay} from './notification/tap-and-play'; export {default as NotificationTimeToLeave} from './notification/time-to-leave'; export {default as NotificationVibration} from './notification/vibration'; export {default as NotificationVoiceChat} from './notification/voice-chat'; export {default as NotificationVpnLock} from './notification/vpn-lock'; export {default as NotificationWc} from './notification/wc'; export {default as NotificationWifi} from './notification/wifi'; export {default as PlacesAcUnit} from './places/ac-unit'; export {default as PlacesAirportShuttle} from './places/airport-shuttle'; export {default as PlacesAllInclusive} from './places/all-inclusive'; export {default as PlacesBeachAccess} from './places/beach-access'; export {default as PlacesBusinessCenter} from './places/business-center'; export {default as PlacesCasino} from './places/casino'; export {default as PlacesChildCare} from './places/child-care'; export {default as PlacesChildFriendly} from './places/child-friendly'; export {default as PlacesFitnessCenter} from './places/fitness-center'; export {default as PlacesFreeBreakfast} from './places/free-breakfast'; export {default as PlacesGolfCourse} from './places/golf-course'; export {default as PlacesHotTub} from './places/hot-tub'; export {default as PlacesKitchen} from './places/kitchen'; export {default as PlacesPool} from './places/pool'; export {default as PlacesRoomService} from './places/room-service'; export {default as PlacesSmokeFree} from './places/smoke-free'; export {default as PlacesSmokingRooms} from './places/smoking-rooms'; export {default as PlacesSpa} from './places/spa'; export {default as SocialCake} from './social/cake'; export {default as SocialDomain} from './social/domain'; export {default as SocialGroupAdd} from './social/group-add'; export {default as SocialGroup} from './social/group'; export {default as SocialLocationCity} from './social/location-city'; export {default as SocialMoodBad} from './social/mood-bad'; export {default as SocialMood} from './social/mood'; export {default as SocialNotificationsActive} from './social/notifications-active'; export {default as SocialNotificationsNone} from './social/notifications-none'; export {default as SocialNotificationsOff} from './social/notifications-off'; export {default as SocialNotificationsPaused} from './social/notifications-paused'; export {default as SocialNotifications} from './social/notifications'; export {default as SocialPages} from './social/pages'; export {default as SocialPartyMode} from './social/party-mode'; export {default as SocialPeopleOutline} from './social/people-outline'; export {default as SocialPeople} from './social/people'; export {default as SocialPersonAdd} from './social/person-add'; export {default as SocialPersonOutline} from './social/person-outline'; export {default as SocialPerson} from './social/person'; export {default as SocialPlusOne} from './social/plus-one'; export {default as SocialPoll} from './social/poll'; export {default as SocialPublic} from './social/public'; export {default as SocialSchool} from './social/school'; export {default as SocialShare} from './social/share'; export {default as SocialWhatshot} from './social/whatshot'; export {default as ToggleCheckBoxOutlineBlank} from './toggle/check-box-outline-blank'; export {default as ToggleCheckBox} from './toggle/check-box'; export {default as ToggleIndeterminateCheckBox} from './toggle/indeterminate-check-box'; export {default as ToggleRadioButtonChecked} from './toggle/radio-button-checked'; export {default as ToggleRadioButtonUnchecked} from './toggle/radio-button-unchecked'; export {default as ToggleStarBorder} from './toggle/star-border'; export {default as ToggleStarHalf} from './toggle/star-half'; export {default as ToggleStar} from './toggle/star';
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("a11yhelp","sl",{title:"Navodila za dostopnost",contents:"Vsebina pomoči. Če želite zapreti pogovorno okno, pritisnite ESC.",legend:[{name:"Splošno",items:[{name:"Orodna vrstica urejevalnika",legend:"Pritisnite ${toolbarFocus} za pomik v orodno vrstico. Z TAB in SHIFT+TAB se pomikate na naslednjo in prejšnjo skupino orodne vrstice. Z DESNO PUŠČICO ali LEVO PUŠČICO se pomikate na naslednji in prejšnji gumb orodne vrstice. Pritisnite SPACE ali ENTER, da aktivirate gumb orodne vrstice."}, {name:"Urejevalno Pogovorno Okno",legend:"Inside a dialog, press TAB to navigate to the next dialog element, press SHIFT+TAB to move to the previous dialog element, press ENTER to submit the dialog, press ESC to cancel the dialog. When a dialog has multiple tabs, the tab list can be reached either with ALT+F10 or with TAB as part of the dialog tabbing order. With tab list focused, move to the next and previous tab with RIGHT and LEFT ARROW, respectively."},{name:"Kontekstni meni urejevalnika",legend:"Pritisnite ${contextMenu} ali APPLICATION KEY, da odprete kontekstni meni. Nato se premaknite na naslednjo možnost menija s tipko TAB ali PUŠČICA DOL. Premakniti se na prejšnjo možnost z SHIFT + TAB ali PUŠČICA GOR. Pritisnite SPACE ali ENTER za izbiro možnosti menija. Odprite podmeni trenutne možnosti menija s tipko SPACE ali ENTER ali DESNA PUŠČICA. Vrnite se na matični element menija s tipko ESC ali LEVA PUŠČICA. Zaprite kontekstni meni z ESC."}, {name:"Urejevalno Seznamsko Polje",legend:"Znotraj seznama, se premaknete na naslednji element seznama s tipko TAB ali PUŠČICO DOL. Z SHIFT+TAB ali PUŠČICO GOR se premaknete na prejšnji element seznama. Pritisnite tipko SPACE ali ENTER za izbiro elementa. Pritisnite tipko ESC, da zaprete seznam."},{name:"Urejevalna vrstica poti elementa",legend:"Pritisnite ${elementsPathFocus} za pomikanje po vrstici elementnih poti. S TAB ali DESNA PUŠČICA se premaknete na naslednji gumb elementa. Z SHIFT+TAB ali LEVO PUŠČICO se premaknete na prejšnji gumb elementa. Pritisnite SPACE ali ENTER za izbiro elementa v urejevalniku."}]}, {name:"Ukazi",items:[{name:"Razveljavi ukaz",legend:"Pritisnite ${undo}"},{name:"Ponovi ukaz",legend:"Pritisnite ${redo}"},{name:"Krepki ukaz",legend:"Pritisnite ${bold}"},{name:"Ležeči ukaz",legend:"Pritisnite ${italic}"},{name:"Poudarni ukaz",legend:"Pritisnite ${underline}"},{name:"Ukaz povezave",legend:"Pritisnite ${link}"},{name:"Skrči Orodno Vrstico Ukaz",legend:"Pritisnite ${toolbarCollapse}"},{name:"Dostop do prejšnjega ukaza ostrenja",legend:"Pritisnite ${accessPreviousSpace} za dostop do najbližjega nedosegljivega osredotočenega prostora pred strešico, npr.: dva sosednja HR elementa. Ponovite kombinacijo tipk, da dosežete oddaljene osredotočene prostore."}, {name:"Dostop do naslednjega ukaza ostrenja",legend:"Pritisnite ${accessNextSpace} za dostop do najbližjega nedosegljivega osredotočenega prostora po strešici, npr.: dva sosednja HR elementa. Ponovite kombinacijo tipk, da dosežete oddaljene osredotočene prostore."},{name:"Pomoč dostopnosti",legend:"Pritisnite ${a11yHelp}"},{name:" Paste as plain text",legend:"Press ${pastetext}",legendEdge:"Press ${pastetext}, followed by ${paste}"}]}],tab:"Tab",pause:"Pause",capslock:"Caps Lock",escape:"Escape", pageUp:"Page Up",pageDown:"Page Down",leftArrow:"Puščica levo",upArrow:"Puščica gor",rightArrow:"Puščica desno",downArrow:"Puščica dol",insert:"Insert",leftWindowKey:"Leva tipka Windows",rightWindowKey:"Desna tipka Windows",selectKey:"Select tipka",numpad0:"Numpad 0",numpad1:"Numpad 1",numpad2:"Numpad 2",numpad3:"Numpad 3",numpad4:"Numpad 4",numpad5:"Numpad 5",numpad6:"Numpad 6",numpad7:"Numpad 7",numpad8:"Numpad 8",numpad9:"Numpad 9",multiply:"Zmnoži",add:"Dodaj",subtract:"Odštej",decimalPoint:"Decimalna vejica", divide:"Deli",f1:"F1",f2:"F2",f3:"F3",f4:"F4",f5:"F5",f6:"F6",f7:"F7",f8:"F8",f9:"F9",f10:"F10",f11:"F11",f12:"F12",numLock:"Num Lock",scrollLock:"Scroll Lock",semiColon:"Podpičje",equalSign:"Enačaj",comma:"Vejica",dash:"Vezaj",period:"Pika",forwardSlash:"Desna poševnica",graveAccent:"Krativec",openBracket:"Oklepaj",backSlash:"Leva poševnica",closeBracket:"Zaklepaj",singleQuote:"Opuščaj"});
import Helper from './_helper'; import { module, test } from 'qunit'; module('Integration | ORM | Has Many | Named | instantiating', function(hooks) { hooks.beforeEach(function() { this.helper = new Helper(); this.schema = this.helper.schema; }); test('the parent accepts a saved child id', function(assert) { let post = this.helper.savedChild(); let user = this.schema.users.new({ blogPostIds: [ post.id ] }); assert.deepEqual(user.blogPostIds, [ post.id ]); assert.deepEqual(user.blogPosts.models[0], post); }); test('the parent errors if the children ids don\'t exist', function(assert) { assert.throws(function() { this.schema.users.new({ blogPostIds: [ 2 ] }); }, /You're instantiating a user that has a blogPostIds of 2, but some of those records don't exist in the database/); }); test('the parent accepts null children foreign key', function(assert) { let user = this.schema.users.new({ blogPostIds: null }); assert.equal(user.blogPosts.models.length, 0); assert.deepEqual(user.blogPostIds, []); assert.deepEqual(user.attrs, { blogPostIds: null }); }); test('the parent accepts saved children', function(assert) { let post = this.helper.savedChild(); let user = this.schema.users.new({ blogPosts: [ post ] }); assert.deepEqual(user.blogPostIds, [ post.id ]); assert.deepEqual(user.blogPosts.models[0], post); }); test('the parent accepts new children', function(assert) { let post = this.schema.posts.new({ title: 'Lorem' }); let user = this.schema.users.new({ blogPosts: [ post ] }); assert.deepEqual(user.blogPostIds, [ undefined ]); assert.deepEqual(user.blogPosts.models[0], post); }); test('the parent accepts null children', function(assert) { let user = this.schema.users.new({ blogPosts: null }); assert.equal(user.blogPosts.models.length, 0); assert.deepEqual(user.blogPostIds, []); assert.deepEqual(user.attrs, { blogPostIds: null }); }); test('the parent accepts children and child ids', function(assert) { let post = this.helper.savedChild(); let user = this.schema.users.new({ blogPosts: [ post ], blogPostIds: [ post.id ] }); assert.deepEqual(user.blogPostIds, [ post.id ]); assert.deepEqual(user.blogPosts.models[0], post); }); test('the parent accepts no reference to children or child ids as empty obj', function(assert) { let user = this.schema.users.new({}); assert.deepEqual(user.blogPostIds, []); assert.deepEqual(user.blogPosts.models, []); assert.deepEqual(user.attrs, { blogPostIds: null }); }); test('the parent accepts no reference to children or child ids', function(assert) { let user = this.schema.users.new(); assert.deepEqual(user.blogPostIds, []); assert.deepEqual(user.blogPosts.models, []); assert.deepEqual(user.attrs, { blogPostIds: null }); }); });
var format = require('util').format; var css2str = require('css2str'); var cleancss = require('clean-css'); var commonParser = require('./common'); exports.init = function(grunt) { return commonParser.init(grunt, { type: 'css', factoryParser: css2js }); }; exports.css2js = function(code, id, options, fileObj) { var tpl = 'define("%s", [], %s);'; return format(tpl, id, css2js(code, options, fileObj)); }; function css2js(code, options, fileObj) { var addStyleBox = false; if (options.styleBox === true) { addStyleBox = true; } else if (options.styleBox && options.styleBox.length) { options.styleBox.forEach(function(file) { if (file === fileObj.name) { addStyleBox = true; } }); } // if outside css modules, fileObj would be undefined // then dont add styleBox var opt = {}; if (addStyleBox && fileObj) { // ex. arale/widget/1.0.0/ => arale-widget-1_0_0 var styleId = unixy((options || {}).idleading || '') .replace(/\/$/, '') .replace(/\//g, '-') .replace(/\./g, '_'); opt.prefix = ['.', styleId, ' '].join(''); } code = css2str(code, opt); // remove comment and format code = cleancss.process(code, { keepSpecialComments: 0, removeEmpty: true }); // transform css to js // spmjs/spm#581 var template = 'function() {seajs.importStyle(\'%s\')}'; return format(template, code); } function unixy(uri) { return uri.replace(/\\/g, '/'); }
import isArrayEqual from '../util/isArrayEqual' import Coordinate from './Coordinate' /* Adapter for Coordinate oriented implementations. E.g. Coordinate transforms can be applied to update selections using OT. @internal */ class CoordinateAdapter extends Coordinate { constructor(owner, pathProperty, offsetProperty) { super('SKIP') this._owner = owner; this._pathProp = pathProperty; this._offsetProp = offsetProperty; Object.freeze(this); } equals(other) { return (other === this || (isArrayEqual(other.path, this.path) && other.offset === this.offset) ) } get path() { return this._owner[this._pathProp]; } set path(path) { this._owner[this._pathProp] = path; } get offset() { return this._owner[this._offsetProp]; } set offset(offset) { this._owner[this._offsetProp] = offset; } toJSON() { return { path: this.path, offset: this.offset } } toString() { return "(" + this.path.join('.') + ", " + this.offset + ")" } } export default CoordinateAdapter
import request from 'ROOT_SOURCE/utils/request' import { CURRENT_PAGE, PAGE_SIZE, TOTAL, RESPONSE_DESTRUST_KEY, RESPONSE_LIST_DESTRUST_KEY } from 'ROOT_SOURCE/base/BaseConfig' import { MOD_PREFIX } from '../constants' export const LIST__UPDATE_FORM_DATA = `${MOD_PREFIX}__LIST__UPDATE_FORM_DATA` export const LIST__UPDATE_TABLE_DATA = `${MOD_PREFIX}__LIST__UPDATE_TABLE_DATA` const updateTable = function (/*formData|pagination*/formData={}) { return async (dispatch, getState) => { // 初始化antd-table-pagination let _formData = Object.assign( {[PAGE_SIZE]: 10, [CURRENT_PAGE]: 1}, formData, ) // 请求server数据 let result = await request['post']('/asset/getAsset', _formData) if (!result) { return; } // 解构server结果 let resultBody = result[RESPONSE_DESTRUST_KEY] if (!resultBody) { return; } // 更新formData dispatch({ type: LIST__UPDATE_FORM_DATA, payload: { ..._formData, [TOTAL]: resultBody[TOTAL], } }) // 更新tableData dispatch({ type: LIST__UPDATE_TABLE_DATA, payload: { dataSource: resultBody[RESPONSE_LIST_DESTRUST_KEY], } }) return resultBody } } export default { updateTable, }
import React from 'react' import warning from './routerWarning' import invariant from 'invariant' import { createRouteFromReactElement } from './RouteUtils' import { component, components, falsy } from './InternalPropTypes' const { func } = React.PropTypes /** * An <IndexRoute> is used to specify its parent's <Route indexRoute> in * a JSX route config. */ const IndexRoute = React.createClass({ statics: { createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = createRouteFromReactElement(element) } else { warning( false, 'An <IndexRoute> does not make sense at the root of your route config' ) } } }, propTypes: { path: falsy, component, components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render() { invariant( false, '<IndexRoute> elements are for router configuration only and should not be rendered' ) } }) export default IndexRoute
import parser from 'css'; // TODO: (tchen) this file hasn't been finished. /** * Use all kinds of rules to transform HTML file. */ class CssProcessor { constructor(doc) { this._doc = doc; this._ast = undefined; this._css = ''; this._rules = []; } /** * Register a new rule * * @param {Object} rule * @return {CssProcessor} */ use(rule) { const schema = Joi.object().keys({ name: Joi.string().required(), filters: Joi.array().items(Joi.func()).required(), results: Joi.array().required(), transform: Joi.func().required(), }); Joi.validate(rule, schema, (err, value) => { if (err) { logger.error(err, value); throw err; } }); this._rules.push(rule); return this; } /** * Generate AST for html file * * @return {CssProcessor} */ ast() { this._ast = this._ast || parser.parse(this._doc); return this; } /** * Transform the nodes that matched by rules, by using the tranform() function * defined in rules. * * @return {CssProcessor} */ transform() { if (!this._ast) { logger.info('Please call ast() to generate AST first.'); return this; } if (!this._rules.length) { logger.info('Nothing to transform. You have not defined rules by using use().'); return this; } findNode(this._ast, this._rules); return this; } /** * Generate html string from the AST. * * @return {CssProcessor} */ serialize() { if (this._ast) { this._css = parser.stringify(this._ast); } return this; } /** * Output the html string * * @return {string} */ toString() { return this._css; } } export default CssProcessor;
class ModelUsers extends RocketChat.models._Base { constructor() { super(...arguments); this.tryEnsureIndex({ 'roles': 1 }, { sparse: 1 }); this.tryEnsureIndex({ 'name': 1 }); this.tryEnsureIndex({ 'lastLogin': 1 }); this.tryEnsureIndex({ 'status': 1 }); this.tryEnsureIndex({ 'active': 1 }, { sparse: 1 }); this.tryEnsureIndex({ 'statusConnection': 1 }, { sparse: 1 }); this.tryEnsureIndex({ 'type': 1 }); this.cache.ensureIndex('username', 'unique'); } findOneByImportId(_id, options) { return this.findOne({ importIds: _id }, options); } findOneByUsername(username, options) { const query = {username}; return this.findOne(query, options); } findOneByEmailAddress(emailAddress, options) { const query = {'emails.address': new RegExp(`^${ s.escapeRegExp(emailAddress) }$`, 'i')}; return this.findOne(query, options); } findOneAdmin(admin, options) { const query = {admin}; return this.findOne(query, options); } findOneByIdAndLoginToken(_id, token, options) { const query = { _id, 'services.resume.loginTokens.hashedToken' : Accounts._hashLoginToken(token) }; return this.findOne(query, options); } // FIND findById(userId) { const query = {_id: userId}; return this.find(query); } findUsersNotOffline(options) { const query = { username: { $exists: 1 }, status: { $in: ['online', 'away', 'busy'] } }; return this.find(query, options); } findByUsername(username, options) { const query = {username}; return this.find(query, options); } findUsersByUsernamesWithHighlights(usernames, options) { if (this.useCache) { const result = { fetch() { return RocketChat.models.Users.getDynamicView('highlights').data().filter(record => usernames.indexOf(record.username) > -1); }, count() { return result.fetch().length; }, forEach(fn) { return result.fetch().forEach(fn); } }; return result; } const query = { username: { $in: usernames }, 'settings.preferences.highlights.0': { $exists: true } }; return this.find(query, options); } findActiveByUsernameOrNameRegexWithExceptions(searchTerm, exceptions, options) { if (exceptions == null) { exceptions = []; } if (options == null) { options = {}; } if (!_.isArray(exceptions)) { exceptions = [ exceptions ]; } const termRegex = new RegExp(s.escapeRegExp(searchTerm), 'i'); const query = { $or: [{ username: termRegex }, { name: termRegex }], active: true, type: { $in: ['user', 'bot'] }, $and: [{ username: { $exists: true } }, { username: { $nin: exceptions } }] }; return this.find(query, options); } findByActiveUsersExcept(searchTerm, exceptions, options) { if (exceptions == null) { exceptions = []; } if (options == null) { options = {}; } if (!_.isArray(exceptions)) { exceptions = [ exceptions ]; } const termRegex = new RegExp(s.escapeRegExp(searchTerm), 'i'); const query = { $and: [ { active: true, $or: [ { username: termRegex }, { name: termRegex }, { 'emails.address': termRegex } ] }, { username: { $exists: true, $nin: exceptions } } ] }; // do not use cache return this._db.find(query, options); } findUsersByNameOrUsername(nameOrUsername, options) { const query = { username: { $exists: 1 }, $or: [ {name: nameOrUsername}, {username: nameOrUsername} ], type: { $in: ['user'] } }; return this.find(query, options); } findByUsernameNameOrEmailAddress(usernameNameOrEmailAddress, options) { const query = { $or: [ {name: usernameNameOrEmailAddress}, {username: usernameNameOrEmailAddress}, {'emails.address': usernameNameOrEmailAddress} ], type: { $in: ['user', 'bot'] } }; return this.find(query, options); } findLDAPUsers(options) { const query = {ldap: true}; return this.find(query, options); } findCrowdUsers(options) { const query = {crowd: true}; return this.find(query, options); } getLastLogin(options) { if (options == null) { options = {}; } const query = { lastLogin: { $exists: 1 } }; options.sort = { lastLogin: -1 }; options.limit = 1; const [user] = this.find(query, options).fetch(); return user && user.lastLogin; } findUsersByUsernames(usernames, options) { const query = { username: { $in: usernames } }; return this.find(query, options); } findUsersByIds(ids, options) { const query = { _id: { $in: ids } }; return this.find(query, options); } // UPDATE addImportIds(_id, importIds) { importIds = [].concat(importIds); const query = {_id}; const update = { $addToSet: { importIds: { $each: importIds } } }; return this.update(query, update); } updateLastLoginById(_id) { const update = { $set: { lastLogin: new Date } }; return this.update(_id, update); } setServiceId(_id, serviceName, serviceId) { const update = {$set: {}}; const serviceIdKey = `services.${ serviceName }.id`; update.$set[serviceIdKey] = serviceId; return this.update(_id, update); } setUsername(_id, username) { const update = {$set: {username}}; return this.update(_id, update); } setEmail(_id, email) { const update = { $set: { emails: [{ address: email, verified: false } ] } }; return this.update(_id, update); } setEmailVerified(_id, email) { const query = { _id, emails: { $elemMatch: { address: email, verified: false } } }; const update = { $set: { 'emails.$.verified': true } }; return this.update(query, update); } setName(_id, name) { const update = { $set: { name } }; return this.update(_id, update); } setCustomFields(_id, fields) { const values = {}; Object.keys(fields).forEach(key => { values[`customFields.${ key }`] = fields[key]; }); const update = {$set: values}; return this.update(_id, update); } setAvatarOrigin(_id, origin) { const update = { $set: { avatarOrigin: origin } }; return this.update(_id, update); } unsetAvatarOrigin(_id) { const update = { $unset: { avatarOrigin: 1 } }; return this.update(_id, update); } setUserActive(_id, active) { if (active == null) { active = true; } const update = { $set: { active } }; return this.update(_id, update); } setAllUsersActive(active) { const update = { $set: { active } }; return this.update({}, update, { multi: true }); } unsetLoginTokens(_id) { const update = { $set: { 'services.resume.loginTokens' : [] } }; return this.update(_id, update); } unsetRequirePasswordChange(_id) { const update = { $unset: { 'requirePasswordChange' : true, 'requirePasswordChangeReason' : true } }; return this.update(_id, update); } resetPasswordAndSetRequirePasswordChange(_id, requirePasswordChange, requirePasswordChangeReason) { const update = { $unset: { 'services.password': 1 }, $set: { requirePasswordChange, requirePasswordChangeReason } }; return this.update(_id, update); } setLanguage(_id, language) { const update = { $set: { language } }; return this.update(_id, update); } setProfile(_id, profile) { const update = { $set: { 'settings.profile': profile } }; return this.update(_id, update); } setPreferences(_id, preferences) { const update = { $set: { 'settings.preferences': preferences } }; return this.update(_id, update); } setUtcOffset(_id, utcOffset) { const query = { _id, utcOffset: { $ne: utcOffset } }; const update = { $set: { utcOffset } }; return this.update(query, update); } saveUserById(_id, data) { const setData = {}; const unsetData = {}; if (data.name != null) { if (!_.isEmpty(s.trim(data.name))) { setData.name = s.trim(data.name); } else { unsetData.name = 1; } } if (data.email != null) { if (!_.isEmpty(s.trim(data.email))) { setData.emails = [{address: s.trim(data.email)}]; } else { unsetData.emails = 1; } } if (data.phone != null) { if (!_.isEmpty(s.trim(data.phone))) { setData.phone = [{phoneNumber: s.trim(data.phone)}]; } else { unsetData.phone = 1; } } const update = {}; if (!_.isEmpty(setData)) { update.$set = setData; } if (!_.isEmpty(unsetData)) { update.$unset = unsetData; } if (_.isEmpty(update)) { return true; } return this.update({ _id }, update); } // INSERT create(data) { const user = { createdAt: new Date, avatarOrigin: 'none' }; _.extend(user, data); return this.insert(user); } // REMOVE removeById(_id) { return this.remove(_id); } /* Find users to send a message by email if: - he is not online - has a verified email - has not disabled email notifications - `active` is equal to true (false means they were deactivated and can't login) */ getUsersToSendOfflineEmail(usersIds) { const query = { _id: { $in: usersIds }, active: true, status: 'offline', statusConnection: { $ne: 'online' }, 'emails.verified': true }; return this.find(query, { fields: { name: 1, username: 1, emails: 1, 'settings.preferences.emailNotificationMode': 1 } }); } } RocketChat.models.Users = new ModelUsers(Meteor.users, true);
function render() { const ul = <ul>{lis.map((li) => { return <li /> })}</ul>; return <root>{ul}</root>; }
var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var devFlagPlugin = new webpack.DefinePlugin({ __DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'false')) }); module.exports = { entry: [ './js/index.js' ], output: { path: __dirname + '/static/', publicPath: '/static/', filename: 'bundle.js', }, plugins: [ new webpack.NoErrorsPlugin(), devFlagPlugin, new ExtractTextPlugin('app.css') ], module: { loaders: [ { test: /\.js$/, loaders: ['babel'], exclude: /node_modules/ }, { test: /\.css$/, loader: ExtractTextPlugin.extract('css-loader?module!cssnext-loader') } ] }, resolve: { extensions: ['', '.js', '.json'] } };
/* * @package jsDAV * @subpackage CardDAV * @copyright Copyright(c) 2013 Mike de Boer. <info AT mikedeboer DOT nl> * @author Mike de Boer <info AT mikedeboer DOT nl> * @license http://github.com/mikedeboer/jsDAV/blob/master/LICENSE MIT License */ "use strict"; var jsCardDAV_iBackend = require("./../interfaces/iBackend"); var jsCardDAV_Plugin = require("./../plugin"); var jsCardDAV_Property_SupportedAddressData = require("./../property/supportedAddressData"); var Db = require("./../../shared/backends/redis"); var Exc = require("./../../shared/exceptions"); var Util = require("./../../shared/util"); /** * Redis CardDAV backend * * This CardDAV backend uses Redis to store addressbooks */ var jsCardDAV_Backend_Redis = module.exports = jsCardDAV_iBackend.extend({ /** * Redis connection * * @var redis */ redis: null, /** * The PDO table name used to store addressbooks */ addressBooksTableName: null, /** * The PDO table name used to store cards */ cardsTableName: null, /** * Sets up the object * * @param Redis redis * @param {String} addressBooksTableName * @param {String} cardsTableName */ initialize: function(redis, addressBooksTableName, cardsTableName) { this.redis = redis; this.addressBooksTableName = addressBooksTableName || "addressbooks"; this.cardsTableName = cardsTableName || "cards"; }, /** * Returns the list of addressbooks for a specific user. * * @param {String} principalUri * @return array */ getAddressBooksForUser: function(principalUri, callback) { var self = this; this.redis.hget(this.addressBooksTableName + "/principalUri", principalUri, function(err, res) { if (err) return callback(err); if (!res) return callback(null, []); var ids; try { ids = JSON.parse(res.toString("utf8")); } catch (ex) { return callback(ex); } var commands = ids.map(function(id) { return ["HMGET", self.addressBooksTableName + "/" + id, "uri", "principaluri", "displayname", "description", "ctag"]; }); self.redis.multi(commands).exec(function(err, res) { if (err) return callback(err); var addressBooks = Db.fromMultiBulk(res).map(function(data, idx) { var obj = { id : ids[idx], uri: data[0], principaluri: data[1], "{DAV:}displayname": data[2], "{http://calendarserver.org/ns/}getctag": data[4] }; obj["{" + jsCardDAV_Plugin.NS_CARDDAV + "}addressbook-description"] = data[3]; obj["{" + jsCardDAV_Plugin.NS_CARDDAV + "}supported-address-data"] = jsCardDAV_Property_SupportedAddressData.new(); return obj; }); callback(null, addressBooks); }); }); }, /** * Updates an addressbook's properties * * See jsDAV_iProperties for a description of the mutations array, as * well as the return value. * * @param {mixed} addressBookId * @param {Array} mutations * @see jsDAV_iProperties#updateProperties * @return bool|array */ updateAddressBook: function(addressBookId, mutations, callback) { var updates = {}; var newValue; for (var property in mutations) { newValue = mutations[property]; switch (property) { case "{DAV:}displayname" : updates.displayname = newValue; break; case "{" + jsCardDAV_Plugin.NS_CARDDAV + "}addressbook-description" : updates.description = newValue; break; default : // If any unsupported values were being updated, we must // let the entire request fail. return callback(null, false); } } // No values are being updated? if (!Object.keys(updates).length) return callback(null, false); var self = this; this.redis.hget(this.addressBooksTableName + "/" + addressBookId, "ctag", function(err, res) { if (err) return callback(err); var ctag = parseInt(res.toString("utf8"), 10); var command = [self.addressBooksTableName + "/" + addressBookId, "ctag", ++ctag]; for (var property in updates) command.push(property, updates[property]); command.push(function(err) { if (err) return callback(err); callback(null, true); }); self.redis.hmset.apply(self.redis, command); }) }, /** * Creates a new address book * * @param {String} principalUri * @param {String} url Just the 'basename' of the url. * @param {Array} properties * @return void */ createAddressBook: function(principalUri, url, properties, callback) { var values = { "displayname": null, "description": null, "principaluri": principalUri, "uri": url, }; var newValue; for (var property in properties) { newValue = properties[property]; switch (property) { case "{DAV:}displayname" : values.displayname = newValue; break; case "{" + jsCardDAV_Plugin.NS_CARDDAV + "}addressbook-description" : values.description = newValue; break; default : return callback(new Exc.BadRequest("Unknown property: " + property)); } } var self = this; this.redis.hget(this.addressBooksTableName + "/principalUri", principalUri, function(err, res) { if (err) return callback(err); var ids; try { ids = JSON.parse(res.toString("utf8")); } catch (ex) { ids = []; } self.redis.incr(self.addressBooksTableName + "/ID", function(err, id) { if (err) return callback(err); ids.push(id); var commands = [ ["HSET", self.addressBooksTableName + "/principalUri", principalUri, JSON.stringify(ids)] ]; var hmset = ["HMSET", self.addressBooksTableName + "/" + id, "ctag", 1]; for (var property in values) { hmset.push(property, values[property]); } commands.push(hmset); self.redis.multi(commands).exec(callback); }); }); }, /** * Deletes an entire addressbook and all its contents * * @param {Number} addressBookId * @return void */ deleteAddressBook: function(addressBookId, callback) { var commands = [ ["DEL", this.addressBooksTableName + "/" + addressBookId], ["DEL", this.addressBooksTableName + "/" + addressBookId + "/" + this.cardsTableName] ]; var self = this; // fetch the principalUri to be able to retrieve the array of addressbooks. this.redis.hget(this.addressBooksTableName + "/" + addressBookId, "principaluri", function(err, res) { if (err) return callback(err); var principalUri = res.toString("utf8"); // fetch the addressbook array for this principalUri self.redis.hget(self.addressBooksTableName + "/principalUri", principalUri, function(err, res) { if (err || !res) return callback(err); var ids; try { ids = JSON.parse(res.toString("utf8")); } catch (ex) { ids = []; } var idx = ids.indexOf(addressBookId); if (idx > -1) ids.splice(idx, 1); commands.push(["HSET", self.addressBooksTableName + "/principalUri", principalUri, JSON.stringify(ids)]); // fetch the list of card IDs self.redis.zrange(self.addressBooksTableName + "/" + addressBookId + "/" + self.cardsTableName, 0, -1, function(err, res) { if (err) return callback(err); if (res) { Db.fromMultiBulk(res).forEach(function(cardUri) { commands.push(["DEL", self.cardsTableName + "/" + addressBookId + "/" + cardUri]); }); } self.redis.multi(commands).exec(callback) }); }); }); }, /** * Returns all cards for a specific addressbook id. * * This method should return the following properties for each card: * * carddata - raw vcard data * * uri - Some unique url * * lastmodified - A unix timestamp * * It's recommended to also return the following properties: * * etag - A unique etag. This must change every time the card changes. * * size - The size of the card in bytes. * * If these last two properties are provided, less time will be spent * calculating them. If they are specified, you can also ommit carddata. * This may speed up certain requests, especially with large cards. * * @param {mixed} addressbookId * @return array */ getCards: function(addressbookId, callback) { var self = this; // fetch the list of card IDs self.redis.zrange(this.addressBooksTableName + "/" + addressbookId + "/" + this.cardsTableName, 0, -1, function(err, res) { if (err) return callback(err); var cardUris = Db.fromMultiBulk(res); var commands = cardUris.map(function(cardUri) { return ["HMGET", self.cardsTableName + "/"+ addressbookId + "/" + cardUri, "carddata", "lastmodified"]; }); self.redis.multi(commands).exec(function(err, res) { if (err) return callback(err); if (!res || !res.length) return callback(null, []); var cards = []; Db.fromMultiBulk(res).map(function(data, idx) { if (!data[0] && !data[1]) return; cards.push({ uri: cardUris[idx], carddata: data[0], lastmodified: parseInt(data[1], 10) }); }); callback(null, cards); }); }); }, /** * Returns a specfic card. * * The same set of properties must be returned as with getCards. The only * exception is that 'carddata' is absolutely required. * * @param {mixed} addressBookId * @param {String} cardUri * @return array */ getCard: function(addressBookId, cardUri, callback) { this.redis.hmget(this.cardsTableName + "/" + addressBookId + "/" + cardUri, "carddata", "lastmodified", function(err, res) { if (err) return callback(err); res = Db.fromMultiBulk(res); if (!res || !res.length || (!res[0] && !res[1])) return callback(); callback(null, { uri: cardUri, carddata: res[0], lastmodified: parseInt(res[1], 10) }); }); }, /** * Creates a new card. * * The addressbook id will be passed as the first argument. This is the * same id as it is returned from the getAddressbooksForUser method. * * The cardUri is a base uri, and doesn't include the full path. The * cardData argument is the vcard body, and is passed as a string. * * It is possible to return an ETag from this method. This ETag is for the * newly created resource, and must be enclosed with double quotes (that * is, the string itself must contain the double quotes). * * You should only return the ETag if you store the carddata as-is. If a * subsequent GET request on the same card does not have the same body, * byte-by-byte and you did return an ETag here, clients tend to get * confused. * * If you don't return an ETag, you can just return null. * * @param {mixed} addressBookId * @param {String} cardUri * @param {String} cardData * @return string|null */ createCard: function(addressBookId, cardUri, cardData, callback) { var self = this; var now = Date.now(); var commands = [ ["HMSET", this.cardsTableName + "/" + addressBookId + "/" + cardUri, "carddata", cardData, "lastmodified", now], ["ZADD", this.addressBooksTableName + "/" + addressBookId + "/" + this.cardsTableName, now, cardUri] ]; this.redis.hget(this.addressBooksTableName + "/" + addressBookId, "ctag", function(err, ctag) { if (err) return callback(err); ctag = parseInt(ctag.toString("utf8"), 10); commands.push(["HSET", self.addressBooksTableName + "/" + addressBookId, "ctag", ++ctag]); self.redis.multi(commands).exec(function(err) { if (err) return callback(err); callback(null, "\"" + Util.md5(cardData) + "\""); }); }); }, /** * Updates a card. * * The addressbook id will be passed as the first argument. This is the * same id as it is returned from the getAddressbooksForUser method. * * The cardUri is a base uri, and doesn't include the full path. The * cardData argument is the vcard body, and is passed as a string. * * It is possible to return an ETag from this method. This ETag should * match that of the updated resource, and must be enclosed with double * quotes (that is: the string itself must contain the actual quotes). * * You should only return the ETag if you store the carddata as-is. If a * subsequent GET request on the same card does not have the same body, * byte-by-byte and you did return an ETag here, clients tend to get * confused. * * If you don't return an ETag, you can just return null. * * @param {mixed} addressBookId * @param {String} cardUri * @param {String} cardData * @return string|null */ updateCard: function(addressBookId, cardUri, cardData, callback) { var self = this; var now = Date.now(); var commands = [ ["HMSET", this.cardsTableName + "/" + addressBookId + "/" + cardUri, "carddata", cardData, "lastmodified", now] ]; this.redis.hget(this.addressBooksTableName + "/" + addressBookId, "ctag", function(err, ctag) { if (err) return callback(err); ctag = parseInt(ctag.toString("utf8"), 10); commands.push(["HSET", self.addressBooksTableName + "/" + addressBookId, "ctag", ++ctag]); self.redis.multi(commands).exec(function(err) { if (err) return callback(err); callback(null, "\"" + Util.md5(cardData) + "\""); }); }); }, /** * Deletes a card * * @param {mixed} addressBookId * @param {String} cardUri * @return bool */ deleteCard: function(addressBookId, cardUri, callback) { var self = this; var commands = [ ["DEL", this.cardsTableName + "/" + addressBookId + "/" + cardUri], ["ZREM", this.addressBooksTableName + "/" + addressBookId + "/" + this.cardsTableName, cardUri] ]; this.redis.hget(this.addressBooksTableName + "/" + addressBookId, "ctag", function(err, ctag) { if (err) return callback(err); ctag = parseInt(ctag.toString("utf8"), 10); commands.push(["HSET", self.addressBooksTableName + "/" + addressBookId, "ctag", ++ctag]); self.redis.multi(commands).exec(function(err) { if (err) return callback(err); callback(null, true); }); }); } });
version https://git-lfs.github.com/spec/v1 oid sha256:2a2b3dd9a94dffa9096c9d624c2b8f3ff1ea597cadbc30c4312d35d25d95c2af size 490
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _AX6Util = require("../AX6Util"); var _AX6Util2 = _interopRequireDefault(_AX6Util); var _AX6Mustache = require("../AX6Mustache"); var _AX6Mustache2 = _interopRequireDefault(_AX6Mustache); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var onclickPageMove = function onclickPageMove(_act) { var callback = function callback(_pageNo) { if (this.page.currentPage != _pageNo) { this.page.selectPage = _pageNo; if (this.config.page.onChange) { this.config.page.onChange.call({ self: this, page: this.page, data: this.data }); } } }; var processor = { "first": function first() { callback.call(this, 0); }, "prev": function prev() { var pageNo = this.page.currentPage - 1; if (pageNo < 0) pageNo = 0; callback.call(this, pageNo); }, "next": function next() { var pageNo = this.page.currentPage + 1; if (pageNo > this.page.totalPages - 1) pageNo = this.page.totalPages - 1; callback.call(this, pageNo); }, "last": function last() { callback.call(this, this.page.totalPages - 1); } }; if (_act in processor) { processor[_act].call(this); } else { callback.call(this, _act - 1); } }; var navigationUpdate = function navigationUpdate() { var self = this; if (this.page) { var page = { hasPage: false, currentPage: this.page.currentPage, pageSize: this.page.pageSize, totalElements: this.page.totalElements, totalPages: this.page.totalPages, firstIcon: this.config.page.firstIcon, prevIcon: this.config.page.prevIcon || "«", nextIcon: this.config.page.nextIcon || "»", lastIcon: this.config.page.lastIcon }; var navigationItemCount = this.config.page.navigationItemCount; page["@paging"] = function () { var returns = [], startI = void 0, endI = void 0; startI = page.currentPage - Math.floor(navigationItemCount / 2); if (startI < 0) startI = 0; endI = page.currentPage + navigationItemCount; if (endI > page.totalPages) endI = page.totalPages; if (endI - startI > navigationItemCount) { endI = startI + navigationItemCount; } if (endI - startI < navigationItemCount) { startI = endI - navigationItemCount; } if (startI < 0) startI = 0; for (var p = startI, l = endI; p < l; p++) { returns.push({ 'pageNo': p + 1, 'selected': page.currentPage == p }); } return returns; }(); if (page["@paging"].length > 0) { page.hasPage = true; } this.$["page"]["navigation"].html(_AX6Mustache2.default.render(this.__tmpl.page_navigation.call(this), page)); this.$["page"]["navigation"].find("[data-ax6grid-page-move]").on("click", function () { onclickPageMove.call(self, this.getAttribute("data-ax6grid-page-move")); }); } else { this.$["page"]["navigation"].empty(); } }; var statusUpdate = function statusUpdate() { if (!this.config.page.statusDisplay) { return; } var toRowIndex = void 0, rangeCount = Math.min(this.xvar.dataRowCount, this.xvar.virtualPaintRowCount); var data = {}; toRowIndex = this.xvar.virtualPaintStartRowIndex + rangeCount; if (toRowIndex > this.xvar.dataRowCount) { toRowIndex = this.xvar.dataRowCount; } data.fromRowIndex = _AX6Util2.default.number(this.xvar.virtualPaintStartRowIndex + 1, { "money": true }); data.toRowIndex = _AX6Util2.default.number(toRowIndex, { "money": true }); data.totalElements = false; data.dataRealRowCount = this.xvar.dataRowCount !== this.xvar.dataRealRowCount ? _AX6Util2.default.number(this.xvar.dataRealRowCount, { "money": true }) : false; data.dataRowCount = _AX6Util2.default.number(this.xvar.dataRowCount, { "money": true }); data.progress = this.appendProgress ? this.config.appendProgressIcon : ""; if (this.page) { data.fromRowIndex_page = _AX6Util2.default.number(this.xvar.virtualPaintStartRowIndex + this.page.currentPage * this.page.pageSize + 1, { "money": true }); data.toRowIndex_page = _AX6Util2.default.number(this.xvar.virtualPaintStartRowIndex + rangeCount + this.page.currentPage * this.page.pageSize, { "money": true }); data.totalElements = _AX6Util2.default.number(this.page.totalElements, { "money": true }); if (data.toRowIndex_page > this.page.totalElements) { data.toRowIndex_page = this.page.totalElements; } } this.$["page"]["status"].html(_AX6Mustache2.default.render(this.__tmpl.page_status.call(this), data)); }; exports.default = { navigationUpdate: navigationUpdate, statusUpdate: statusUpdate };
define(['./unique', './filter', './some', './contains'], function (unique, filter, some, contains) { /** * Return a new Array with elements that aren't present in the other Arrays. */ function difference(arr) { var arrs = Array.prototype.slice.call(arguments, 1), result = filter(unique(arr), function(needle){ return !some(arrs, function(haystack){ return contains(haystack, needle); }); }); return result; } return difference; });
/*! * reveal.js * http://lab.hakim.se/reveal-js * MIT licensed * * Copyright (C) 2016 Hakim El Hattab, http://hakim.se */ (function( root, factory ) { if( typeof define === 'function' && define.amd ) { // AMD. Register as an anonymous module. define( function() { root.Reveal = factory(); return root.Reveal; } ); } else if( typeof exports === 'object' ) { // Node. Does not work with strict CommonJS. module.exports = factory(); } else { // Browser globals. root.Reveal = factory(); } }( this, function() { 'use strict'; var Reveal; // The reveal.js version var VERSION = '3.3.0'; var SLIDES_SELECTOR = '.slides section', HORIZONTAL_SLIDES_SELECTOR = '.slides>section', VERTICAL_SLIDES_SELECTOR = '.slides>section.present>section', HOME_SLIDE_SELECTOR = '.slides>section:first-of-type', UA = navigator.userAgent, // Configuration defaults, can be overridden at initialization time config = { // The "normal" size of the presentation, aspect ratio will be preserved // when the presentation is scaled to fit different resolutions width: 960, height: 700, // Factor of the display size that should remain empty around the content margin: 0.1, // Bounds for smallest/largest possible scale to apply to content minScale: 0.2, maxScale: 1.5, // Display controls in the bottom right corner controls: false, // Display a presentation progress bar progress: true, // Display the page number of the current slide slideNumber: false, // Push each slide change to the browser history history: false, // Enable keyboard shortcuts for navigation keyboard: true, // Optional function that blocks keyboard events when retuning false keyboardCondition: null, // Enable the slide overview mode overview: true, // Vertical centering of slides center: true, // Enables touch navigation on devices with touch input touch: true, // Loop the presentation loop: false, // Change the presentation direction to be RTL rtl: false, // Randomizes the order of slides each time the presentation loads shuffle: false, // Turns fragments on and off globally fragments: true, // Flags if the presentation is running in an embedded mode, // i.e. contained within a limited portion of the screen embedded: false, // Flags if we should show a help overlay when the questionmark // key is pressed help: true, // Flags if it should be possible to pause the presentation (blackout) pause: true, // Flags if speaker notes should be visible to all viewers showNotes: false, // Number of milliseconds between automatically proceeding to the // next slide, disabled when set to 0, this value can be overwritten // by using a data-autoslide attribute on your slides autoSlide: 0, // Stop auto-sliding after user input autoSlideStoppable: true, // Use this method for navigation when auto-sliding (defaults to navigateNext) autoSlideMethod: null, // Enable slide navigation via mouse wheel mouseWheel: false, // Apply a 3D roll to links on hover rollingLinks: false, // Hides the address bar on mobile devices hideAddressBar: true, // Opens links in an iframe preview overlay previewLinks: false, // Exposes the reveal.js API through window.postMessage postMessage: true, // Dispatches all reveal.js events to the parent window through postMessage postMessageEvents: false, // Focuses body when page changes visiblity to ensure keyboard shortcuts work focusBodyOnPageVisibilityChange: true, // Transition style transition: 'convex', // none/fade/slide/convex/concave/zoom // Transition speed transitionSpeed: 'default', // default/fast/slow // Transition style for full page slide backgrounds backgroundTransition: 'fade', // none/fade/slide/convex/concave/zoom // Parallax background image parallaxBackgroundImage: '', // CSS syntax, e.g. "a.jpg" // Parallax background size parallaxBackgroundSize: '', // CSS syntax, e.g. "3000px 2000px" // Amount of pixels to move the parallax background per slide step parallaxBackgroundHorizontal: null, parallaxBackgroundVertical: null, // Number of slides away from the current that are visible viewDistance: 3, // Script dependencies to load dependencies: [] }, // Flags if reveal.js is loaded (has dispatched the 'ready' event) loaded = false, // Flags if the overview mode is currently active overview = false, // Holds the dimensions of our overview slides, including margins overviewSlideWidth = null, overviewSlideHeight = null, // The horizontal and vertical index of the currently active slide indexh, indexv, // The previous and current slide HTML elements previousSlide, currentSlide, previousBackground, // Slides may hold a data-state attribute which we pick up and apply // as a class to the body. This list contains the combined state of // all current slides. state = [], // The current scale of the presentation (see width/height config) scale = 1, // CSS transform that is currently applied to the slides container, // split into two groups slidesTransform = { layout: '', overview: '' }, // Cached references to DOM elements dom = {}, // Features supported by the browser, see #checkCapabilities() features = {}, // Client is a mobile device, see #checkCapabilities() isMobileDevice, // Client is a desktop Chrome, see #checkCapabilities() isChrome, // Throttles mouse wheel navigation lastMouseWheelStep = 0, // Delays updates to the URL due to a Chrome thumbnailer bug writeURLTimeout = 0, // Flags if the interaction event listeners are bound eventsAreBound = false, // The current auto-slide duration autoSlide = 0, // Auto slide properties autoSlidePlayer, autoSlideTimeout = 0, autoSlideStartTime = -1, autoSlidePaused = false, // Holds information about the currently ongoing touch input touch = { startX: 0, startY: 0, startSpan: 0, startCount: 0, captured: false, threshold: 40 }, // Holds information about the keyboard shortcuts keyboardShortcuts = { 'N , SPACE': 'Next slide', 'P': 'Previous slide', '&#8592; , H': 'Navigate left', '&#8594; , L': 'Navigate right', '&#8593; , K': 'Navigate up', '&#8595; , J': 'Navigate down', 'Home': 'First slide', 'End': 'Last slide', 'B , .': 'Pause', 'F': 'Fullscreen', 'ESC, O': 'Slide overview' }; /** * Starts up the presentation if the client is capable. */ function initialize( options ) { checkCapabilities(); if( !features.transforms2d && !features.transforms3d ) { document.body.setAttribute( 'class', 'no-transforms' ); // Since JS won't be running any further, we load all lazy // loading elements upfront var images = toArray( document.getElementsByTagName( 'img' ) ), iframes = toArray( document.getElementsByTagName( 'iframe' ) ); var lazyLoadable = images.concat( iframes ); for( var i = 0, len = lazyLoadable.length; i < len; i++ ) { var element = lazyLoadable[i]; if( element.getAttribute( 'data-src' ) ) { element.setAttribute( 'src', element.getAttribute( 'data-src' ) ); element.removeAttribute( 'data-src' ); } } // If the browser doesn't support core features we won't be // using JavaScript to control the presentation return; } // Cache references to key DOM elements dom.wrapper = document.querySelector( '.reveal' ); dom.slides = document.querySelector( '.reveal .slides' ); // Force a layout when the whole page, incl fonts, has loaded window.addEventListener( 'load', layout, false ); var query = Reveal.getQueryHash(); // Do not accept new dependencies via query config to avoid // the potential of malicious script injection if( typeof query['dependencies'] !== 'undefined' ) delete query['dependencies']; // Copy options over to our config object extend( config, options ); extend( config, query ); // Hide the address bar in mobile browsers hideAddressBar(); // Loads the dependencies and continues to #start() once done load(); } /** * Inspect the client to see what it's capable of, this * should only happens once per runtime. */ function checkCapabilities() { isMobileDevice = /(iphone|ipod|ipad|android)/gi.test( UA ); isChrome = /chrome/i.test( UA ) && !/edge/i.test( UA ); var testElement = document.createElement( 'div' ); features.transforms3d = 'WebkitPerspective' in testElement.style || 'MozPerspective' in testElement.style || 'msPerspective' in testElement.style || 'OPerspective' in testElement.style || 'perspective' in testElement.style; features.transforms2d = 'WebkitTransform' in testElement.style || 'MozTransform' in testElement.style || 'msTransform' in testElement.style || 'OTransform' in testElement.style || 'transform' in testElement.style; features.requestAnimationFrameMethod = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame; features.requestAnimationFrame = typeof features.requestAnimationFrameMethod === 'function'; features.canvas = !!document.createElement( 'canvas' ).getContext; // Transitions in the overview are disabled in desktop and // Safari due to lag features.overviewTransitions = !/Version\/[\d\.]+.*Safari/.test( UA ); // Flags if we should use zoom instead of transform to scale // up slides. Zoom produces crisper results but has a lot of // xbrowser quirks so we only use it in whitelsited browsers. features.zoom = 'zoom' in testElement.style && !isMobileDevice && ( isChrome || /Version\/[\d\.]+.*Safari/.test( UA ) ); } /** * Loads the dependencies of reveal.js. Dependencies are * defined via the configuration option 'dependencies' * and will be loaded prior to starting/binding reveal.js. * Some dependencies may have an 'async' flag, if so they * will load after reveal.js has been started up. */ function load() { var scripts = [], scriptsAsync = [], scriptsToPreload = 0; // Called once synchronous scripts finish loading function proceed() { if( scriptsAsync.length ) { // Load asynchronous scripts head.js.apply( null, scriptsAsync ); } start(); } function loadScript( s ) { head.ready( s.src.match( /([\w\d_\-]*)\.?js$|[^\\\/]*$/i )[0], function() { // Extension may contain callback functions if( typeof s.callback === 'function' ) { s.callback.apply( this ); } if( --scriptsToPreload === 0 ) { proceed(); } }); } for( var i = 0, len = config.dependencies.length; i < len; i++ ) { var s = config.dependencies[i]; // Load if there's no condition or the condition is truthy if( !s.condition || s.condition() ) { if( s.async ) { scriptsAsync.push( s.src ); } else { scripts.push( s.src ); } loadScript( s ); } } if( scripts.length ) { scriptsToPreload = scripts.length; // Load synchronous scripts head.js.apply( null, scripts ); } else { proceed(); } } /** * Starts up reveal.js by binding input events and navigating * to the current URL deeplink if there is one. */ function start() { // Make sure we've got all the DOM elements we need setupDOM(); // Listen to messages posted to this window setupPostMessage(); // Prevent the slides from being scrolled out of view setupScrollPrevention(); // Resets all vertical slides so that only the first is visible resetVerticalSlides(); // Updates the presentation to match the current configuration values configure(); // Read the initial hash readURL(); // Update all backgrounds updateBackground( true ); // Notify listeners that the presentation is ready but use a 1ms // timeout to ensure it's not fired synchronously after #initialize() setTimeout( function() { // Enable transitions now that we're loaded dom.slides.classList.remove( 'no-transition' ); loaded = true; dispatchEvent( 'ready', { 'indexh': indexh, 'indexv': indexv, 'currentSlide': currentSlide } ); }, 1 ); // Special setup and config is required when printing to PDF if( isPrintingPDF() ) { removeEventListeners(); // The document needs to have loaded for the PDF layout // measurements to be accurate if( document.readyState === 'complete' ) { setupPDF(); } else { window.addEventListener( 'load', setupPDF ); } } } /** * Finds and stores references to DOM elements which are * required by the presentation. If a required element is * not found, it is created. */ function setupDOM() { // Prevent transitions while we're loading dom.slides.classList.add( 'no-transition' ); // Background element dom.background = createSingletonNode( dom.wrapper, 'div', 'backgrounds', null ); // Progress bar dom.progress = createSingletonNode( dom.wrapper, 'div', 'progress', '<span></span>' ); dom.progressbar = dom.progress.querySelector( 'span' ); // Arrow controls createSingletonNode( dom.wrapper, 'aside', 'controls', '<button class="navigate-left" aria-label="previous slide"></button>' + '<button class="navigate-right" aria-label="next slide"></button>' + '<button class="navigate-up" aria-label="above slide"></button>' + '<button class="navigate-down" aria-label="below slide"></button>' ); // Slide number dom.slideNumber = createSingletonNode( dom.wrapper, 'div', 'slide-number', '' ); // Element containing notes that are visible to the audience dom.speakerNotes = createSingletonNode( dom.wrapper, 'div', 'speaker-notes', null ); dom.speakerNotes.setAttribute( 'data-prevent-swipe', '' ); // Overlay graphic which is displayed during the paused mode createSingletonNode( dom.wrapper, 'div', 'pause-overlay', null ); // Cache references to elements dom.controls = document.querySelector( '.reveal .controls' ); dom.theme = document.querySelector( '#theme' ); dom.wrapper.setAttribute( 'role', 'application' ); // There can be multiple instances of controls throughout the page dom.controlsLeft = toArray( document.querySelectorAll( '.navigate-left' ) ); dom.controlsRight = toArray( document.querySelectorAll( '.navigate-right' ) ); dom.controlsUp = toArray( document.querySelectorAll( '.navigate-up' ) ); dom.controlsDown = toArray( document.querySelectorAll( '.navigate-down' ) ); dom.controlsPrev = toArray( document.querySelectorAll( '.navigate-prev' ) ); dom.controlsNext = toArray( document.querySelectorAll( '.navigate-next' ) ); dom.statusDiv = createStatusDiv(); } /** * Creates a hidden div with role aria-live to announce the * current slide content. Hide the div off-screen to make it * available only to Assistive Technologies. */ function createStatusDiv() { var statusDiv = document.getElementById( 'aria-status-div' ); if( !statusDiv ) { statusDiv = document.createElement( 'div' ); statusDiv.style.position = 'absolute'; statusDiv.style.height = '1px'; statusDiv.style.width = '1px'; statusDiv.style.overflow ='hidden'; statusDiv.style.clip = 'rect( 1px, 1px, 1px, 1px )'; statusDiv.setAttribute( 'id', 'aria-status-div' ); statusDiv.setAttribute( 'aria-live', 'polite' ); statusDiv.setAttribute( 'aria-atomic','true' ); dom.wrapper.appendChild( statusDiv ); } return statusDiv; } /** * Configures the presentation for printing to a static * PDF. */ function setupPDF() { var slideSize = getComputedSlideSize( window.innerWidth, window.innerHeight ); // Dimensions of the PDF pages var pageWidth = Math.floor( slideSize.width * ( 1 + config.margin ) ), pageHeight = Math.floor( slideSize.height * ( 1 + config.margin ) ); // Dimensions of slides within the pages var slideWidth = slideSize.width, slideHeight = slideSize.height; // Let the browser know what page size we want to print injectStyleSheet( '@page{size:'+ pageWidth +'px '+ pageHeight +'px; margin: 0;}' ); // Limit the size of certain elements to the dimensions of the slide injectStyleSheet( '.reveal section>img, .reveal section>video, .reveal section>iframe{max-width: '+ slideWidth +'px; max-height:'+ slideHeight +'px}' ); document.body.classList.add( 'print-pdf' ); document.body.style.width = pageWidth + 'px'; document.body.style.height = pageHeight + 'px'; // Add each slide's index as attributes on itself, we need these // indices to generate slide numbers below toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( hslide, h ) { hslide.setAttribute( 'data-index-h', h ); if( hslide.classList.contains( 'stack' ) ) { toArray( hslide.querySelectorAll( 'section' ) ).forEach( function( vslide, v ) { vslide.setAttribute( 'data-index-h', h ); vslide.setAttribute( 'data-index-v', v ); } ); } } ); // Slide and slide background layout toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) { // Vertical stacks are not centred since their section // children will be if( slide.classList.contains( 'stack' ) === false ) { // Center the slide inside of the page, giving the slide some margin var left = ( pageWidth - slideWidth ) / 2, top = ( pageHeight - slideHeight ) / 2; var contentHeight = getAbsoluteHeight( slide ); var numberOfPages = Math.max( Math.ceil( contentHeight / pageHeight ), 1 ); // Center slides vertically if( numberOfPages === 1 && config.center || slide.classList.contains( 'center' ) ) { top = Math.max( ( pageHeight - contentHeight ) / 2, 0 ); } // Position the slide inside of the page slide.style.left = left + 'px'; slide.style.top = top + 'px'; slide.style.width = slideWidth + 'px'; // TODO Backgrounds need to be multiplied when the slide // stretches over multiple pages var background = slide.querySelector( '.slide-background' ); if( background ) { background.style.width = pageWidth + 'px'; background.style.height = ( pageHeight * numberOfPages ) + 'px'; background.style.top = -top + 'px'; background.style.left = -left + 'px'; } // Inject notes if `showNotes` is enabled if( config.showNotes ) { var notes = getSlideNotes( slide ); if( notes ) { var notesSpacing = 8; var notesElement = document.createElement( 'div' ); notesElement.classList.add( 'speaker-notes' ); notesElement.classList.add( 'speaker-notes-pdf' ); notesElement.innerHTML = notes; notesElement.style.left = ( notesSpacing - left ) + 'px'; notesElement.style.bottom = ( notesSpacing - top ) + 'px'; notesElement.style.width = ( pageWidth - notesSpacing*2 ) + 'px'; slide.appendChild( notesElement ); } } // Inject slide numbers if `slideNumbers` are enabled if( config.slideNumber ) { var slideNumberH = parseInt( slide.getAttribute( 'data-index-h' ), 10 ) + 1, slideNumberV = parseInt( slide.getAttribute( 'data-index-v' ), 10 ) + 1; var numberElement = document.createElement( 'div' ); numberElement.classList.add( 'slide-number' ); numberElement.classList.add( 'slide-number-pdf' ); numberElement.innerHTML = formatSlideNumber( slideNumberH, '.', slideNumberV ); background.appendChild( numberElement ); } } } ); // Show all fragments toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' .fragment' ) ).forEach( function( fragment ) { fragment.classList.add( 'visible' ); } ); } /** * This is an unfortunate necessity. Some actions – such as * an input field being focused in an iframe or using the * keyboard to expand text selection beyond the bounds of * a slide – can trigger our content to be pushed out of view. * This scrolling can not be prevented by hiding overflow in * CSS (we already do) so we have to resort to repeatedly * checking if the slides have been offset :( */ function setupScrollPrevention() { setInterval( function() { if( dom.wrapper.scrollTop !== 0 || dom.wrapper.scrollLeft !== 0 ) { dom.wrapper.scrollTop = 0; dom.wrapper.scrollLeft = 0; } }, 1000 ); } /** * Creates an HTML element and returns a reference to it. * If the element already exists the existing instance will * be returned. */ function createSingletonNode( container, tagname, classname, innerHTML ) { // Find all nodes matching the description var nodes = container.querySelectorAll( '.' + classname ); // Check all matches to find one which is a direct child of // the specified container for( var i = 0; i < nodes.length; i++ ) { var testNode = nodes[i]; if( testNode.parentNode === container ) { return testNode; } } // If no node was found, create it now var node = document.createElement( tagname ); node.classList.add( classname ); if( typeof innerHTML === 'string' ) { node.innerHTML = innerHTML; } container.appendChild( node ); return node; } /** * Creates the slide background elements and appends them * to the background container. One element is created per * slide no matter if the given slide has visible background. */ function createBackgrounds() { var printMode = isPrintingPDF(); // Clear prior backgrounds dom.background.innerHTML = ''; dom.background.classList.add( 'no-transition' ); // Iterate over all horizontal slides toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( slideh ) { var backgroundStack; if( printMode ) { backgroundStack = createBackground( slideh, slideh ); } else { backgroundStack = createBackground( slideh, dom.background ); } // Iterate over all vertical slides toArray( slideh.querySelectorAll( 'section' ) ).forEach( function( slidev ) { if( printMode ) { createBackground( slidev, slidev ); } else { createBackground( slidev, backgroundStack ); } backgroundStack.classList.add( 'stack' ); } ); } ); // Add parallax background if specified if( config.parallaxBackgroundImage ) { dom.background.style.backgroundImage = 'url("' + config.parallaxBackgroundImage + '")'; dom.background.style.backgroundSize = config.parallaxBackgroundSize; // Make sure the below properties are set on the element - these properties are // needed for proper transitions to be set on the element via CSS. To remove // annoying background slide-in effect when the presentation starts, apply // these properties after short time delay setTimeout( function() { dom.wrapper.classList.add( 'has-parallax-background' ); }, 1 ); } else { dom.background.style.backgroundImage = ''; dom.wrapper.classList.remove( 'has-parallax-background' ); } } /** * Creates a background for the given slide. * * @param {HTMLElement} slide * @param {HTMLElement} container The element that the background * should be appended to */ function createBackground( slide, container ) { var data = { background: slide.getAttribute( 'data-background' ), backgroundSize: slide.getAttribute( 'data-background-size' ), backgroundImage: slide.getAttribute( 'data-background-image' ), backgroundVideo: slide.getAttribute( 'data-background-video' ), backgroundIframe: slide.getAttribute( 'data-background-iframe' ), backgroundColor: slide.getAttribute( 'data-background-color' ), backgroundRepeat: slide.getAttribute( 'data-background-repeat' ), backgroundPosition: slide.getAttribute( 'data-background-position' ), backgroundTransition: slide.getAttribute( 'data-background-transition' ) }; var element = document.createElement( 'div' ); // Carry over custom classes from the slide to the background element.className = 'slide-background ' + slide.className.replace( /present|past|future/, '' ); if( data.background ) { // Auto-wrap image urls in url(...) if( /^(http|file|\/\/)/gi.test( data.background ) || /\.(svg|png|jpg|jpeg|gif|bmp)$/gi.test( data.background ) ) { slide.setAttribute( 'data-background-image', data.background ); } else { element.style.background = data.background; } } // Create a hash for this combination of background settings. // This is used to determine when two slide backgrounds are // the same. if( data.background || data.backgroundColor || data.backgroundImage || data.backgroundVideo || data.backgroundIframe ) { element.setAttribute( 'data-background-hash', data.background + data.backgroundSize + data.backgroundImage + data.backgroundVideo + data.backgroundIframe + data.backgroundColor + data.backgroundRepeat + data.backgroundPosition + data.backgroundTransition ); } // Additional and optional background properties if( data.backgroundSize ) element.style.backgroundSize = data.backgroundSize; if( data.backgroundColor ) element.style.backgroundColor = data.backgroundColor; if( data.backgroundRepeat ) element.style.backgroundRepeat = data.backgroundRepeat; if( data.backgroundPosition ) element.style.backgroundPosition = data.backgroundPosition; if( data.backgroundTransition ) element.setAttribute( 'data-background-transition', data.backgroundTransition ); container.appendChild( element ); // If backgrounds are being recreated, clear old classes slide.classList.remove( 'has-dark-background' ); slide.classList.remove( 'has-light-background' ); // If this slide has a background color, add a class that // signals if it is light or dark. If the slide has no background // color, no class will be set var computedBackgroundColor = window.getComputedStyle( element ).backgroundColor; if( computedBackgroundColor ) { var rgb = colorToRgb( computedBackgroundColor ); // Ignore fully transparent backgrounds. Some browsers return // rgba(0,0,0,0) when reading the computed background color of // an element with no background if( rgb && rgb.a !== 0 ) { if( colorBrightness( computedBackgroundColor ) < 128 ) { slide.classList.add( 'has-dark-background' ); } else { slide.classList.add( 'has-light-background' ); } } } return element; } /** * Registers a listener to postMessage events, this makes it * possible to call all reveal.js API methods from another * window. For example: * * revealWindow.postMessage( JSON.stringify({ * method: 'slide', * args: [ 2 ] * }), '*' ); */ function setupPostMessage() { if( config.postMessage ) { window.addEventListener( 'message', function ( event ) { var data = event.data; // Make sure we're dealing with JSON if( typeof data === 'string' && data.charAt( 0 ) === '{' && data.charAt( data.length - 1 ) === '}' ) { data = JSON.parse( data ); // Check if the requested method can be found if( data.method && typeof Reveal[data.method] === 'function' ) { Reveal[data.method].apply( Reveal, data.args ); } } }, false ); } } /** * Applies the configuration settings from the config * object. May be called multiple times. */ function configure( options ) { var numberOfSlides = dom.wrapper.querySelectorAll( SLIDES_SELECTOR ).length; dom.wrapper.classList.remove( config.transition ); // New config options may be passed when this method // is invoked through the API after initialization if( typeof options === 'object' ) extend( config, options ); // Force linear transition based on browser capabilities if( features.transforms3d === false ) config.transition = 'linear'; dom.wrapper.classList.add( config.transition ); dom.wrapper.setAttribute( 'data-transition-speed', config.transitionSpeed ); dom.wrapper.setAttribute( 'data-background-transition', config.backgroundTransition ); dom.controls.style.display = config.controls ? 'block' : 'none'; dom.progress.style.display = config.progress ? 'block' : 'none'; dom.slideNumber.style.display = config.slideNumber && !isPrintingPDF() ? 'block' : 'none'; if( config.shuffle ) { shuffle(); } if( config.rtl ) { dom.wrapper.classList.add( 'rtl' ); } else { dom.wrapper.classList.remove( 'rtl' ); } if( config.center ) { dom.wrapper.classList.add( 'center' ); } else { dom.wrapper.classList.remove( 'center' ); } // Exit the paused mode if it was configured off if( config.pause === false ) { resume(); } if( config.showNotes ) { dom.speakerNotes.classList.add( 'visible' ); } else { dom.speakerNotes.classList.remove( 'visible' ); } if( config.mouseWheel ) { document.addEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF document.addEventListener( 'mousewheel', onDocumentMouseScroll, false ); } else { document.removeEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF document.removeEventListener( 'mousewheel', onDocumentMouseScroll, false ); } // Rolling 3D links if( config.rollingLinks ) { enableRollingLinks(); } else { disableRollingLinks(); } // Iframe link previews if( config.previewLinks ) { enablePreviewLinks(); } else { disablePreviewLinks(); enablePreviewLinks( '[data-preview-link]' ); } // Remove existing auto-slide controls if( autoSlidePlayer ) { autoSlidePlayer.destroy(); autoSlidePlayer = null; } // Generate auto-slide controls if needed if( numberOfSlides > 1 && config.autoSlide && config.autoSlideStoppable && features.canvas && features.requestAnimationFrame ) { autoSlidePlayer = new Playback( dom.wrapper, function() { return Math.min( Math.max( ( Date.now() - autoSlideStartTime ) / autoSlide, 0 ), 1 ); } ); autoSlidePlayer.on( 'click', onAutoSlidePlayerClick ); autoSlidePaused = false; } // When fragments are turned off they should be visible if( config.fragments === false ) { toArray( dom.slides.querySelectorAll( '.fragment' ) ).forEach( function( element ) { element.classList.add( 'visible' ); element.classList.remove( 'current-fragment' ); } ); } sync(); } /** * Binds all event listeners. */ function addEventListeners() { eventsAreBound = true; window.addEventListener( 'hashchange', onWindowHashChange, false ); window.addEventListener( 'resize', onWindowResize, false ); if( config.touch ) { dom.wrapper.addEventListener( 'touchstart', onTouchStart, false ); dom.wrapper.addEventListener( 'touchmove', onTouchMove, false ); dom.wrapper.addEventListener( 'touchend', onTouchEnd, false ); // Support pointer-style touch interaction as well if( window.navigator.pointerEnabled ) { // IE 11 uses un-prefixed version of pointer events dom.wrapper.addEventListener( 'pointerdown', onPointerDown, false ); dom.wrapper.addEventListener( 'pointermove', onPointerMove, false ); dom.wrapper.addEventListener( 'pointerup', onPointerUp, false ); } else if( window.navigator.msPointerEnabled ) { // IE 10 uses prefixed version of pointer events dom.wrapper.addEventListener( 'MSPointerDown', onPointerDown, false ); dom.wrapper.addEventListener( 'MSPointerMove', onPointerMove, false ); dom.wrapper.addEventListener( 'MSPointerUp', onPointerUp, false ); } } if( config.keyboard ) { document.addEventListener( 'keydown', onDocumentKeyDown, false ); document.addEventListener( 'keypress', onDocumentKeyPress, false ); } if( config.progress && dom.progress ) { dom.progress.addEventListener( 'click', onProgressClicked, false ); } if( config.focusBodyOnPageVisibilityChange ) { var visibilityChange; if( 'hidden' in document ) { visibilityChange = 'visibilitychange'; } else if( 'msHidden' in document ) { visibilityChange = 'msvisibilitychange'; } else if( 'webkitHidden' in document ) { visibilityChange = 'webkitvisibilitychange'; } if( visibilityChange ) { document.addEventListener( visibilityChange, onPageVisibilityChange, false ); } } // Listen to both touch and click events, in case the device // supports both var pointerEvents = [ 'touchstart', 'click' ]; // Only support touch for Android, fixes double navigations in // stock browser if( UA.match( /android/gi ) ) { pointerEvents = [ 'touchstart' ]; } pointerEvents.forEach( function( eventName ) { dom.controlsLeft.forEach( function( el ) { el.addEventListener( eventName, onNavigateLeftClicked, false ); } ); dom.controlsRight.forEach( function( el ) { el.addEventListener( eventName, onNavigateRightClicked, false ); } ); dom.controlsUp.forEach( function( el ) { el.addEventListener( eventName, onNavigateUpClicked, false ); } ); dom.controlsDown.forEach( function( el ) { el.addEventListener( eventName, onNavigateDownClicked, false ); } ); dom.controlsPrev.forEach( function( el ) { el.addEventListener( eventName, onNavigatePrevClicked, false ); } ); dom.controlsNext.forEach( function( el ) { el.addEventListener( eventName, onNavigateNextClicked, false ); } ); } ); } /** * Unbinds all event listeners. */ function removeEventListeners() { eventsAreBound = false; document.removeEventListener( 'keydown', onDocumentKeyDown, false ); document.removeEventListener( 'keypress', onDocumentKeyPress, false ); window.removeEventListener( 'hashchange', onWindowHashChange, false ); window.removeEventListener( 'resize', onWindowResize, false ); dom.wrapper.removeEventListener( 'touchstart', onTouchStart, false ); dom.wrapper.removeEventListener( 'touchmove', onTouchMove, false ); dom.wrapper.removeEventListener( 'touchend', onTouchEnd, false ); // IE11 if( window.navigator.pointerEnabled ) { dom.wrapper.removeEventListener( 'pointerdown', onPointerDown, false ); dom.wrapper.removeEventListener( 'pointermove', onPointerMove, false ); dom.wrapper.removeEventListener( 'pointerup', onPointerUp, false ); } // IE10 else if( window.navigator.msPointerEnabled ) { dom.wrapper.removeEventListener( 'MSPointerDown', onPointerDown, false ); dom.wrapper.removeEventListener( 'MSPointerMove', onPointerMove, false ); dom.wrapper.removeEventListener( 'MSPointerUp', onPointerUp, false ); } if ( config.progress && dom.progress ) { dom.progress.removeEventListener( 'click', onProgressClicked, false ); } [ 'touchstart', 'click' ].forEach( function( eventName ) { dom.controlsLeft.forEach( function( el ) { el.removeEventListener( eventName, onNavigateLeftClicked, false ); } ); dom.controlsRight.forEach( function( el ) { el.removeEventListener( eventName, onNavigateRightClicked, false ); } ); dom.controlsUp.forEach( function( el ) { el.removeEventListener( eventName, onNavigateUpClicked, false ); } ); dom.controlsDown.forEach( function( el ) { el.removeEventListener( eventName, onNavigateDownClicked, false ); } ); dom.controlsPrev.forEach( function( el ) { el.removeEventListener( eventName, onNavigatePrevClicked, false ); } ); dom.controlsNext.forEach( function( el ) { el.removeEventListener( eventName, onNavigateNextClicked, false ); } ); } ); } /** * Extend object a with the properties of object b. * If there's a conflict, object b takes precedence. */ function extend( a, b ) { for( var i in b ) { a[ i ] = b[ i ]; } } /** * Converts the target object to an array. */ function toArray( o ) { return Array.prototype.slice.call( o ); } /** * Utility for deserializing a value. */ function deserialize( value ) { if( typeof value === 'string' ) { if( value === 'null' ) return null; else if( value === 'true' ) return true; else if( value === 'false' ) return false; else if( value.match( /^\d+$/ ) ) return parseFloat( value ); } return value; } /** * Measures the distance in pixels between point a * and point b. * * @param {Object} a point with x/y properties * @param {Object} b point with x/y properties */ function distanceBetween( a, b ) { var dx = a.x - b.x, dy = a.y - b.y; return Math.sqrt( dx*dx + dy*dy ); } /** * Applies a CSS transform to the target element. */ function transformElement( element, transform ) { element.style.WebkitTransform = transform; element.style.MozTransform = transform; element.style.msTransform = transform; element.style.transform = transform; } /** * Applies CSS transforms to the slides container. The container * is transformed from two separate sources: layout and the overview * mode. */ function transformSlides( transforms ) { // Pick up new transforms from arguments if( typeof transforms.layout === 'string' ) slidesTransform.layout = transforms.layout; if( typeof transforms.overview === 'string' ) slidesTransform.overview = transforms.overview; // Apply the transforms to the slides container if( slidesTransform.layout ) { transformElement( dom.slides, slidesTransform.layout + ' ' + slidesTransform.overview ); } else { transformElement( dom.slides, slidesTransform.overview ); } } /** * Injects the given CSS styles into the DOM. */ function injectStyleSheet( value ) { var tag = document.createElement( 'style' ); tag.type = 'text/css'; if( tag.styleSheet ) { tag.styleSheet.cssText = value; } else { tag.appendChild( document.createTextNode( value ) ); } document.getElementsByTagName( 'head' )[0].appendChild( tag ); } /** * Converts various color input formats to an {r:0,g:0,b:0} object. * * @param {String} color The string representation of a color, * the following formats are supported: * - #000 * - #000000 * - rgb(0,0,0) */ function colorToRgb( color ) { var hex3 = color.match( /^#([0-9a-f]{3})$/i ); if( hex3 && hex3[1] ) { hex3 = hex3[1]; return { r: parseInt( hex3.charAt( 0 ), 16 ) * 0x11, g: parseInt( hex3.charAt( 1 ), 16 ) * 0x11, b: parseInt( hex3.charAt( 2 ), 16 ) * 0x11 }; } var hex6 = color.match( /^#([0-9a-f]{6})$/i ); if( hex6 && hex6[1] ) { hex6 = hex6[1]; return { r: parseInt( hex6.substr( 0, 2 ), 16 ), g: parseInt( hex6.substr( 2, 2 ), 16 ), b: parseInt( hex6.substr( 4, 2 ), 16 ) }; } var rgb = color.match( /^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i ); if( rgb ) { return { r: parseInt( rgb[1], 10 ), g: parseInt( rgb[2], 10 ), b: parseInt( rgb[3], 10 ) }; } var rgba = color.match( /^rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\,\s*([\d]+|[\d]*.[\d]+)\s*\)$/i ); if( rgba ) { return { r: parseInt( rgba[1], 10 ), g: parseInt( rgba[2], 10 ), b: parseInt( rgba[3], 10 ), a: parseFloat( rgba[4] ) }; } return null; } /** * Calculates brightness on a scale of 0-255. * * @param color See colorStringToRgb for supported formats. */ function colorBrightness( color ) { if( typeof color === 'string' ) color = colorToRgb( color ); if( color ) { return ( color.r * 299 + color.g * 587 + color.b * 114 ) / 1000; } return null; } /** * Retrieves the height of the given element by looking * at the position and height of its immediate children. */ function getAbsoluteHeight( element ) { var height = 0; if( element ) { var absoluteChildren = 0; toArray( element.childNodes ).forEach( function( child ) { if( typeof child.offsetTop === 'number' && child.style ) { // Count # of abs children if( window.getComputedStyle( child ).position === 'absolute' ) { absoluteChildren += 1; } height = Math.max( height, child.offsetTop + child.offsetHeight ); } } ); // If there are no absolute children, use offsetHeight if( absoluteChildren === 0 ) { height = element.offsetHeight; } } return height; } /** * Returns the remaining height within the parent of the * target element. * * remaining height = [ configured parent height ] - [ current parent height ] */ function getRemainingHeight( element, height ) { height = height || 0; if( element ) { var newHeight, oldHeight = element.style.height; // Change the .stretch element height to 0 in order find the height of all // the other elements element.style.height = '0px'; newHeight = height - element.parentNode.offsetHeight; // Restore the old height, just in case element.style.height = oldHeight + 'px'; return newHeight; } return height; } /** * Checks if this instance is being used to print a PDF. */ function isPrintingPDF() { return ( /print-pdf/gi ).test( window.location.search ); } /** * Hides the address bar if we're on a mobile device. */ function hideAddressBar() { if( config.hideAddressBar && isMobileDevice ) { // Events that should trigger the address bar to hide window.addEventListener( 'load', removeAddressBar, false ); window.addEventListener( 'orientationchange', removeAddressBar, false ); } } /** * Causes the address bar to hide on mobile devices, * more vertical space ftw. */ function removeAddressBar() { setTimeout( function() { window.scrollTo( 0, 1 ); }, 10 ); } /** * Dispatches an event of the specified type from the * reveal DOM element. */ function dispatchEvent( type, args ) { var event = document.createEvent( 'HTMLEvents', 1, 2 ); event.initEvent( type, true, true ); extend( event, args ); dom.wrapper.dispatchEvent( event ); // If we're in an iframe, post each reveal.js event to the // parent window. Used by the notes plugin if( config.postMessageEvents && window.parent !== window.self ) { window.parent.postMessage( JSON.stringify({ namespace: 'reveal', eventName: type, state: getState() }), '*' ); } } /** * Wrap all links in 3D goodness. */ function enableRollingLinks() { if( features.transforms3d && !( 'msPerspective' in document.body.style ) ) { var anchors = dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' a' ); for( var i = 0, len = anchors.length; i < len; i++ ) { var anchor = anchors[i]; if( anchor.textContent && !anchor.querySelector( '*' ) && ( !anchor.className || !anchor.classList.contains( anchor, 'roll' ) ) ) { var span = document.createElement('span'); span.setAttribute('data-title', anchor.text); span.innerHTML = anchor.innerHTML; anchor.classList.add( 'roll' ); anchor.innerHTML = ''; anchor.appendChild(span); } } } } /** * Unwrap all 3D links. */ function disableRollingLinks() { var anchors = dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' a.roll' ); for( var i = 0, len = anchors.length; i < len; i++ ) { var anchor = anchors[i]; var span = anchor.querySelector( 'span' ); if( span ) { anchor.classList.remove( 'roll' ); anchor.innerHTML = span.innerHTML; } } } /** * Bind preview frame links. */ function enablePreviewLinks( selector ) { var anchors = toArray( document.querySelectorAll( selector ? selector : 'a' ) ); anchors.forEach( function( element ) { if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) { element.addEventListener( 'click', onPreviewLinkClicked, false ); } } ); } /** * Unbind preview frame links. */ function disablePreviewLinks() { var anchors = toArray( document.querySelectorAll( 'a' ) ); anchors.forEach( function( element ) { if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) { element.removeEventListener( 'click', onPreviewLinkClicked, false ); } } ); } /** * Opens a preview window for the target URL. */ function showPreview( url ) { closeOverlay(); dom.overlay = document.createElement( 'div' ); dom.overlay.classList.add( 'overlay' ); dom.overlay.classList.add( 'overlay-preview' ); dom.wrapper.appendChild( dom.overlay ); dom.overlay.innerHTML = [ '<header>', '<a class="close" href="#"><span class="icon"></span></a>', '<a class="external" href="'+ url +'" target="_blank"><span class="icon"></span></a>', '</header>', '<div class="spinner"></div>', '<div class="viewport">', '<iframe src="'+ url +'"></iframe>', '</div>' ].join(''); dom.overlay.querySelector( 'iframe' ).addEventListener( 'load', function( event ) { dom.overlay.classList.add( 'loaded' ); }, false ); dom.overlay.querySelector( '.close' ).addEventListener( 'click', function( event ) { closeOverlay(); event.preventDefault(); }, false ); dom.overlay.querySelector( '.external' ).addEventListener( 'click', function( event ) { closeOverlay(); }, false ); setTimeout( function() { dom.overlay.classList.add( 'visible' ); }, 1 ); } /** * Opens a overlay window with help material. */ function showHelp() { if( config.help ) { closeOverlay(); dom.overlay = document.createElement( 'div' ); dom.overlay.classList.add( 'overlay' ); dom.overlay.classList.add( 'overlay-help' ); dom.wrapper.appendChild( dom.overlay ); var html = '<p class="title">Keyboard Shortcuts</p><br/>'; html += '<table><th>KEY</th><th>ACTION</th>'; for( var key in keyboardShortcuts ) { html += '<tr><td>' + key + '</td><td>' + keyboardShortcuts[ key ] + '</td></tr>'; } html += '</table>'; dom.overlay.innerHTML = [ '<header>', '<a class="close" href="#"><span class="icon"></span></a>', '</header>', '<div class="viewport">', '<div class="viewport-inner">'+ html +'</div>', '</div>' ].join(''); dom.overlay.querySelector( '.close' ).addEventListener( 'click', function( event ) { closeOverlay(); event.preventDefault(); }, false ); setTimeout( function() { dom.overlay.classList.add( 'visible' ); }, 1 ); } } /** * Closes any currently open overlay. */ function closeOverlay() { if( dom.overlay ) { dom.overlay.parentNode.removeChild( dom.overlay ); dom.overlay = null; } } /** * Applies JavaScript-controlled layout rules to the * presentation. */ function layout() { if( dom.wrapper && !isPrintingPDF() ) { var size = getComputedSlideSize(); var slidePadding = 20; // TODO Dig this out of DOM // Layout the contents of the slides layoutSlideContents( config.width, config.height, slidePadding ); dom.slides.style.width = size.width + 'px'; dom.slides.style.height = size.height + 'px'; // Determine scale of content to fit within available space scale = Math.min( size.presentationWidth / size.width, size.presentationHeight / size.height ); // Respect max/min scale settings scale = Math.max( scale, config.minScale ); scale = Math.min( scale, config.maxScale ); // Don't apply any scaling styles if scale is 1 if( scale === 1 ) { dom.slides.style.zoom = ''; dom.slides.style.left = ''; dom.slides.style.top = ''; dom.slides.style.bottom = ''; dom.slides.style.right = ''; transformSlides( { layout: '' } ); } else { // Prefer zoom for scaling up so that content remains crisp. // Don't use zoom to scale down since that can lead to shifts // in text layout/line breaks. if( scale > 1 && features.zoom ) { dom.slides.style.zoom = scale; dom.slides.style.left = ''; dom.slides.style.top = ''; dom.slides.style.bottom = ''; dom.slides.style.right = ''; transformSlides( { layout: '' } ); } // Apply scale transform as a fallback else { dom.slides.style.zoom = ''; dom.slides.style.left = '50%'; dom.slides.style.top = '50%'; dom.slides.style.bottom = 'auto'; dom.slides.style.right = 'auto'; transformSlides( { layout: 'translate(-50%, -50%) scale('+ scale +')' } ); } } // Select all slides, vertical and horizontal var slides = toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ); for( var i = 0, len = slides.length; i < len; i++ ) { var slide = slides[ i ]; // Don't bother updating invisible slides if( slide.style.display === 'none' ) { continue; } if( config.center || slide.classList.contains( 'center' ) ) { // Vertical stacks are not centred since their section // children will be if( slide.classList.contains( 'stack' ) ) { slide.style.top = 0; } else { slide.style.top = Math.max( ( ( size.height - getAbsoluteHeight( slide ) ) / 2 ) - slidePadding, 0 ) + 'px'; } } else { slide.style.top = ''; } } updateProgress(); updateParallax(); } } /** * Applies layout logic to the contents of all slides in * the presentation. */ function layoutSlideContents( width, height, padding ) { // Handle sizing of elements with the 'stretch' class toArray( dom.slides.querySelectorAll( 'section > .stretch' ) ).forEach( function( element ) { // Determine how much vertical space we can use var remainingHeight = getRemainingHeight( element, height ); // Consider the aspect ratio of media elements if( /(img|video)/gi.test( element.nodeName ) ) { var nw = element.naturalWidth || element.videoWidth, nh = element.naturalHeight || element.videoHeight; var es = Math.min( width / nw, remainingHeight / nh ); element.style.width = ( nw * es ) + 'px'; element.style.height = ( nh * es ) + 'px'; } else { element.style.width = width + 'px'; element.style.height = remainingHeight + 'px'; } } ); } /** * Calculates the computed pixel size of our slides. These * values are based on the width and height configuration * options. */ function getComputedSlideSize( presentationWidth, presentationHeight ) { var size = { // Slide size width: config.width, height: config.height, // Presentation size presentationWidth: presentationWidth || dom.wrapper.offsetWidth, presentationHeight: presentationHeight || dom.wrapper.offsetHeight }; // Reduce available space by margin size.presentationWidth -= ( size.presentationWidth * config.margin ); size.presentationHeight -= ( size.presentationHeight * config.margin ); // Slide width may be a percentage of available width if( typeof size.width === 'string' && /%$/.test( size.width ) ) { size.width = parseInt( size.width, 10 ) / 100 * size.presentationWidth; } // Slide height may be a percentage of available height if( typeof size.height === 'string' && /%$/.test( size.height ) ) { size.height = parseInt( size.height, 10 ) / 100 * size.presentationHeight; } return size; } /** * Stores the vertical index of a stack so that the same * vertical slide can be selected when navigating to and * from the stack. * * @param {HTMLElement} stack The vertical stack element * @param {int} v Index to memorize */ function setPreviousVerticalIndex( stack, v ) { if( typeof stack === 'object' && typeof stack.setAttribute === 'function' ) { stack.setAttribute( 'data-previous-indexv', v || 0 ); } } /** * Retrieves the vertical index which was stored using * #setPreviousVerticalIndex() or 0 if no previous index * exists. * * @param {HTMLElement} stack The vertical stack element */ function getPreviousVerticalIndex( stack ) { if( typeof stack === 'object' && typeof stack.setAttribute === 'function' && stack.classList.contains( 'stack' ) ) { // Prefer manually defined start-indexv var attributeName = stack.hasAttribute( 'data-start-indexv' ) ? 'data-start-indexv' : 'data-previous-indexv'; return parseInt( stack.getAttribute( attributeName ) || 0, 10 ); } return 0; } /** * Displays the overview of slides (quick nav) by scaling * down and arranging all slide elements. */ function activateOverview() { // Only proceed if enabled in config if( config.overview && !isOverview() ) { overview = true; dom.wrapper.classList.add( 'overview' ); dom.wrapper.classList.remove( 'overview-deactivating' ); if( features.overviewTransitions ) { setTimeout( function() { dom.wrapper.classList.add( 'overview-animated' ); }, 1 ); } // Don't auto-slide while in overview mode cancelAutoSlide(); // Move the backgrounds element into the slide container to // that the same scaling is applied dom.slides.appendChild( dom.background ); // Clicking on an overview slide navigates to it toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) { if( !slide.classList.contains( 'stack' ) ) { slide.addEventListener( 'click', onOverviewSlideClicked, true ); } } ); // Calculate slide sizes var margin = 70; var slideSize = getComputedSlideSize(); overviewSlideWidth = slideSize.width + margin; overviewSlideHeight = slideSize.height + margin; // Reverse in RTL mode if( config.rtl ) { overviewSlideWidth = -overviewSlideWidth; } updateSlidesVisibility(); layoutOverview(); updateOverview(); layout(); // Notify observers of the overview showing dispatchEvent( 'overviewshown', { 'indexh': indexh, 'indexv': indexv, 'currentSlide': currentSlide } ); } } /** * Uses CSS transforms to position all slides in a grid for * display inside of the overview mode. */ function layoutOverview() { // Layout slides toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( hslide, h ) { hslide.setAttribute( 'data-index-h', h ); transformElement( hslide, 'translate3d(' + ( h * overviewSlideWidth ) + 'px, 0, 0)' ); if( hslide.classList.contains( 'stack' ) ) { toArray( hslide.querySelectorAll( 'section' ) ).forEach( function( vslide, v ) { vslide.setAttribute( 'data-index-h', h ); vslide.setAttribute( 'data-index-v', v ); transformElement( vslide, 'translate3d(0, ' + ( v * overviewSlideHeight ) + 'px, 0)' ); } ); } } ); // Layout slide backgrounds toArray( dom.background.childNodes ).forEach( function( hbackground, h ) { transformElement( hbackground, 'translate3d(' + ( h * overviewSlideWidth ) + 'px, 0, 0)' ); toArray( hbackground.querySelectorAll( '.slide-background' ) ).forEach( function( vbackground, v ) { transformElement( vbackground, 'translate3d(0, ' + ( v * overviewSlideHeight ) + 'px, 0)' ); } ); } ); } /** * Moves the overview viewport to the current slides. * Called each time the current slide changes. */ function updateOverview() { transformSlides( { overview: [ 'translateX('+ ( -indexh * overviewSlideWidth ) +'px)', 'translateY('+ ( -indexv * overviewSlideHeight ) +'px)', 'translateZ('+ ( window.innerWidth < 400 ? -1000 : -2500 ) +'px)' ].join( ' ' ) } ); } /** * Exits the slide overview and enters the currently * active slide. */ function deactivateOverview() { // Only proceed if enabled in config if( config.overview ) { overview = false; dom.wrapper.classList.remove( 'overview' ); dom.wrapper.classList.remove( 'overview-animated' ); // Temporarily add a class so that transitions can do different things // depending on whether they are exiting/entering overview, or just // moving from slide to slide dom.wrapper.classList.add( 'overview-deactivating' ); setTimeout( function () { dom.wrapper.classList.remove( 'overview-deactivating' ); }, 1 ); // Move the background element back out dom.wrapper.appendChild( dom.background ); // Clean up changes made to slides toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) { transformElement( slide, '' ); slide.removeEventListener( 'click', onOverviewSlideClicked, true ); } ); // Clean up changes made to backgrounds toArray( dom.background.querySelectorAll( '.slide-background' ) ).forEach( function( background ) { transformElement( background, '' ); } ); transformSlides( { overview: '' } ); slide( indexh, indexv ); layout(); cueAutoSlide(); // Notify observers of the overview hiding dispatchEvent( 'overviewhidden', { 'indexh': indexh, 'indexv': indexv, 'currentSlide': currentSlide } ); } } /** * Toggles the slide overview mode on and off. * * @param {Boolean} override Optional flag which overrides the * toggle logic and forcibly sets the desired state. True means * overview is open, false means it's closed. */ function toggleOverview( override ) { if( typeof override === 'boolean' ) { override ? activateOverview() : deactivateOverview(); } else { isOverview() ? deactivateOverview() : activateOverview(); } } /** * Checks if the overview is currently active. * * @return {Boolean} true if the overview is active, * false otherwise */ function isOverview() { return overview; } /** * Checks if the current or specified slide is vertical * (nested within another slide). * * @param {HTMLElement} slide [optional] The slide to check * orientation of */ function isVerticalSlide( slide ) { // Prefer slide argument, otherwise use current slide slide = slide ? slide : currentSlide; return slide && slide.parentNode && !!slide.parentNode.nodeName.match( /section/i ); } /** * Handling the fullscreen functionality via the fullscreen API * * @see http://fullscreen.spec.whatwg.org/ * @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode */ function enterFullscreen() { var element = document.body; // Check which implementation is available var requestMethod = element.requestFullScreen || element.webkitRequestFullscreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullscreen; if( requestMethod ) { requestMethod.apply( element ); } } /** * Enters the paused mode which fades everything on screen to * black. */ function pause() { if( config.pause ) { var wasPaused = dom.wrapper.classList.contains( 'paused' ); cancelAutoSlide(); dom.wrapper.classList.add( 'paused' ); if( wasPaused === false ) { dispatchEvent( 'paused' ); } } } /** * Exits from the paused mode. */ function resume() { var wasPaused = dom.wrapper.classList.contains( 'paused' ); dom.wrapper.classList.remove( 'paused' ); cueAutoSlide(); if( wasPaused ) { dispatchEvent( 'resumed' ); } } /** * Toggles the paused mode on and off. */ function togglePause( override ) { if( typeof override === 'boolean' ) { override ? pause() : resume(); } else { isPaused() ? resume() : pause(); } } /** * Checks if we are currently in the paused mode. */ function isPaused() { return dom.wrapper.classList.contains( 'paused' ); } /** * Toggles the auto slide mode on and off. * * @param {Boolean} override Optional flag which sets the desired state. * True means autoplay starts, false means it stops. */ function toggleAutoSlide( override ) { if( typeof override === 'boolean' ) { override ? resumeAutoSlide() : pauseAutoSlide(); } else { autoSlidePaused ? resumeAutoSlide() : pauseAutoSlide(); } } /** * Checks if the auto slide mode is currently on. */ function isAutoSliding() { return !!( autoSlide && !autoSlidePaused ); } /** * Steps from the current point in the presentation to the * slide which matches the specified horizontal and vertical * indices. * * @param {int} h Horizontal index of the target slide * @param {int} v Vertical index of the target slide * @param {int} f Optional index of a fragment within the * target slide to activate * @param {int} o Optional origin for use in multimaster environments */ function slide( h, v, f, o ) { // Remember where we were at before previousSlide = currentSlide; // Query all horizontal slides in the deck var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ); // If no vertical index is specified and the upcoming slide is a // stack, resume at its previous vertical index if( v === undefined && !isOverview() ) { v = getPreviousVerticalIndex( horizontalSlides[ h ] ); } // If we were on a vertical stack, remember what vertical index // it was on so we can resume at the same position when returning if( previousSlide && previousSlide.parentNode && previousSlide.parentNode.classList.contains( 'stack' ) ) { setPreviousVerticalIndex( previousSlide.parentNode, indexv ); } // Remember the state before this slide var stateBefore = state.concat(); // Reset the state array state.length = 0; var indexhBefore = indexh || 0, indexvBefore = indexv || 0; // Activate and transition to the new slide indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h ); indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v ); // Update the visibility of slides now that the indices have changed updateSlidesVisibility(); layout(); // Apply the new state stateLoop: for( var i = 0, len = state.length; i < len; i++ ) { // Check if this state existed on the previous slide. If it // did, we will avoid adding it repeatedly for( var j = 0; j < stateBefore.length; j++ ) { if( stateBefore[j] === state[i] ) { stateBefore.splice( j, 1 ); continue stateLoop; } } document.documentElement.classList.add( state[i] ); // Dispatch custom event matching the state's name dispatchEvent( state[i] ); } // Clean up the remains of the previous state while( stateBefore.length ) { document.documentElement.classList.remove( stateBefore.pop() ); } // Update the overview if it's currently active if( isOverview() ) { updateOverview(); } // Find the current horizontal slide and any possible vertical slides // within it var currentHorizontalSlide = horizontalSlides[ indexh ], currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' ); // Store references to the previous and current slides currentSlide = currentVerticalSlides[ indexv ] || currentHorizontalSlide; // Show fragment, if specified if( typeof f !== 'undefined' ) { navigateFragment( f ); } // Dispatch an event if the slide changed var slideChanged = ( indexh !== indexhBefore || indexv !== indexvBefore ); if( slideChanged ) { dispatchEvent( 'slidechanged', { 'indexh': indexh, 'indexv': indexv, 'previousSlide': previousSlide, 'currentSlide': currentSlide, 'origin': o } ); } else { // Ensure that the previous slide is never the same as the current previousSlide = null; } // Solves an edge case where the previous slide maintains the // 'present' class when navigating between adjacent vertical // stacks if( previousSlide ) { previousSlide.classList.remove( 'present' ); previousSlide.setAttribute( 'aria-hidden', 'true' ); // Reset all slides upon navigate to home // Issue: #285 if ( dom.wrapper.querySelector( HOME_SLIDE_SELECTOR ).classList.contains( 'present' ) ) { // Launch async task setTimeout( function () { var slides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.stack') ), i; for( i in slides ) { if( slides[i] ) { // Reset stack setPreviousVerticalIndex( slides[i], 0 ); } } }, 0 ); } } // Handle embedded content if( slideChanged || !previousSlide ) { stopEmbeddedContent( previousSlide ); startEmbeddedContent( currentSlide ); } // Announce the current slide contents, for screen readers dom.statusDiv.textContent = currentSlide.textContent; updateControls(); updateProgress(); updateBackground(); updateParallax(); updateSlideNumber(); updateNotes(); // Update the URL hash writeURL(); cueAutoSlide(); } /** * Syncs the presentation with the current DOM. Useful * when new slides or control elements are added or when * the configuration has changed. */ function sync() { // Subscribe to input removeEventListeners(); addEventListeners(); // Force a layout to make sure the current config is accounted for layout(); // Reflect the current autoSlide value autoSlide = config.autoSlide; // Start auto-sliding if it's enabled cueAutoSlide(); // Re-create the slide backgrounds createBackgrounds(); // Write the current hash to the URL writeURL(); sortAllFragments(); updateControls(); updateProgress(); updateBackground( true ); updateSlideNumber(); updateSlidesVisibility(); updateNotes(); formatEmbeddedContent(); startEmbeddedContent( currentSlide ); if( isOverview() ) { layoutOverview(); } } /** * Resets all vertical slides so that only the first * is visible. */ function resetVerticalSlides() { var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); horizontalSlides.forEach( function( horizontalSlide ) { var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ); verticalSlides.forEach( function( verticalSlide, y ) { if( y > 0 ) { verticalSlide.classList.remove( 'present' ); verticalSlide.classList.remove( 'past' ); verticalSlide.classList.add( 'future' ); verticalSlide.setAttribute( 'aria-hidden', 'true' ); } } ); } ); } /** * Sorts and formats all of fragments in the * presentation. */ function sortAllFragments() { var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); horizontalSlides.forEach( function( horizontalSlide ) { var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ); verticalSlides.forEach( function( verticalSlide, y ) { sortFragments( verticalSlide.querySelectorAll( '.fragment' ) ); } ); if( verticalSlides.length === 0 ) sortFragments( horizontalSlide.querySelectorAll( '.fragment' ) ); } ); } /** * Randomly shuffles all slides in the deck. */ function shuffle() { var slides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); slides.forEach( function( slide ) { // Insert this slide next to another random slide. This may // cause the slide to insert before itself but that's fine. dom.slides.insertBefore( slide, slides[ Math.floor( Math.random() * slides.length ) ] ); } ); } /** * Updates one dimension of slides by showing the slide * with the specified index. * * @param {String} selector A CSS selector that will fetch * the group of slides we are working with * @param {Number} index The index of the slide that should be * shown * * @return {Number} The index of the slide that is now shown, * might differ from the passed in index if it was out of * bounds. */ function updateSlides( selector, index ) { // Select all slides and convert the NodeList result to // an array var slides = toArray( dom.wrapper.querySelectorAll( selector ) ), slidesLength = slides.length; var printMode = isPrintingPDF(); if( slidesLength ) { // Should the index loop? if( config.loop ) { index %= slidesLength; if( index < 0 ) { index = slidesLength + index; } } // Enforce max and minimum index bounds index = Math.max( Math.min( index, slidesLength - 1 ), 0 ); for( var i = 0; i < slidesLength; i++ ) { var element = slides[i]; var reverse = config.rtl && !isVerticalSlide( element ); element.classList.remove( 'past' ); element.classList.remove( 'present' ); element.classList.remove( 'future' ); // http://www.w3.org/html/wg/drafts/html/master/editing.html#the-hidden-attribute element.setAttribute( 'hidden', '' ); element.setAttribute( 'aria-hidden', 'true' ); // If this element contains vertical slides if( element.querySelector( 'section' ) ) { element.classList.add( 'stack' ); } // If we're printing static slides, all slides are "present" if( printMode ) { element.classList.add( 'present' ); continue; } if( i < index ) { // Any element previous to index is given the 'past' class element.classList.add( reverse ? 'future' : 'past' ); if( config.fragments ) { var pastFragments = toArray( element.querySelectorAll( '.fragment' ) ); // Show all fragments on prior slides while( pastFragments.length ) { var pastFragment = pastFragments.pop(); pastFragment.classList.add( 'visible' ); pastFragment.classList.remove( 'current-fragment' ); } } } else if( i > index ) { // Any element subsequent to index is given the 'future' class element.classList.add( reverse ? 'past' : 'future' ); if( config.fragments ) { var futureFragments = toArray( element.querySelectorAll( '.fragment.visible' ) ); // No fragments in future slides should be visible ahead of time while( futureFragments.length ) { var futureFragment = futureFragments.pop(); futureFragment.classList.remove( 'visible' ); futureFragment.classList.remove( 'current-fragment' ); } } } } // Mark the current slide as present slides[index].classList.add( 'present' ); slides[index].removeAttribute( 'hidden' ); slides[index].removeAttribute( 'aria-hidden' ); // If this slide has a state associated with it, add it // onto the current state of the deck var slideState = slides[index].getAttribute( 'data-state' ); if( slideState ) { state = state.concat( slideState.split( ' ' ) ); } } else { // Since there are no slides we can't be anywhere beyond the // zeroth index index = 0; } return index; } /** * Optimization method; hide all slides that are far away * from the present slide. */ function updateSlidesVisibility() { // Select all slides and convert the NodeList result to // an array var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ), horizontalSlidesLength = horizontalSlides.length, distanceX, distanceY; if( horizontalSlidesLength && typeof indexh !== 'undefined' ) { // The number of steps away from the present slide that will // be visible var viewDistance = isOverview() ? 10 : config.viewDistance; // Limit view distance on weaker devices if( isMobileDevice ) { viewDistance = isOverview() ? 6 : 2; } // All slides need to be visible when exporting to PDF if( isPrintingPDF() ) { viewDistance = Number.MAX_VALUE; } for( var x = 0; x < horizontalSlidesLength; x++ ) { var horizontalSlide = horizontalSlides[x]; var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ), verticalSlidesLength = verticalSlides.length; // Determine how far away this slide is from the present distanceX = Math.abs( ( indexh || 0 ) - x ) || 0; // If the presentation is looped, distance should measure // 1 between the first and last slides if( config.loop ) { distanceX = Math.abs( ( ( indexh || 0 ) - x ) % ( horizontalSlidesLength - viewDistance ) ) || 0; } // Show the horizontal slide if it's within the view distance if( distanceX < viewDistance ) { showSlide( horizontalSlide ); } else { hideSlide( horizontalSlide ); } if( verticalSlidesLength ) { var oy = getPreviousVerticalIndex( horizontalSlide ); for( var y = 0; y < verticalSlidesLength; y++ ) { var verticalSlide = verticalSlides[y]; distanceY = x === ( indexh || 0 ) ? Math.abs( ( indexv || 0 ) - y ) : Math.abs( y - oy ); if( distanceX + distanceY < viewDistance ) { showSlide( verticalSlide ); } else { hideSlide( verticalSlide ); } } } } } } /** * Pick up notes from the current slide and display tham * to the viewer. * * @see `showNotes` config value */ function updateNotes() { if( config.showNotes && dom.speakerNotes && currentSlide && !isPrintingPDF() ) { dom.speakerNotes.innerHTML = getSlideNotes() || ''; } } /** * Updates the progress bar to reflect the current slide. */ function updateProgress() { // Update progress if enabled if( config.progress && dom.progressbar ) { dom.progressbar.style.width = getProgress() * dom.wrapper.offsetWidth + 'px'; } } /** * Updates the slide number div to reflect the current slide. * * The following slide number formats are available: * "h.v": horizontal . vertical slide number (default) * "h/v": horizontal / vertical slide number * "c": flattened slide number * "c/t": flattened slide number / total slides */ function updateSlideNumber() { // Update slide number if enabled if( config.slideNumber && dom.slideNumber ) { var value = []; var format = 'h.v'; // Check if a custom number format is available if( typeof config.slideNumber === 'string' ) { format = config.slideNumber; } switch( format ) { case 'c': value.push( getSlidePastCount() + 1 ); break; case 'c/t': value.push( getSlidePastCount() + 1, '/', getTotalSlides() ); break; case 'h/v': value.push( indexh + 1 ); if( isVerticalSlide() ) value.push( '/', indexv + 1 ); break; default: value.push( indexh + 1 ); if( isVerticalSlide() ) value.push( '.', indexv + 1 ); } dom.slideNumber.innerHTML = formatSlideNumber( value[0], value[1], value[2] ); } } /** * Applies HTML formatting to a slide number before it's * written to the DOM. */ function formatSlideNumber( a, delimiter, b ) { if( typeof b === 'number' && !isNaN( b ) ) { return '<span class="slide-number-a">'+ a +'</span>' + '<span class="slide-number-delimiter">'+ delimiter +'</span>' + '<span class="slide-number-b">'+ b +'</span>'; } else { return '<span class="slide-number-a">'+ a +'</span>'; } } /** * Updates the state of all control/navigation arrows. */ function updateControls() { var routes = availableRoutes(); var fragments = availableFragments(); // Remove the 'enabled' class from all directions dom.controlsLeft.concat( dom.controlsRight ) .concat( dom.controlsUp ) .concat( dom.controlsDown ) .concat( dom.controlsPrev ) .concat( dom.controlsNext ).forEach( function( node ) { node.classList.remove( 'enabled' ); node.classList.remove( 'fragmented' ); } ); // Add the 'enabled' class to the available routes if( routes.left ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'enabled' ); } ); if( routes.right ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'enabled' ); } ); if( routes.up ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'enabled' ); } ); if( routes.down ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'enabled' ); } ); // Prev/next buttons if( routes.left || routes.up ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'enabled' ); } ); if( routes.right || routes.down ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'enabled' ); } ); // Highlight fragment directions if( currentSlide ) { // Always apply fragment decorator to prev/next buttons if( fragments.prev ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); if( fragments.next ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); // Apply fragment decorators to directional buttons based on // what slide axis they are in if( isVerticalSlide( currentSlide ) ) { if( fragments.prev ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); if( fragments.next ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); } else { if( fragments.prev ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); if( fragments.next ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); } } } /** * Updates the background elements to reflect the current * slide. * * @param {Boolean} includeAll If true, the backgrounds of * all vertical slides (not just the present) will be updated. */ function updateBackground( includeAll ) { var currentBackground = null; // Reverse past/future classes when in RTL mode var horizontalPast = config.rtl ? 'future' : 'past', horizontalFuture = config.rtl ? 'past' : 'future'; // Update the classes of all backgrounds to match the // states of their slides (past/present/future) toArray( dom.background.childNodes ).forEach( function( backgroundh, h ) { backgroundh.classList.remove( 'past' ); backgroundh.classList.remove( 'present' ); backgroundh.classList.remove( 'future' ); if( h < indexh ) { backgroundh.classList.add( horizontalPast ); } else if ( h > indexh ) { backgroundh.classList.add( horizontalFuture ); } else { backgroundh.classList.add( 'present' ); // Store a reference to the current background element currentBackground = backgroundh; } if( includeAll || h === indexh ) { toArray( backgroundh.querySelectorAll( '.slide-background' ) ).forEach( function( backgroundv, v ) { backgroundv.classList.remove( 'past' ); backgroundv.classList.remove( 'present' ); backgroundv.classList.remove( 'future' ); if( v < indexv ) { backgroundv.classList.add( 'past' ); } else if ( v > indexv ) { backgroundv.classList.add( 'future' ); } else { backgroundv.classList.add( 'present' ); // Only if this is the present horizontal and vertical slide if( h === indexh ) currentBackground = backgroundv; } } ); } } ); // Stop any currently playing video background if( previousBackground ) { var previousVideo = previousBackground.querySelector( 'video' ); if( previousVideo ) previousVideo.pause(); } if( currentBackground ) { // Start video playback var currentVideo = currentBackground.querySelector( 'video' ); if( currentVideo ) { var startVideo = function() { currentVideo.currentTime = 0; currentVideo.play(); currentVideo.removeEventListener( 'loadeddata', startVideo ); }; if( currentVideo.readyState > 1 ) { startVideo(); } else { currentVideo.addEventListener( 'loadeddata', startVideo ); } } var backgroundImageURL = currentBackground.style.backgroundImage || ''; // Restart GIFs (doesn't work in Firefox) if( /\.gif/i.test( backgroundImageURL ) ) { currentBackground.style.backgroundImage = ''; window.getComputedStyle( currentBackground ).opacity; currentBackground.style.backgroundImage = backgroundImageURL; } // Don't transition between identical backgrounds. This // prevents unwanted flicker. var previousBackgroundHash = previousBackground ? previousBackground.getAttribute( 'data-background-hash' ) : null; var currentBackgroundHash = currentBackground.getAttribute( 'data-background-hash' ); if( currentBackgroundHash && currentBackgroundHash === previousBackgroundHash && currentBackground !== previousBackground ) { dom.background.classList.add( 'no-transition' ); } previousBackground = currentBackground; } // If there's a background brightness flag for this slide, // bubble it to the .reveal container if( currentSlide ) { [ 'has-light-background', 'has-dark-background' ].forEach( function( classToBubble ) { if( currentSlide.classList.contains( classToBubble ) ) { dom.wrapper.classList.add( classToBubble ); } else { dom.wrapper.classList.remove( classToBubble ); } } ); } // Allow the first background to apply without transition setTimeout( function() { dom.background.classList.remove( 'no-transition' ); }, 1 ); } /** * Updates the position of the parallax background based * on the current slide index. */ function updateParallax() { if( config.parallaxBackgroundImage ) { var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ), verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR ); var backgroundSize = dom.background.style.backgroundSize.split( ' ' ), backgroundWidth, backgroundHeight; if( backgroundSize.length === 1 ) { backgroundWidth = backgroundHeight = parseInt( backgroundSize[0], 10 ); } else { backgroundWidth = parseInt( backgroundSize[0], 10 ); backgroundHeight = parseInt( backgroundSize[1], 10 ); } var slideWidth = dom.background.offsetWidth, horizontalSlideCount = horizontalSlides.length, horizontalOffsetMultiplier, horizontalOffset; if( typeof config.parallaxBackgroundHorizontal === 'number' ) { horizontalOffsetMultiplier = config.parallaxBackgroundHorizontal; } else { horizontalOffsetMultiplier = horizontalSlideCount > 1 ? ( backgroundWidth - slideWidth ) / ( horizontalSlideCount-1 ) : 0; } horizontalOffset = horizontalOffsetMultiplier * indexh * -1; var slideHeight = dom.background.offsetHeight, verticalSlideCount = verticalSlides.length, verticalOffsetMultiplier, verticalOffset; if( typeof config.parallaxBackgroundVertical === 'number' ) { verticalOffsetMultiplier = config.parallaxBackgroundVertical; } else { verticalOffsetMultiplier = ( backgroundHeight - slideHeight ) / ( verticalSlideCount-1 ); } verticalOffset = verticalSlideCount > 0 ? verticalOffsetMultiplier * indexv * 1 : 0; dom.background.style.backgroundPosition = horizontalOffset + 'px ' + -verticalOffset + 'px'; } } /** * Called when the given slide is within the configured view * distance. Shows the slide element and loads any content * that is set to load lazily (data-src). */ function showSlide( slide ) { // Show the slide element slide.style.display = 'block'; // Media elements with data-src attributes toArray( slide.querySelectorAll( 'img[data-src], video[data-src], audio[data-src]' ) ).forEach( function( element ) { element.setAttribute( 'src', element.getAttribute( 'data-src' ) ); element.removeAttribute( 'data-src' ); } ); // Media elements with <source> children toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( media ) { var sources = 0; toArray( media.querySelectorAll( 'source[data-src]' ) ).forEach( function( source ) { source.setAttribute( 'src', source.getAttribute( 'data-src' ) ); source.removeAttribute( 'data-src' ); sources += 1; } ); // If we rewrote sources for this video/audio element, we need // to manually tell it to load from its new origin if( sources > 0 ) { media.load(); } } ); // Show the corresponding background element var indices = getIndices( slide ); var background = getSlideBackground( indices.h, indices.v ); if( background ) { background.style.display = 'block'; // If the background contains media, load it if( background.hasAttribute( 'data-loaded' ) === false ) { background.setAttribute( 'data-loaded', 'true' ); var backgroundImage = slide.getAttribute( 'data-background-image' ), backgroundVideo = slide.getAttribute( 'data-background-video' ), backgroundVideoLoop = slide.hasAttribute( 'data-background-video-loop' ), backgroundVideoMuted = slide.hasAttribute( 'data-background-video-muted' ), backgroundIframe = slide.getAttribute( 'data-background-iframe' ); // Images if( backgroundImage ) { background.style.backgroundImage = 'url('+ backgroundImage +')'; } // Videos else if ( backgroundVideo && !isSpeakerNotes() ) { var video = document.createElement( 'video' ); if( backgroundVideoLoop ) { video.setAttribute( 'loop', '' ); } if( backgroundVideoMuted ) { video.muted = true; } // Support comma separated lists of video sources backgroundVideo.split( ',' ).forEach( function( source ) { video.innerHTML += '<source src="'+ source +'">'; } ); background.appendChild( video ); } // Iframes else if( backgroundIframe ) { var iframe = document.createElement( 'iframe' ); iframe.setAttribute( 'src', backgroundIframe ); iframe.style.width = '100%'; iframe.style.height = '100%'; iframe.style.maxHeight = '100%'; iframe.style.maxWidth = '100%'; background.appendChild( iframe ); } } } } /** * Called when the given slide is moved outside of the * configured view distance. */ function hideSlide( slide ) { // Hide the slide element slide.style.display = 'none'; // Hide the corresponding background element var indices = getIndices( slide ); var background = getSlideBackground( indices.h, indices.v ); if( background ) { background.style.display = 'none'; } } /** * Determine what available routes there are for navigation. * * @return {Object} containing four booleans: left/right/up/down */ function availableRoutes() { var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ), verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR ); var routes = { left: indexh > 0 || config.loop, right: indexh < horizontalSlides.length - 1 || config.loop, up: indexv > 0, down: indexv < verticalSlides.length - 1 }; // reverse horizontal controls for rtl if( config.rtl ) { var left = routes.left; routes.left = routes.right; routes.right = left; } return routes; } /** * Returns an object describing the available fragment * directions. * * @return {Object} two boolean properties: prev/next */ function availableFragments() { if( currentSlide && config.fragments ) { var fragments = currentSlide.querySelectorAll( '.fragment' ); var hiddenFragments = currentSlide.querySelectorAll( '.fragment:not(.visible)' ); return { prev: fragments.length - hiddenFragments.length > 0, next: !!hiddenFragments.length }; } else { return { prev: false, next: false }; } } /** * Enforces origin-specific format rules for embedded media. */ function formatEmbeddedContent() { var _appendParamToIframeSource = function( sourceAttribute, sourceURL, param ) { toArray( dom.slides.querySelectorAll( 'iframe['+ sourceAttribute +'*="'+ sourceURL +'"]' ) ).forEach( function( el ) { var src = el.getAttribute( sourceAttribute ); if( src && src.indexOf( param ) === -1 ) { el.setAttribute( sourceAttribute, src + ( !/\?/.test( src ) ? '?' : '&' ) + param ); } }); }; // YouTube frames must include "?enablejsapi=1" _appendParamToIframeSource( 'src', 'youtube.com/embed/', 'enablejsapi=1' ); _appendParamToIframeSource( 'data-src', 'youtube.com/embed/', 'enablejsapi=1' ); // Vimeo frames must include "?api=1" _appendParamToIframeSource( 'src', 'player.vimeo.com/', 'api=1' ); _appendParamToIframeSource( 'data-src', 'player.vimeo.com/', 'api=1' ); } /** * Start playback of any embedded content inside of * the targeted slide. */ function startEmbeddedContent( slide ) { if( slide && !isSpeakerNotes() ) { // Restart GIFs toArray( slide.querySelectorAll( 'img[src$=".gif"]' ) ).forEach( function( el ) { // Setting the same unchanged source like this was confirmed // to work in Chrome, FF & Safari el.setAttribute( 'src', el.getAttribute( 'src' ) ); } ); // HTML5 media elements toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) { if( el.hasAttribute( 'data-autoplay' ) && typeof el.play === 'function' ) { el.play(); } } ); // Normal iframes toArray( slide.querySelectorAll( 'iframe[src]' ) ).forEach( function( el ) { startEmbeddedIframe( { target: el } ); } ); // Lazy loading iframes toArray( slide.querySelectorAll( 'iframe[data-src]' ) ).forEach( function( el ) { if( el.getAttribute( 'src' ) !== el.getAttribute( 'data-src' ) ) { el.removeEventListener( 'load', startEmbeddedIframe ); // remove first to avoid dupes el.addEventListener( 'load', startEmbeddedIframe ); el.setAttribute( 'src', el.getAttribute( 'data-src' ) ); } } ); } } /** * "Starts" the content of an embedded iframe using the * postmessage API. */ function startEmbeddedIframe( event ) { var iframe = event.target; // YouTube postMessage API if( /youtube\.com\/embed\//.test( iframe.getAttribute( 'src' ) ) && iframe.hasAttribute( 'data-autoplay' ) ) { iframe.contentWindow.postMessage( '{"event":"command","func":"playVideo","args":""}', '*' ); } // Vimeo postMessage API else if( /player\.vimeo\.com\//.test( iframe.getAttribute( 'src' ) ) && iframe.hasAttribute( 'data-autoplay' ) ) { iframe.contentWindow.postMessage( '{"method":"play"}', '*' ); } // Generic postMessage API else { iframe.contentWindow.postMessage( 'slide:start', '*' ); } } /** * Stop playback of any embedded content inside of * the targeted slide. */ function stopEmbeddedContent( slide ) { if( slide && slide.parentNode ) { // HTML5 media elements toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) { if( !el.hasAttribute( 'data-ignore' ) && typeof el.pause === 'function' ) { el.pause(); } } ); // Generic postMessage API for non-lazy loaded iframes toArray( slide.querySelectorAll( 'iframe' ) ).forEach( function( el ) { el.contentWindow.postMessage( 'slide:stop', '*' ); el.removeEventListener( 'load', startEmbeddedIframe ); }); // YouTube postMessage API toArray( slide.querySelectorAll( 'iframe[src*="youtube.com/embed/"]' ) ).forEach( function( el ) { if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) { el.contentWindow.postMessage( '{"event":"command","func":"pauseVideo","args":""}', '*' ); } }); // Vimeo postMessage API toArray( slide.querySelectorAll( 'iframe[src*="player.vimeo.com/"]' ) ).forEach( function( el ) { if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) { el.contentWindow.postMessage( '{"method":"pause"}', '*' ); } }); // Lazy loading iframes toArray( slide.querySelectorAll( 'iframe[data-src]' ) ).forEach( function( el ) { // Only removing the src doesn't actually unload the frame // in all browsers (Firefox) so we set it to blank first el.setAttribute( 'src', 'about:blank' ); el.removeAttribute( 'src' ); } ); } } /** * Returns the number of past slides. This can be used as a global * flattened index for slides. */ function getSlidePastCount() { var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); // The number of past slides var pastCount = 0; // Step through all slides and count the past ones mainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) { var horizontalSlide = horizontalSlides[i]; var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ); for( var j = 0; j < verticalSlides.length; j++ ) { // Stop as soon as we arrive at the present if( verticalSlides[j].classList.contains( 'present' ) ) { break mainLoop; } pastCount++; } // Stop as soon as we arrive at the present if( horizontalSlide.classList.contains( 'present' ) ) { break; } // Don't count the wrapping section for vertical slides if( horizontalSlide.classList.contains( 'stack' ) === false ) { pastCount++; } } return pastCount; } /** * Returns a value ranging from 0-1 that represents * how far into the presentation we have navigated. */ function getProgress() { // The number of past and total slides var totalCount = getTotalSlides(); var pastCount = getSlidePastCount(); if( currentSlide ) { var allFragments = currentSlide.querySelectorAll( '.fragment' ); // If there are fragments in the current slide those should be // accounted for in the progress. if( allFragments.length > 0 ) { var visibleFragments = currentSlide.querySelectorAll( '.fragment.visible' ); // This value represents how big a portion of the slide progress // that is made up by its fragments (0-1) var fragmentWeight = 0.9; // Add fragment progress to the past slide count pastCount += ( visibleFragments.length / allFragments.length ) * fragmentWeight; } } return pastCount / ( totalCount - 1 ); } /** * Checks if this presentation is running inside of the * speaker notes window. */ function isSpeakerNotes() { return !!window.location.search.match( /receiver/gi ); } /** * Reads the current URL (hash) and navigates accordingly. */ function readURL() { var hash = window.location.hash; // Attempt to parse the hash as either an index or name var bits = hash.slice( 2 ).split( '/' ), name = hash.replace( /#|\//gi, '' ); // If the first bit is invalid and there is a name we can // assume that this is a named link if( isNaN( parseInt( bits[0], 10 ) ) && name.length ) { var element; // Ensure the named link is a valid HTML ID attribute if( /^[a-zA-Z][\w:.-]*$/.test( name ) ) { // Find the slide with the specified ID element = document.getElementById( name ); } if( element ) { // Find the position of the named slide and navigate to it var indices = Reveal.getIndices( element ); slide( indices.h, indices.v ); } // If the slide doesn't exist, navigate to the current slide else { slide( indexh || 0, indexv || 0 ); } } else { // Read the index components of the hash var h = parseInt( bits[0], 10 ) || 0, v = parseInt( bits[1], 10 ) || 0; if( h !== indexh || v !== indexv ) { slide( h, v ); } } } /** * Updates the page URL (hash) to reflect the current * state. * * @param {Number} delay The time in ms to wait before * writing the hash */ function writeURL( delay ) { if( config.history ) { // Make sure there's never more than one timeout running clearTimeout( writeURLTimeout ); // If a delay is specified, timeout this call if( typeof delay === 'number' ) { writeURLTimeout = setTimeout( writeURL, delay ); } else if( currentSlide ) { var url = '/'; // Attempt to create a named link based on the slide's ID var id = currentSlide.getAttribute( 'id' ); if( id ) { id = id.replace( /[^a-zA-Z0-9\-\_\:\.]/g, '' ); } // If the current slide has an ID, use that as a named link if( typeof id === 'string' && id.length ) { url = '/' + id; } // Otherwise use the /h/v index else { if( indexh > 0 || indexv > 0 ) url += indexh; if( indexv > 0 ) url += '/' + indexv; } window.location.hash = url; } } } /** * Retrieves the h/v location of the current, or specified, * slide. * * @param {HTMLElement} slide If specified, the returned * index will be for this slide rather than the currently * active one * * @return {Object} { h: <int>, v: <int>, f: <int> } */ function getIndices( slide ) { // By default, return the current indices var h = indexh, v = indexv, f; // If a slide is specified, return the indices of that slide if( slide ) { var isVertical = isVerticalSlide( slide ); var slideh = isVertical ? slide.parentNode : slide; // Select all horizontal slides var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); // Now that we know which the horizontal slide is, get its index h = Math.max( horizontalSlides.indexOf( slideh ), 0 ); // Assume we're not vertical v = undefined; // If this is a vertical slide, grab the vertical index if( isVertical ) { v = Math.max( toArray( slide.parentNode.querySelectorAll( 'section' ) ).indexOf( slide ), 0 ); } } if( !slide && currentSlide ) { var hasFragments = currentSlide.querySelectorAll( '.fragment' ).length > 0; if( hasFragments ) { var currentFragment = currentSlide.querySelector( '.current-fragment' ); if( currentFragment && currentFragment.hasAttribute( 'data-fragment-index' ) ) { f = parseInt( currentFragment.getAttribute( 'data-fragment-index' ), 10 ); } else { f = currentSlide.querySelectorAll( '.fragment.visible' ).length - 1; } } } return { h: h, v: v, f: f }; } /** * Retrieves the total number of slides in this presentation. */ function getTotalSlides() { return dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length; } /** * Returns the slide element matching the specified index. */ function getSlide( x, y ) { var horizontalSlide = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR )[ x ]; var verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll( 'section' ); if( verticalSlides && verticalSlides.length && typeof y === 'number' ) { return verticalSlides ? verticalSlides[ y ] : undefined; } return horizontalSlide; } /** * Returns the background element for the given slide. * All slides, even the ones with no background properties * defined, have a background element so as long as the * index is valid an element will be returned. */ function getSlideBackground( x, y ) { // When printing to PDF the slide backgrounds are nested // inside of the slides if( isPrintingPDF() ) { var slide = getSlide( x, y ); if( slide ) { var background = slide.querySelector( '.slide-background' ); if( background && background.parentNode === slide ) { return background; } } return undefined; } var horizontalBackground = dom.wrapper.querySelectorAll( '.backgrounds>.slide-background' )[ x ]; var verticalBackgrounds = horizontalBackground && horizontalBackground.querySelectorAll( '.slide-background' ); if( verticalBackgrounds && verticalBackgrounds.length && typeof y === 'number' ) { return verticalBackgrounds ? verticalBackgrounds[ y ] : undefined; } return horizontalBackground; } /** * Retrieves the speaker notes from a slide. Notes can be * defined in two ways: * 1. As a data-notes attribute on the slide <section> * 2. As an <aside class="notes"> inside of the slide */ function getSlideNotes( slide ) { // Default to the current slide slide = slide || currentSlide; // Notes can be specified via the data-notes attribute... if( slide.hasAttribute( 'data-notes' ) ) { return slide.getAttribute( 'data-notes' ); } // ... or using an <aside class="notes"> element var notesElement = slide.querySelector( 'aside.notes' ); if( notesElement ) { return notesElement.innerHTML; } return null; } /** * Retrieves the current state of the presentation as * an object. This state can then be restored at any * time. */ function getState() { var indices = getIndices(); return { indexh: indices.h, indexv: indices.v, indexf: indices.f, paused: isPaused(), overview: isOverview() }; } /** * Restores the presentation to the given state. * * @param {Object} state As generated by getState() */ function setState( state ) { if( typeof state === 'object' ) { slide( deserialize( state.indexh ), deserialize( state.indexv ), deserialize( state.indexf ) ); var pausedFlag = deserialize( state.paused ), overviewFlag = deserialize( state.overview ); if( typeof pausedFlag === 'boolean' && pausedFlag !== isPaused() ) { togglePause( pausedFlag ); } if( typeof overviewFlag === 'boolean' && overviewFlag !== isOverview() ) { toggleOverview( overviewFlag ); } } } /** * Return a sorted fragments list, ordered by an increasing * "data-fragment-index" attribute. * * Fragments will be revealed in the order that they are returned by * this function, so you can use the index attributes to control the * order of fragment appearance. * * To maintain a sensible default fragment order, fragments are presumed * to be passed in document order. This function adds a "fragment-index" * attribute to each node if such an attribute is not already present, * and sets that attribute to an integer value which is the position of * the fragment within the fragments list. */ function sortFragments( fragments ) { fragments = toArray( fragments ); var ordered = [], unordered = [], sorted = []; // Group ordered and unordered elements fragments.forEach( function( fragment, i ) { if( fragment.hasAttribute( 'data-fragment-index' ) ) { var index = parseInt( fragment.getAttribute( 'data-fragment-index' ), 10 ); if( !ordered[index] ) { ordered[index] = []; } ordered[index].push( fragment ); } else { unordered.push( [ fragment ] ); } } ); // Append fragments without explicit indices in their // DOM order ordered = ordered.concat( unordered ); // Manually count the index up per group to ensure there // are no gaps var index = 0; // Push all fragments in their sorted order to an array, // this flattens the groups ordered.forEach( function( group ) { group.forEach( function( fragment ) { sorted.push( fragment ); fragment.setAttribute( 'data-fragment-index', index ); } ); index ++; } ); return sorted; } /** * Navigate to the specified slide fragment. * * @param {Number} index The index of the fragment that * should be shown, -1 means all are invisible * @param {Number} offset Integer offset to apply to the * fragment index * * @return {Boolean} true if a change was made in any * fragments visibility as part of this call */ function navigateFragment( index, offset ) { if( currentSlide && config.fragments ) { var fragments = sortFragments( currentSlide.querySelectorAll( '.fragment' ) ); if( fragments.length ) { // If no index is specified, find the current if( typeof index !== 'number' ) { var lastVisibleFragment = sortFragments( currentSlide.querySelectorAll( '.fragment.visible' ) ).pop(); if( lastVisibleFragment ) { index = parseInt( lastVisibleFragment.getAttribute( 'data-fragment-index' ) || 0, 10 ); } else { index = -1; } } // If an offset is specified, apply it to the index if( typeof offset === 'number' ) { index += offset; } var fragmentsShown = [], fragmentsHidden = []; toArray( fragments ).forEach( function( element, i ) { if( element.hasAttribute( 'data-fragment-index' ) ) { i = parseInt( element.getAttribute( 'data-fragment-index' ), 10 ); } // Visible fragments if( i <= index ) { if( !element.classList.contains( 'visible' ) ) fragmentsShown.push( element ); element.classList.add( 'visible' ); element.classList.remove( 'current-fragment' ); // Announce the fragments one by one to the Screen Reader dom.statusDiv.textContent = element.textContent; if( i === index ) { element.classList.add( 'current-fragment' ); } } // Hidden fragments else { if( element.classList.contains( 'visible' ) ) fragmentsHidden.push( element ); element.classList.remove( 'visible' ); element.classList.remove( 'current-fragment' ); } } ); if( fragmentsHidden.length ) { dispatchEvent( 'fragmenthidden', { fragment: fragmentsHidden[0], fragments: fragmentsHidden } ); } if( fragmentsShown.length ) { dispatchEvent( 'fragmentshown', { fragment: fragmentsShown[0], fragments: fragmentsShown } ); } updateControls(); updateProgress(); return !!( fragmentsShown.length || fragmentsHidden.length ); } } return false; } /** * Navigate to the next slide fragment. * * @return {Boolean} true if there was a next fragment, * false otherwise */ function nextFragment() { return navigateFragment( null, 1 ); } /** * Navigate to the previous slide fragment. * * @return {Boolean} true if there was a previous fragment, * false otherwise */ function previousFragment() { return navigateFragment( null, -1 ); } /** * Cues a new automated slide if enabled in the config. */ function cueAutoSlide() { cancelAutoSlide(); if( currentSlide ) { var currentFragment = currentSlide.querySelector( '.current-fragment' ); var fragmentAutoSlide = currentFragment ? currentFragment.getAttribute( 'data-autoslide' ) : null; var parentAutoSlide = currentSlide.parentNode ? currentSlide.parentNode.getAttribute( 'data-autoslide' ) : null; var slideAutoSlide = currentSlide.getAttribute( 'data-autoslide' ); // Pick value in the following priority order: // 1. Current fragment's data-autoslide // 2. Current slide's data-autoslide // 3. Parent slide's data-autoslide // 4. Global autoSlide setting if( fragmentAutoSlide ) { autoSlide = parseInt( fragmentAutoSlide, 10 ); } else if( slideAutoSlide ) { autoSlide = parseInt( slideAutoSlide, 10 ); } else if( parentAutoSlide ) { autoSlide = parseInt( parentAutoSlide, 10 ); } else { autoSlide = config.autoSlide; } // If there are media elements with data-autoplay, // automatically set the autoSlide duration to the // length of that media. Not applicable if the slide // is divided up into fragments. if( currentSlide.querySelectorAll( '.fragment' ).length === 0 ) { toArray( currentSlide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) { if( el.hasAttribute( 'data-autoplay' ) ) { if( autoSlide && el.duration * 1000 > autoSlide ) { autoSlide = ( el.duration * 1000 ) + 1000; } } } ); } // Cue the next auto-slide if: // - There is an autoSlide value // - Auto-sliding isn't paused by the user // - The presentation isn't paused // - The overview isn't active // - The presentation isn't over if( autoSlide && !autoSlidePaused && !isPaused() && !isOverview() && ( !Reveal.isLastSlide() || availableFragments().next || config.loop === true ) ) { autoSlideTimeout = setTimeout( function() { typeof config.autoSlideMethod === 'function' ? config.autoSlideMethod() : navigateNext(); cueAutoSlide(); }, autoSlide ); autoSlideStartTime = Date.now(); } if( autoSlidePlayer ) { autoSlidePlayer.setPlaying( autoSlideTimeout !== -1 ); } } } /** * Cancels any ongoing request to auto-slide. */ function cancelAutoSlide() { clearTimeout( autoSlideTimeout ); autoSlideTimeout = -1; } function pauseAutoSlide() { if( autoSlide && !autoSlidePaused ) { autoSlidePaused = true; dispatchEvent( 'autoslidepaused' ); clearTimeout( autoSlideTimeout ); if( autoSlidePlayer ) { autoSlidePlayer.setPlaying( false ); } } } function resumeAutoSlide() { if( autoSlide && autoSlidePaused ) { autoSlidePaused = false; dispatchEvent( 'autoslideresumed' ); cueAutoSlide(); } } function navigateLeft() { // Reverse for RTL if( config.rtl ) { if( ( isOverview() || nextFragment() === false ) && availableRoutes().left ) { slide( indexh + 1 ); } } // Normal navigation else if( ( isOverview() || previousFragment() === false ) && availableRoutes().left ) { slide( indexh - 1 ); } } function navigateRight() { // Reverse for RTL if( config.rtl ) { if( ( isOverview() || previousFragment() === false ) && availableRoutes().right ) { slide( indexh - 1 ); } } // Normal navigation else if( ( isOverview() || nextFragment() === false ) && availableRoutes().right ) { slide( indexh + 1 ); } } function navigateUp() { // Prioritize hiding fragments if( ( isOverview() || previousFragment() === false ) && availableRoutes().up ) { slide( indexh, indexv - 1 ); } } function navigateDown() { // Prioritize revealing fragments if( ( isOverview() || nextFragment() === false ) && availableRoutes().down ) { slide( indexh, indexv + 1 ); } } /** * Navigates backwards, prioritized in the following order: * 1) Previous fragment * 2) Previous vertical slide * 3) Previous horizontal slide */ function navigatePrev() { // Prioritize revealing fragments if( previousFragment() === false ) { if( availableRoutes().up ) { navigateUp(); } else { // Fetch the previous horizontal slide, if there is one var previousSlide; if( config.rtl ) { previousSlide = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.future' ) ).pop(); } else { previousSlide = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.past' ) ).pop(); } if( previousSlide ) { var v = ( previousSlide.querySelectorAll( 'section' ).length - 1 ) || undefined; var h = indexh - 1; slide( h, v ); } } } } /** * The reverse of #navigatePrev(). */ function navigateNext() { // Prioritize revealing fragments if( nextFragment() === false ) { if( availableRoutes().down ) { navigateDown(); } else if( config.rtl ) { navigateLeft(); } else { navigateRight(); } } } /** * Checks if the target element prevents the triggering of * swipe navigation. */ function isSwipePrevented( target ) { while( target && typeof target.hasAttribute === 'function' ) { if( target.hasAttribute( 'data-prevent-swipe' ) ) return true; target = target.parentNode; } return false; } // --------------------------------------------------------------------// // ----------------------------- EVENTS -------------------------------// // --------------------------------------------------------------------// /** * Called by all event handlers that are based on user * input. */ function onUserInput( event ) { if( config.autoSlideStoppable ) { pauseAutoSlide(); } } /** * Handler for the document level 'keypress' event. */ function onDocumentKeyPress( event ) { // Check if the pressed key is question mark if( event.shiftKey && event.charCode === 63 ) { if( dom.overlay ) { closeOverlay(); } else { showHelp( true ); } } } /** * Handler for the document level 'keydown' event. */ function onDocumentKeyDown( event ) { // If there's a condition specified and it returns false, // ignore this event if( typeof config.keyboardCondition === 'function' && config.keyboardCondition() === false ) { return true; } // Remember if auto-sliding was paused so we can toggle it var autoSlideWasPaused = autoSlidePaused; onUserInput( event ); // Check if there's a focused element that could be using // the keyboard var activeElementIsCE = document.activeElement && document.activeElement.contentEditable !== 'inherit'; var activeElementIsInput = document.activeElement && document.activeElement.tagName && /input|textarea/i.test( document.activeElement.tagName ); // Disregard the event if there's a focused element or a // keyboard modifier key is present if( activeElementIsCE || activeElementIsInput || (event.shiftKey && event.keyCode !== 32) || event.altKey || event.ctrlKey || event.metaKey ) return; // While paused only allow resume keyboard events; 'b', '.'' var resumeKeyCodes = [66,190,191]; var key; // Custom key bindings for togglePause should be able to resume if( typeof config.keyboard === 'object' ) { for( key in config.keyboard ) { if( config.keyboard[key] === 'togglePause' ) { resumeKeyCodes.push( parseInt( key, 10 ) ); } } } if( isPaused() && resumeKeyCodes.indexOf( event.keyCode ) === -1 ) { return false; } var triggered = false; // 1. User defined key bindings if( typeof config.keyboard === 'object' ) { for( key in config.keyboard ) { // Check if this binding matches the pressed key if( parseInt( key, 10 ) === event.keyCode ) { var value = config.keyboard[ key ]; // Callback function if( typeof value === 'function' ) { value.apply( null, [ event ] ); } // String shortcuts to reveal.js API else if( typeof value === 'string' && typeof Reveal[ value ] === 'function' ) { Reveal[ value ].call(); } triggered = true; } } } // 2. System defined key bindings if( triggered === false ) { // Assume true and try to prove false triggered = true; switch( event.keyCode ) { // p, page up case 80: case 33: navigatePrev(); break; // n, page down case 78: case 34: navigateNext(); break; // h, left case 72: case 37: navigateLeft(); break; // l, right case 76: case 39: navigateRight(); break; // k, up case 75: case 38: navigateUp(); break; // j, down case 74: case 40: navigateDown(); break; // home case 36: slide( 0 ); break; // end case 35: slide( Number.MAX_VALUE ); break; // space case 32: isOverview() ? deactivateOverview() : event.shiftKey ? navigatePrev() : navigateNext(); break; // return case 13: isOverview() ? deactivateOverview() : triggered = false; break; // two-spot, semicolon, b, period, Logitech presenter tools "black screen" button case 58: case 59: case 66: case 190: case 191: togglePause(); break; // f case 70: enterFullscreen(); break; // a case 65: if ( config.autoSlideStoppable ) toggleAutoSlide( autoSlideWasPaused ); break; default: triggered = false; } } // If the input resulted in a triggered action we should prevent // the browsers default behavior if( triggered ) { event.preventDefault && event.preventDefault(); } // ESC or O key else if ( ( event.keyCode === 27 || event.keyCode === 79 ) && features.transforms3d ) { if( dom.overlay ) { closeOverlay(); } else { toggleOverview(); } event.preventDefault && event.preventDefault(); } // If auto-sliding is enabled we need to cue up // another timeout cueAutoSlide(); } /** * Handler for the 'touchstart' event, enables support for * swipe and pinch gestures. */ function onTouchStart( event ) { if( isSwipePrevented( event.target ) ) return true; touch.startX = event.touches[0].clientX; touch.startY = event.touches[0].clientY; touch.startCount = event.touches.length; // If there's two touches we need to memorize the distance // between those two points to detect pinching if( event.touches.length === 2 && config.overview ) { touch.startSpan = distanceBetween( { x: event.touches[1].clientX, y: event.touches[1].clientY }, { x: touch.startX, y: touch.startY } ); } } /** * Handler for the 'touchmove' event. */ function onTouchMove( event ) { if( isSwipePrevented( event.target ) ) return true; // Each touch should only trigger one action if( !touch.captured ) { onUserInput( event ); var currentX = event.touches[0].clientX; var currentY = event.touches[0].clientY; // If the touch started with two points and still has // two active touches; test for the pinch gesture if( event.touches.length === 2 && touch.startCount === 2 && config.overview ) { // The current distance in pixels between the two touch points var currentSpan = distanceBetween( { x: event.touches[1].clientX, y: event.touches[1].clientY }, { x: touch.startX, y: touch.startY } ); // If the span is larger than the desire amount we've got // ourselves a pinch if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) { touch.captured = true; if( currentSpan < touch.startSpan ) { activateOverview(); } else { deactivateOverview(); } } event.preventDefault(); } // There was only one touch point, look for a swipe else if( event.touches.length === 1 && touch.startCount !== 2 ) { var deltaX = currentX - touch.startX, deltaY = currentY - touch.startY; if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) { touch.captured = true; navigateLeft(); } else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) { touch.captured = true; navigateRight(); } else if( deltaY > touch.threshold ) { touch.captured = true; navigateUp(); } else if( deltaY < -touch.threshold ) { touch.captured = true; navigateDown(); } // If we're embedded, only block touch events if they have // triggered an action if( config.embedded ) { if( touch.captured || isVerticalSlide( currentSlide ) ) { event.preventDefault(); } } // Not embedded? Block them all to avoid needless tossing // around of the viewport in iOS else { event.preventDefault(); } } } // There's a bug with swiping on some Android devices unless // the default action is always prevented else if( UA.match( /android/gi ) ) { event.preventDefault(); } } /** * Handler for the 'touchend' event. */ function onTouchEnd( event ) { touch.captured = false; } /** * Convert pointer down to touch start. */ function onPointerDown( event ) { if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) { event.touches = [{ clientX: event.clientX, clientY: event.clientY }]; onTouchStart( event ); } } /** * Convert pointer move to touch move. */ function onPointerMove( event ) { if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) { event.touches = [{ clientX: event.clientX, clientY: event.clientY }]; onTouchMove( event ); } } /** * Convert pointer up to touch end. */ function onPointerUp( event ) { if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) { event.touches = [{ clientX: event.clientX, clientY: event.clientY }]; onTouchEnd( event ); } } /** * Handles mouse wheel scrolling, throttled to avoid skipping * multiple slides. */ function onDocumentMouseScroll( event ) { if( Date.now() - lastMouseWheelStep > 600 ) { lastMouseWheelStep = Date.now(); var delta = event.detail || -event.wheelDelta; if( delta > 0 ) { navigateNext(); } else { navigatePrev(); } } } /** * Clicking on the progress bar results in a navigation to the * closest approximate horizontal slide using this equation: * * ( clickX / presentationWidth ) * numberOfSlides */ function onProgressClicked( event ) { onUserInput( event ); event.preventDefault(); var slidesTotal = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).length; var slideIndex = Math.floor( ( event.clientX / dom.wrapper.offsetWidth ) * slidesTotal ); if( config.rtl ) { slideIndex = slidesTotal - slideIndex; } slide( slideIndex ); } /** * Event handler for navigation control buttons. */ function onNavigateLeftClicked( event ) { event.preventDefault(); onUserInput(); navigateLeft(); } function onNavigateRightClicked( event ) { event.preventDefault(); onUserInput(); navigateRight(); } function onNavigateUpClicked( event ) { event.preventDefault(); onUserInput(); navigateUp(); } function onNavigateDownClicked( event ) { event.preventDefault(); onUserInput(); navigateDown(); } function onNavigatePrevClicked( event ) { event.preventDefault(); onUserInput(); navigatePrev(); } function onNavigateNextClicked( event ) { event.preventDefault(); onUserInput(); navigateNext(); } /** * Handler for the window level 'hashchange' event. */ function onWindowHashChange( event ) { readURL(); } /** * Handler for the window level 'resize' event. */ function onWindowResize( event ) { layout(); } /** * Handle for the window level 'visibilitychange' event. */ function onPageVisibilityChange( event ) { var isHidden = document.webkitHidden || document.msHidden || document.hidden; // If, after clicking a link or similar and we're coming back, // focus the document.body to ensure we can use keyboard shortcuts if( isHidden === false && document.activeElement !== document.body ) { // Not all elements support .blur() - SVGs among them. if( typeof document.activeElement.blur === 'function' ) { document.activeElement.blur(); } document.body.focus(); } } /** * Invoked when a slide is and we're in the overview. */ function onOverviewSlideClicked( event ) { // TODO There's a bug here where the event listeners are not // removed after deactivating the overview. if( eventsAreBound && isOverview() ) { event.preventDefault(); var element = event.target; while( element && !element.nodeName.match( /section/gi ) ) { element = element.parentNode; } if( element && !element.classList.contains( 'disabled' ) ) { deactivateOverview(); if( element.nodeName.match( /section/gi ) ) { var h = parseInt( element.getAttribute( 'data-index-h' ), 10 ), v = parseInt( element.getAttribute( 'data-index-v' ), 10 ); slide( h, v ); } } } } /** * Handles clicks on links that are set to preview in the * iframe overlay. */ function onPreviewLinkClicked( event ) { if( event.currentTarget && event.currentTarget.hasAttribute( 'href' ) ) { var url = event.currentTarget.getAttribute( 'href' ); if( url ) { showPreview( url ); event.preventDefault(); } } } /** * Handles click on the auto-sliding controls element. */ function onAutoSlidePlayerClick( event ) { // Replay if( Reveal.isLastSlide() && config.loop === false ) { slide( 0, 0 ); resumeAutoSlide(); } // Resume else if( autoSlidePaused ) { resumeAutoSlide(); } // Pause else { pauseAutoSlide(); } } // --------------------------------------------------------------------// // ------------------------ PLAYBACK COMPONENT ------------------------// // --------------------------------------------------------------------// /** * Constructor for the playback component, which displays * play/pause/progress controls. * * @param {HTMLElement} container The component will append * itself to this * @param {Function} progressCheck A method which will be * called frequently to get the current progress on a range * of 0-1 */ function Playback( container, progressCheck ) { // Cosmetics this.diameter = 100; this.diameter2 = this.diameter/2; this.thickness = 6; // Flags if we are currently playing this.playing = false; // Current progress on a 0-1 range this.progress = 0; // Used to loop the animation smoothly this.progressOffset = 1; this.container = container; this.progressCheck = progressCheck; this.canvas = document.createElement( 'canvas' ); this.canvas.className = 'playback'; this.canvas.width = this.diameter; this.canvas.height = this.diameter; this.canvas.style.width = this.diameter2 + 'px'; this.canvas.style.height = this.diameter2 + 'px'; this.context = this.canvas.getContext( '2d' ); this.container.appendChild( this.canvas ); this.render(); } Playback.prototype.setPlaying = function( value ) { var wasPlaying = this.playing; this.playing = value; // Start repainting if we weren't already if( !wasPlaying && this.playing ) { this.animate(); } else { this.render(); } }; Playback.prototype.animate = function() { var progressBefore = this.progress; this.progress = this.progressCheck(); // When we loop, offset the progress so that it eases // smoothly rather than immediately resetting if( progressBefore > 0.8 && this.progress < 0.2 ) { this.progressOffset = this.progress; } this.render(); if( this.playing ) { features.requestAnimationFrameMethod.call( window, this.animate.bind( this ) ); } }; /** * Renders the current progress and playback state. */ Playback.prototype.render = function() { var progress = this.playing ? this.progress : 0, radius = ( this.diameter2 ) - this.thickness, x = this.diameter2, y = this.diameter2, iconSize = 28; // Ease towards 1 this.progressOffset += ( 1 - this.progressOffset ) * 0.1; var endAngle = ( - Math.PI / 2 ) + ( progress * ( Math.PI * 2 ) ); var startAngle = ( - Math.PI / 2 ) + ( this.progressOffset * ( Math.PI * 2 ) ); this.context.save(); this.context.clearRect( 0, 0, this.diameter, this.diameter ); // Solid background color this.context.beginPath(); this.context.arc( x, y, radius + 4, 0, Math.PI * 2, false ); this.context.fillStyle = 'rgba( 0, 0, 0, 0.4 )'; this.context.fill(); // Draw progress track this.context.beginPath(); this.context.arc( x, y, radius, 0, Math.PI * 2, false ); this.context.lineWidth = this.thickness; this.context.strokeStyle = '#666'; this.context.stroke(); if( this.playing ) { // Draw progress on top of track this.context.beginPath(); this.context.arc( x, y, radius, startAngle, endAngle, false ); this.context.lineWidth = this.thickness; this.context.strokeStyle = '#fff'; this.context.stroke(); } this.context.translate( x - ( iconSize / 2 ), y - ( iconSize / 2 ) ); // Draw play/pause icons if( this.playing ) { this.context.fillStyle = '#fff'; this.context.fillRect( 0, 0, iconSize / 2 - 4, iconSize ); this.context.fillRect( iconSize / 2 + 4, 0, iconSize / 2 - 4, iconSize ); } else { this.context.beginPath(); this.context.translate( 4, 0 ); this.context.moveTo( 0, 0 ); this.context.lineTo( iconSize - 4, iconSize / 2 ); this.context.lineTo( 0, iconSize ); this.context.fillStyle = '#fff'; this.context.fill(); } this.context.restore(); }; Playback.prototype.on = function( type, listener ) { this.canvas.addEventListener( type, listener, false ); }; Playback.prototype.off = function( type, listener ) { this.canvas.removeEventListener( type, listener, false ); }; Playback.prototype.destroy = function() { this.playing = false; if( this.canvas.parentNode ) { this.container.removeChild( this.canvas ); } }; // --------------------------------------------------------------------// // ------------------------------- API --------------------------------// // --------------------------------------------------------------------// Reveal = { VERSION: VERSION, initialize: initialize, configure: configure, sync: sync, // Navigation methods slide: slide, left: navigateLeft, right: navigateRight, up: navigateUp, down: navigateDown, prev: navigatePrev, next: navigateNext, // Fragment methods navigateFragment: navigateFragment, prevFragment: previousFragment, nextFragment: nextFragment, // Deprecated aliases navigateTo: slide, navigateLeft: navigateLeft, navigateRight: navigateRight, navigateUp: navigateUp, navigateDown: navigateDown, navigatePrev: navigatePrev, navigateNext: navigateNext, // Forces an update in slide layout layout: layout, // Randomizes the order of slides shuffle: shuffle, // Returns an object with the available routes as booleans (left/right/top/bottom) availableRoutes: availableRoutes, // Returns an object with the available fragments as booleans (prev/next) availableFragments: availableFragments, // Toggles the overview mode on/off toggleOverview: toggleOverview, // Toggles the "black screen" mode on/off togglePause: togglePause, // Toggles the auto slide mode on/off toggleAutoSlide: toggleAutoSlide, // State checks isOverview: isOverview, isPaused: isPaused, isAutoSliding: isAutoSliding, // Adds or removes all internal event listeners (such as keyboard) addEventListeners: addEventListeners, removeEventListeners: removeEventListeners, // Facility for persisting and restoring the presentation state getState: getState, setState: setState, // Presentation progress on range of 0-1 getProgress: getProgress, // Returns the indices of the current, or specified, slide getIndices: getIndices, getTotalSlides: getTotalSlides, // Returns the slide element at the specified index getSlide: getSlide, // Returns the slide background element at the specified index getSlideBackground: getSlideBackground, // Returns the speaker notes string for a slide, or null getSlideNotes: getSlideNotes, // Returns the previous slide element, may be null getPreviousSlide: function() { return previousSlide; }, // Returns the current slide element getCurrentSlide: function() { return currentSlide; }, // Returns the current scale of the presentation content getScale: function() { return scale; }, // Returns the current configuration object getConfig: function() { return config; }, // Helper method, retrieves query string as a key/value hash getQueryHash: function() { var query = {}; location.search.replace( /[A-Z0-9]+?=([\w\.%-]*)/gi, function(a) { query[ a.split( '=' ).shift() ] = a.split( '=' ).pop(); } ); // Basic deserialization for( var i in query ) { var value = query[ i ]; query[ i ] = deserialize( unescape( value ) ); } return query; }, // Returns true if we're currently on the first slide isFirstSlide: function() { return ( indexh === 0 && indexv === 0 ); }, // Returns true if we're currently on the last slide isLastSlide: function() { if( currentSlide ) { // Does this slide has next a sibling? if( currentSlide.nextElementSibling ) return false; // If it's vertical, does its parent have a next sibling? if( isVerticalSlide( currentSlide ) && currentSlide.parentNode.nextElementSibling ) return false; return true; } return false; }, // Checks if reveal.js has been loaded and is ready for use isReady: function() { return loaded; }, // Forward event binding to the reveal DOM element addEventListener: function( type, listener, useCapture ) { if( 'addEventListener' in window ) { ( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture ); } }, removeEventListener: function( type, listener, useCapture ) { if( 'addEventListener' in window ) { ( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture ); } }, // Programatically triggers a keyboard event triggerKey: function( keyCode ) { onDocumentKeyDown( { keyCode: keyCode } ); }, // Registers a new shortcut to include in the help overlay registerKeyboardShortcut: function( key, value ) { keyboardShortcuts[key] = value; } }; return Reveal; }));
var express = require('express'); var app = express(); app.use('/', express.static(__dirname + '/src', { maxAge: 31536000000 })); app.listen(process.env.PORT || 3000); console.log("Server running ...");
/** * Populate an association * GET /:model/:parentId/:relation * GET /:model/:parentId/:relation/:id * * Expand response with populated data from relations in models. */ module.exports = require('sails/lib/hooks/blueprints/actions/populate');
/*global tarteaucitron */ tarteaucitron.lang = { "middleBarHead": "☝ 🍪", "adblock": "Merhaba! Bu site şeffaflıkla oynar ve size etkinleştirilecek üçüncü taraf hizmetleri seçeneği sunar.", "adblock_call": "Kişiselleştirmeye başlamak için lütfen reklam engelleyicinizi devre dışı bırakın.", "reload": "Sayfayı yeniden yükle", "alertBigScroll": "Kaydırma devam edien,", "alertBigClick": "Navigasyonunuza devam ederek,", "alertBig": "çerez yükleyebilecek üçüncü taraf hizmetlerinin kullanımını kabul edersiniz", "alertBigPrivacy": "Bu site çerezleri kullanır ve etkinleştirmek istediklerinizi kontrol etmenizi sağlar", "alertSmall": "Hizmet yönetimi", "acceptAll": "evet, her şeyi kabul edin", "personalize": "kişiselleştirmek", "close": "kapat", "privacyUrl": "Gizlilik Politikası", "all": "Tüm hizmetler için tercihler", "info": "Gizliliğinin korunması", "disclaimer": "Bu üçüncü taraf hizmetlerini yetkilendirerek, çerezlerin depolanmasını ve okunmasını ve düzgün çalışması için gerekli izleme teknolojilerinin kullanımını kabul ediyorsunuz.", "allow": "izin", "deny": "yasak", "noCookie": "Bu hizmet çerez yerleştirmez.", "useCookie": "Bu hizmet para yatırabilir", "useCookieCurrent": "Bu hizmet sunuldu", "useNoCookie": "Bu hizmet herhangi bir çerez yerleştirmedi.", "more": "Daha fazlasını öğrenin", "source": "web sitesine bakın", "credit": "Çerez yönetimi tarteaucitron.js", "noServices": "Bu site, onayınızı gerektiren hiçbir çerez kullanmıyor.", "toggleInfoBox": "Çerezlerin depolanmasıyla ilgili bilgileri göster / gizle", "title": "Çerez yönetimi paneli", "cookieDetail": "Ayrıntı çerezleri", "ourSite": "sitemizde", "modalWindow": "(kalıcı pencere)", "newWindow": "(yeni pencere)", "allowAll": "Tüm çerezlere izin verin", "denyAll": "Tüm çerezleri yasaklayın", "icon": "Cookies", "fallback": "devre dışı.", "allowed": "izin verildi", "disallowed": "izin verilmeyen", "ads": { "title": "Reklam yönetimi", "details": "Reklam ajansları, sitedeki reklam alanını pazarlayarak gelir elde etmenizi sağlar." }, "analytic": { "title": "Kitle ölçümü", "details": "Kitle ölçüm hizmetleri, siteyi geliştirmek için yararlı katılım istatistikleri oluşturur." }, "social": { "title": "Sosyal Medya", "details": "Sosyal ağlar sitenin kullanım kolaylığını geliştirir ve paylaşım yoluyla sitenin tanıtımına yardımcı olur." }, "video": { "title": "Videolar", "details": "Video paylaşım hizmetleri siteyi multimedya içeriğiyle zenginleştirir ve görünürlüğünü artırır.\n" + "\n" }, "comment": { "title": "yorumlar\n", "details": "Yorum yöneticileri yorumlarınızın gönderilmesini kolaylaştırır ve spam ile mücadele eder.", }, "support": { "title": "destek", "details": "Destek hizmetleri, site ekibiyle iletişim kurmanıza ve ekibinizi geliştirmenize yardımcı olur.\n" + "\n" }, "api": { "title": "APIs", "details": "APIs komut dosyalarının yüklenmesine izin verir: coğrafi konum, arama motorları, çeviriler, ..." }, "other": { "title": "diğer\n", "details": "Web içeriğini görüntüleme hizmetleri." }, "mandatoryTitle": "Mandatory cookies", "mandatoryText": "This site uses cookies necessary for its proper functioning which cannot be deactivated." };
if(!dojo._hasResource["dojox.dtl.utils.date"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["dojox.dtl.utils.date"] = true; dojo.provide("dojox.dtl.utils.date"); dojo.require("dojox.date.php"); dojox.dtl.utils.date.DateFormat = function(/*String*/ format){ dojox.date.php.DateFormat.call(this, format); } dojo.extend(dojox.dtl.utils.date.DateFormat, dojox.date.php.DateFormat.prototype, { f: function(){ // summary: // Time, in 12-hour hours and minutes, with minutes left off if they're zero. // description: // Examples: '1', '1:30', '2:05', '2' // Proprietary extension. return (!this.date.getMinutes()) ? this.g() : this.g() + ":" + this.i(); }, N: function(){ // summary: Month abbreviation in Associated Press style. Proprietary extension. return dojox.dtl.utils.date._months_ap[this.date.getMonth()]; }, P: function(){ // summary: // Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off // if they're zero and the strings 'midnight' and 'noon' if appropriate. // description: // Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.' // Proprietary extension. if(!this.date.getMinutes() && !this.date.getHours()) return 'midnight'; if(!this.date.getMinutes() && this.date.getHours() == 12) return 'noon'; return this.f() + " " + this.a(); } }); dojo.mixin(dojox.dtl.utils.date, { format: function(/*Date*/ date, /*String*/ format){ var df = new dojox.dtl.utils.date.DateFormat(format); return df.format(date); }, timesince: function(d, now){ // summary: // Takes two datetime objects and returns the time between then and now // as a nicely formatted string, e.g "10 minutes" // description: // Adapted from http://blog.natbat.co.uk/archive/2003/Jun/14/time_since if(!(d instanceof Date)){ d = new Date(d.year, d.month, d.day); } if(!now){ now = new Date(); } var delta = Math.abs(now.getTime() - d.getTime()); for(var i = 0, chunk; chunk = dojox.dtl.utils.date._chunks[i]; i++){ var count = Math.floor(delta / chunk[0]); if(count) break; } return count + " " + chunk[1](count); }, _chunks: [ [60 * 60 * 24 * 365 * 1000, function(n){ return (n == 1) ? 'year' : 'years'; }], [60 * 60 * 24 * 30 * 1000, function(n){ return (n == 1) ? 'month' : 'months'; }], [60 * 60 * 24 * 7 * 1000, function(n){ return (n == 1) ? 'week' : 'weeks'; }], [60 * 60 * 24 * 1000, function(n){ return (n == 1) ? 'day' : 'days'; }], [60 * 60 * 1000, function(n){ return (n == 1) ? 'hour' : 'hours'; }], [60 * 1000, function(n){ return (n == 1) ? 'minute' : 'minutes'; }] ], _months_ap: ["Jan.", "Feb.", "March", "April", "May", "June", "July", "Aug.", "Sept.", "Oct.", "Nov.", "Dec."] }); }
/* eslint-disable consistent-return, jsx-a11y/no-noninteractive-tabindex */ import * as React from 'react'; import * as ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import ownerDocument from '../utils/ownerDocument'; import useForkRef from '../utils/useForkRef'; /** * @ignore - internal component. */ function TrapFocus(props) { var children = props.children, _props$disableAutoFoc = props.disableAutoFocus, disableAutoFocus = _props$disableAutoFoc === void 0 ? false : _props$disableAutoFoc, _props$disableEnforce = props.disableEnforceFocus, disableEnforceFocus = _props$disableEnforce === void 0 ? false : _props$disableEnforce, _props$disableRestore = props.disableRestoreFocus, disableRestoreFocus = _props$disableRestore === void 0 ? false : _props$disableRestore, getDoc = props.getDoc, isEnabled = props.isEnabled, open = props.open; var ignoreNextEnforceFocus = React.useRef(); var sentinelStart = React.useRef(null); var sentinelEnd = React.useRef(null); var nodeToRestore = React.useRef(); var rootRef = React.useRef(null); // can be removed once we drop support for non ref forwarding class components var handleOwnRef = React.useCallback(function (instance) { // #StrictMode ready rootRef.current = ReactDOM.findDOMNode(instance); }, []); var handleRef = useForkRef(children.ref, handleOwnRef); // ⚠️ You may rely on React.useMemo as a performance optimization, not as a semantic guarantee. // https://reactjs.org/docs/hooks-reference.html#usememo React.useMemo(function () { if (!open || typeof window === 'undefined') { return; } nodeToRestore.current = getDoc().activeElement; }, [open]); // eslint-disable-line react-hooks/exhaustive-deps React.useEffect(function () { if (!open) { return; } var doc = ownerDocument(rootRef.current); // We might render an empty child. if (!disableAutoFocus && rootRef.current && !rootRef.current.contains(doc.activeElement)) { if (!rootRef.current.hasAttribute('tabIndex')) { if (process.env.NODE_ENV !== 'production') { console.error(['Material-UI: the modal content node does not accept focus.', 'For the benefit of assistive technologies, ' + 'the tabIndex of the node is being set to "-1".'].join('\n')); } rootRef.current.setAttribute('tabIndex', -1); } rootRef.current.focus(); } var contain = function contain() { if (disableEnforceFocus || !isEnabled() || ignoreNextEnforceFocus.current) { ignoreNextEnforceFocus.current = false; return; } if (rootRef.current && !rootRef.current.contains(doc.activeElement)) { rootRef.current.focus(); } }; var loopFocus = function loopFocus(event) { // 9 = Tab if (disableEnforceFocus || !isEnabled() || event.keyCode !== 9) { return; } // Make sure the next tab starts from the right place. if (doc.activeElement === rootRef.current) { // We need to ignore the next contain as // it will try to move the focus back to the rootRef element. ignoreNextEnforceFocus.current = true; if (event.shiftKey) { sentinelEnd.current.focus(); } else { sentinelStart.current.focus(); } } }; doc.addEventListener('focus', contain, true); doc.addEventListener('keydown', loopFocus, true); // With Edge, Safari and Firefox, no focus related events are fired when the focused area stops being a focused area // e.g. https://bugzilla.mozilla.org/show_bug.cgi?id=559561. // // The whatwg spec defines how the browser should behave but does not explicitly mention any events: // https://html.spec.whatwg.org/multipage/interaction.html#focus-fixup-rule. var interval = setInterval(function () { contain(); }, 50); return function () { clearInterval(interval); doc.removeEventListener('focus', contain, true); doc.removeEventListener('keydown', loopFocus, true); // restoreLastFocus() if (!disableRestoreFocus) { // In IE 11 it is possible for document.activeElement to be null resulting // in nodeToRestore.current being null. // Not all elements in IE 11 have a focus method. // Once IE 11 support is dropped the focus() call can be unconditional. if (nodeToRestore.current && nodeToRestore.current.focus) { nodeToRestore.current.focus(); } nodeToRestore.current = null; } }; }, [disableAutoFocus, disableEnforceFocus, disableRestoreFocus, isEnabled, open]); return React.createElement(React.Fragment, null, React.createElement("div", { tabIndex: 0, ref: sentinelStart, "data-test": "sentinelStart" }), React.cloneElement(children, { ref: handleRef }), React.createElement("div", { tabIndex: 0, ref: sentinelEnd, "data-test": "sentinelEnd" })); } process.env.NODE_ENV !== "production" ? TrapFocus.propTypes = { /** * A single child content element. */ children: PropTypes.element.isRequired, /** * If `true`, the modal will not automatically shift focus to itself when it opens, and * replace it to the last focused element when it closes. * This also works correctly with any modal children that have the `disableAutoFocus` prop. * * Generally this should never be set to `true` as it makes the modal less * accessible to assistive technologies, like screen readers. */ disableAutoFocus: PropTypes.bool, /** * If `true`, the modal will not prevent focus from leaving the modal while open. * * Generally this should never be set to `true` as it makes the modal less * accessible to assistive technologies, like screen readers. */ disableEnforceFocus: PropTypes.bool, /** * If `true`, the modal will not restore focus to previously focused element once * modal is hidden. */ disableRestoreFocus: PropTypes.bool, /** * Return the document to consider. * We use it to implement the restore focus between different browser documents. */ getDoc: PropTypes.func.isRequired, /** * Do we still want to enforce the focus? * This prop helps nesting TrapFocus elements. */ isEnabled: PropTypes.func.isRequired, /** * If `true`, the modal is open. */ open: PropTypes.bool.isRequired } : void 0; /* In the future, we should be able to replace TrapFocus with: https://github.com/facebook/react/blob/master/packages/react-events/docs/FocusScope.md ```jsx import FocusScope from 'react-dom/FocusScope'; function TrapFocus(props) { const { children disableAutoFocus = false, disableEnforceFocus = false, disableRestoreFocus = false, open, } = props; if (!open) { return children; } return ( <FocusScope autoFocus={!disableAutoFocus} contain={!disableEnforceFocus} restoreFocus={!disableRestoreFocus} > {children} </FocusScope> ); } ``` */ export default TrapFocus;
CKEDITOR.plugins.setLang("docprops","sv",{bgColor:"Bakgrundsfärg",bgFixed:"Fast bakgrund",bgImage:"Bakgrundsbildens URL",charset:"Teckenuppsättningar",charsetASCII:"ASCII",charsetCE:"Central Europa",charsetCR:"Kyrillisk",charsetCT:"Traditionell Kinesisk (Big5)",charsetGR:"Grekiska",charsetJP:"Japanska",charsetKR:"Koreanska",charsetOther:"Övriga teckenuppsättningar",charsetTR:"Turkiska",charsetUN:"Unicode (UTF-8)",charsetWE:"Väst Europa",chooseColor:"Välj",design:"Design",docTitle:"Sidtitel",docType:"Sidhuvud", docTypeOther:"Övriga sidhuvuden",label:"Dokumentegenskaper",margin:"Sidmarginal",marginBottom:"Botten",marginLeft:"Vänster",marginRight:"Höger",marginTop:"Topp",meta:"Metadata",metaAuthor:"Författare",metaCopyright:"Upphovsrätt",metaDescription:"Sidans beskrivning",metaKeywords:"Sidans nyckelord (kommaseparerade)",other:"Annan...",previewHtml:'<p>Detta är en <strong>exempel text</strong>. Du använder <a href="javascript:void(0)">CKEditor</a>.</p>',title:"Dokumentegenskaper",txtColor:"Textfärg",xhtmlDec:"Inkludera XHTML deklaration"});
suite('ViewQueue', function() { setup(function(){ wdi.Debug.debug = false; //disable debugging, it slows tests }); suite('#getLength()', function() { test('Should return 0 for empty queue', function() { var q = new wdi.ViewQueue(); assert.strictEqual(q.getLength(), 0); }); }); suite('#push()', function() { setup(function() { this.q = new wdi.ViewQueue(); }); test('Should be able to add elements as string', function() { this.q.push('hello'); assert.strictEqual(this.q.getLength(), 5); }); test('Should be able to add arrays', function() { this.q.push([1,2,3,4,5]); assert.strictEqual(this.q.getLength(), 5); }); test('Should be able to push multiple arrays', function() { this.q.push([1,2,3,4,5]); this.q.push([1,2,3,4,5]); assert.strictEqual(this.q.getLength(), 10); }); }); suite('#shift()', function() { setup(function() { this.q = new wdi.ViewQueue(); this.q.push([1,2,3,4,5]); }); test('Should allways return array', function() { var element = this.q.shift(1); assert.isArray(element); }); test('Should read parts of the queue', function() { var elements = this.q.shift(2); assert.deepEqual(elements, [1,2]); }); test('Should read all the queue', function() { var elements = this.q.shift(5); assert.deepEqual(elements, [1,2,3,4,5]); }); test('Should empty all the queue', function() { var elements = this.q.shift(5); assert.strictEqual(this.q.getLength(), 0); }); test('Should empty parts of the queue', function() { var elements = this.q.shift(2); assert.strictEqual(this.q.getLength(), 3); }); }); suite('#peek()', function() { setup(function() { this.q = new wdi.ViewQueue(); this.q.push([1,2,3,4,5]); }); test('Should read a single element', function() { var element = this.q.peek(0, 1); assert.deepEqual(element, [1]); }); test('Should read 3 elements of the queue', function() { var elements = this.q.peek(1, 4); assert.deepEqual(elements, [2,3,4]); }); test('Should read all the elements of the queue', function() { var elements = this.q.peek(0); assert.deepEqual(elements, [1,2,3,4,5]); }); test('Should be immutable', function() { this.q.peek(1, 4); assert.strictEqual(this.q.getLength(), 5); }); }); });
version https://git-lfs.github.com/spec/v1 oid sha256:138071c9db4b470525a8ede2b8dd26a4a62cca564c6a50323d1590d010a5a8ae size 725
var expect = this.chai.expect; describe('Views.Page', function () { var model; var view; before(function () { model = new Backbone.Model({ message: 'Hello world' }); view = new Application.Views.Page({ model: model, template: _.template('<span>{{message}}</span>') }); }); it('can activate', function () { expect(view).to.respondTo('activate'); }); it('can deactivate', function () { expect(view).to.respondTo('deactivate'); }); it('renders model attributes', function () { expect(view.render().$el.html()).to.contain(model.get('message')); }); });
steal('funcunit/qunit','jquery/lang/observe',function(){ module('jquery/lang/observe/delegate') var matches = $.Observe.prototype.delegate.matches; test("matches", function(){ equals( matches(['**'], ['foo','bar','0']) , 'foo.bar.0' , "everything" ); equals( matches(['*.**'], ['foo']) , null , "everything at least one level deep" ) equals( matches(['foo','*'], ['foo','bar','0']) , 'foo.bar' ) equals(matches(['*'], ['foo','bar','0']) , 'foo' ); equals( matches([ '*', 'bar' ], ['foo','bar','0']) , 'foo.bar' ) // - props - // - returns - 'foo.bar' }) test("list events", function(){ return; var list = new $.Observe.List([ {name: 'Justin'}, {name: 'Brian'}, {name: 'Austin'}, {name: 'Mihael'}]) list.comparator = 'name'; list.sort(); // events on a list // - move - item from one position to another // due to changes in elements that change the sort order // - add (items added to a list) // - remove (items removed from a list) // - reset (all items removed from the list) // - change something happened // a move directly on this list list.bind('move', function(ev, item, newPos, oldPos){ ok(true,"move called"); equals(item.name, "Zed"); equals(newPos, 3); equals(oldPos, 0); }); // a remove directly on this list list.bind('remove', function(ev, items, oldPos){ ok(true,"remove called"); equals(items.length,1); equals(items[0].name, 'Alexis'); equals(oldPos, 0, "put in right spot") }) list.bind('add', function(ev, items, newPos){ ok(true,"add called"); equals(items.length,1); equals(items[0].name, 'Alexis'); equals(newPos, 0, "put in right spot") }); list.push({name: 'Alexis'}); // now lets remove alexis ... list.splice(0,1); list[0].attr('name',"Zed") }) test("delegate", 4,function(){ var state = new $.Observe({ properties : { prices : [] } }); var prices = state.attr('properties.prices'); state.delegate("properties.prices","change", function(ev, attr, how, val, old){ equals(attr, "0", "correct change name") equals(how, "add") equals(val[0].attr("foo"),"bar", "correct") ok(this === prices, "rooted element") }); prices.push({foo: "bar"}); state.undelegate(); }) test("delegate on add", 2, function(){ var state = new $.Observe({}); state.delegate("foo","add", function(ev, newVal){ ok(true, "called"); equals(newVal, "bar","got newVal") }).delegate("foo","remove", function(){ ok(false,"remove should not be called") }); state.attr("foo","bar") }) test("delegate set is called on add", 2, function(){ var state = new $.Observe({}); state.delegate("foo","set", function(ev, newVal){ ok(true, "called"); equals(newVal, "bar","got newVal") }); state.attr("foo","bar") }); test("delegate's this", 5, function(){ var state = new $.Observe({ person : { name : { first : "justin", last : "meyer" } }, prop : "foo" }); var n = state.attr('person.name'), check // listen to person name changes state.delegate("person.name","set", check = function(ev, newValue, oldVal, from){ // make sure we are getting back the person.name equals(this, n) equals(newValue, "Brian"); equals(oldVal, "justin"); // and how to get there equals(from,"first") }); n.attr('first',"Brian"); state.undelegate("person.name",'set',check) // stop listening // now listen to changes in prop state.delegate("prop","set", function(){ equals(this, 'food'); }); // this is weird, probably need to support direct bind ... // update the prop state.attr('prop','food') }) test("delegate on deep properties with *", function(){ var state = new $.Observe({ person : { name : { first : "justin", last : "meyer" } } }); state.delegate("person","set", function(ev, newVal, oldVal, attr){ equals(this, state.attr('person'), "this is set right") equals(attr, "name.first") }); state.attr("person.name.first","brian") }); test("compound sets", function(){ var state = new $.Observe({ type : "person", id: "5" }); var count = 0; state.delegate("type=person id","set", function(){ equals(state.type, "person","type is person") ok(state.id !== undefined, "id has value"); count++; }) // should trigger a change state.attr("id",0); equals(count, 1, "changing the id to 0 caused a change"); // should not fire a set state.removeAttr("id") equals(count, 1, "removing the id changed nothing"); state.attr("id",3) equals(count, 2, "adding an id calls callback"); state.attr("type","peter") equals(count, 2, "changing the type does not fire callback"); state.removeAttr("type"); state.removeAttr("id"); equals(count, 2, ""); state.attr({ type : "person", id: "5" }); equals(count, 3, "setting person and id only fires 1 event"); state.removeAttr("type"); state.removeAttr("id"); state.attr({ type : "person" }); equals(count, 3, "setting person does not fire anything"); }) test("undelegate within event loop",1, function(){ var state = new $.Observe({ type : "person", id: "5" }); var f1 = function(){ state.undelegate("type","add",f2); }, f2 = function(){ ok(false,"I am removed, how am I called") }, f3 = function(){ state.undelegate("type","add",f1); }, f4 = function(){ ok(true,"f4 called") }; state.delegate("type", "set", f1); state.delegate("type","set",f2); state.delegate("type","set",f3); state.delegate("type","set",f4); state.attr("type","other"); }) });
/** * Collection: Administrators of a Dashboard * */ var Users = require('./Users'), User = require('./User'); module.exports = Users.extend({ model: User, idAttribute: "_id", url: function(){ return hackdash.apiURL + '/' + this.domain + '/admins'; }, addAdmin: function(userId){ $.ajax({ url: this.url() + '/' + userId, type: "POST", context: this }).done(function(user){ this.add(user); }); }, });
import React, { useEffect } from 'react'; import Header from '../../../components/Header'; import { useEndpoint } from '../../../contexts/ServerContext'; import { AsyncStatePhase, useAsyncState } from '../../../hooks/useAsyncState'; import ParentRoom from './ParentRoom'; const ParentRoomWithEndpointData = ({ rid }) => { const { resolve, reject, reset, phase, value } = useAsyncState(); const getData = useEndpoint('GET', 'rooms.info'); useEffect(() => { (async () => { reset(); getData({ roomId: rid }) .then(resolve) .catch((error) => { reject(error); }); })(); }, [reset, getData, rid, resolve, reject]); if (AsyncStatePhase.LOADING === phase) { return <Header.Tag.Skeleton />; } if (AsyncStatePhase.ERROR === phase || !value?.room) { return null; } return <ParentRoom room={value.room} />; }; export default ParentRoomWithEndpointData;
// Write a function that returns the specified string in uppercase // Parameter S is a String. function uppercase(s) { var result = s.toUpperCase(); return result; } module.exports = uppercase;
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is JavaScript Engine testing utilities. * * The Initial Developer of the Original Code is * Mozilla Foundation. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor(s): Brendan Eich * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ var gTestfile = 'regress-465220.js'; //----------------------------------------------------------------------------- var BUGNUMBER = 465220; var summary = 'Do not assert: anti-nesting'; var actual = ''; var expect = ''; //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function test() { enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); expect = 'TypeError: can\'t convert o to primitive type'; jit(true); try { var o = {toString: function()(i > 2) ? this : "foo"}; var s = ""; for (var i = 0; i < 5; i++) s += o + o; print(s); actual = 'No Exception'; } catch(ex) { actual = 'TypeError: can\'t convert o to primitive type'; } jit(false); reportCompare(expect, actual, summary); exitFunc ('test'); }
import r from 'restructure'; // An array of predefined values accessible by instructions export default new r.Struct({ controlValues: new r.Array(r.int16) });
var axon = require('..') , should = require('should'); var req = axon.socket('req') , rep = axon.socket('rep'); req.bind(4000); rep.connect(4000); rep.on('message', function(msg, reply){ reply('got "' + msg + '"', function(){ req.close(); rep.close(); }); }); req.send('hello');